File size: 471,337 Bytes
2bc1566 8b2b6f0 2bc1566 8b2b6f0 2bc1566 8b2b6f0 2bc1566 8b2b6f0 2bc1566 8b2b6f0 2bc1566 8b2b6f0 2bc1566 8b2b6f0 2bc1566 8b2b6f0 2bc1566 4df0320 2bc1566 4df0320 2bc1566 8b2b6f0 2bc1566 8b2b6f0 2bc1566 8b2b6f0 2bc1566 8b2b6f0 2bc1566 8b2b6f0 2bc1566 8b2b6f0 2bc1566 8b2b6f0 2bc1566 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209 7210 7211 7212 7213 7214 7215 7216 7217 7218 7219 7220 7221 7222 7223 7224 7225 7226 7227 7228 7229 7230 7231 7232 7233 7234 7235 7236 7237 7238 7239 7240 7241 7242 7243 7244 7245 7246 7247 7248 7249 7250 7251 7252 7253 7254 7255 7256 7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267 7268 7269 7270 7271 7272 7273 7274 7275 7276 7277 7278 7279 7280 7281 7282 7283 7284 7285 7286 7287 7288 7289 7290 7291 7292 7293 7294 7295 7296 7297 7298 7299 7300 7301 7302 7303 7304 7305 7306 7307 7308 7309 7310 7311 7312 7313 7314 7315 7316 7317 7318 7319 7320 7321 7322 7323 7324 7325 7326 7327 7328 7329 7330 7331 7332 7333 7334 7335 7336 7337 7338 7339 7340 7341 7342 7343 7344 7345 7346 7347 7348 7349 7350 7351 7352 7353 7354 7355 7356 7357 7358 7359 7360 7361 7362 7363 7364 7365 7366 7367 7368 7369 7370 7371 7372 7373 7374 7375 7376 7377 7378 7379 7380 7381 7382 7383 7384 7385 7386 7387 7388 7389 7390 7391 7392 7393 7394 7395 7396 7397 7398 7399 7400 7401 7402 7403 7404 7405 7406 7407 7408 7409 7410 7411 7412 7413 7414 7415 7416 7417 7418 7419 7420 7421 7422 7423 7424 7425 7426 7427 7428 7429 7430 7431 7432 7433 7434 7435 7436 7437 7438 7439 7440 7441 7442 7443 7444 7445 7446 7447 7448 7449 7450 7451 7452 7453 7454 7455 7456 7457 7458 7459 7460 7461 7462 7463 7464 7465 7466 7467 7468 7469 7470 7471 7472 7473 7474 7475 7476 7477 7478 7479 7480 7481 7482 7483 7484 7485 7486 7487 7488 7489 7490 7491 7492 7493 7494 7495 7496 7497 7498 7499 7500 7501 7502 7503 7504 7505 7506 7507 7508 7509 7510 7511 7512 7513 7514 7515 7516 7517 7518 7519 7520 7521 7522 7523 7524 7525 7526 7527 7528 7529 7530 7531 7532 7533 7534 7535 7536 7537 7538 7539 7540 7541 7542 7543 7544 7545 7546 7547 7548 7549 7550 7551 7552 7553 7554 7555 7556 7557 7558 7559 7560 7561 7562 7563 7564 7565 7566 7567 7568 7569 7570 7571 7572 7573 7574 7575 7576 7577 7578 7579 7580 7581 7582 7583 7584 7585 7586 7587 7588 7589 7590 7591 7592 7593 7594 7595 7596 7597 7598 7599 7600 7601 7602 7603 7604 7605 7606 7607 7608 7609 7610 7611 7612 7613 7614 7615 7616 7617 7618 7619 7620 7621 7622 7623 7624 7625 7626 7627 7628 7629 7630 7631 7632 7633 7634 7635 7636 7637 7638 7639 7640 7641 7642 7643 7644 7645 7646 7647 7648 7649 7650 7651 7652 7653 7654 7655 7656 7657 7658 7659 7660 7661 7662 7663 7664 7665 7666 7667 7668 7669 7670 7671 7672 7673 7674 7675 7676 7677 7678 7679 7680 7681 7682 7683 7684 7685 7686 7687 7688 7689 7690 7691 7692 7693 7694 7695 7696 7697 7698 7699 7700 7701 7702 7703 7704 7705 7706 7707 7708 7709 7710 7711 7712 7713 7714 7715 7716 7717 7718 7719 7720 7721 7722 7723 7724 7725 7726 7727 7728 7729 7730 7731 7732 7733 7734 7735 7736 7737 7738 7739 7740 7741 7742 7743 7744 7745 7746 7747 7748 7749 7750 7751 7752 7753 7754 7755 7756 7757 7758 7759 7760 7761 7762 7763 7764 7765 7766 7767 7768 7769 7770 7771 7772 7773 7774 7775 7776 7777 7778 7779 7780 7781 7782 7783 7784 7785 7786 7787 7788 7789 7790 7791 7792 7793 7794 7795 7796 7797 7798 7799 7800 7801 7802 7803 7804 7805 7806 7807 7808 7809 7810 7811 7812 7813 7814 7815 7816 7817 7818 7819 7820 7821 7822 7823 7824 7825 7826 7827 7828 7829 7830 7831 7832 7833 7834 7835 7836 7837 7838 7839 7840 7841 7842 7843 7844 7845 7846 7847 7848 7849 7850 7851 7852 7853 7854 7855 7856 7857 7858 7859 7860 7861 7862 7863 7864 7865 7866 7867 7868 7869 7870 7871 7872 7873 7874 7875 7876 7877 7878 7879 7880 7881 7882 7883 7884 7885 7886 7887 7888 7889 7890 7891 7892 7893 7894 7895 7896 7897 7898 7899 7900 7901 7902 7903 7904 7905 7906 7907 7908 7909 7910 7911 7912 7913 7914 7915 7916 7917 7918 7919 7920 7921 7922 7923 7924 7925 7926 7927 7928 7929 7930 7931 7932 7933 7934 7935 7936 7937 7938 7939 7940 7941 7942 7943 7944 7945 7946 7947 7948 7949 7950 7951 7952 7953 7954 7955 7956 7957 7958 7959 7960 7961 7962 7963 7964 7965 7966 7967 7968 7969 7970 7971 7972 7973 7974 7975 7976 7977 7978 7979 7980 7981 7982 7983 7984 7985 7986 7987 7988 7989 7990 7991 7992 7993 7994 7995 7996 7997 7998 7999 8000 8001 8002 8003 8004 8005 8006 8007 8008 8009 8010 8011 8012 8013 8014 8015 8016 8017 8018 8019 8020 8021 8022 8023 8024 8025 8026 8027 8028 8029 8030 8031 8032 8033 8034 8035 8036 8037 8038 8039 8040 8041 8042 8043 8044 8045 8046 8047 8048 8049 8050 8051 8052 8053 8054 8055 8056 8057 8058 8059 8060 8061 8062 8063 8064 8065 8066 8067 8068 8069 8070 8071 8072 8073 8074 8075 8076 8077 8078 8079 8080 8081 8082 8083 8084 8085 8086 8087 8088 8089 8090 8091 8092 8093 8094 8095 8096 8097 8098 8099 8100 8101 8102 8103 8104 8105 8106 8107 8108 8109 8110 8111 8112 8113 8114 8115 8116 8117 8118 8119 8120 8121 8122 8123 8124 8125 8126 8127 8128 8129 8130 8131 8132 8133 8134 8135 8136 8137 8138 8139 8140 8141 8142 8143 8144 8145 8146 8147 8148 8149 8150 8151 8152 8153 8154 8155 8156 8157 8158 8159 8160 8161 8162 8163 8164 8165 8166 8167 8168 8169 8170 8171 8172 8173 8174 8175 8176 8177 8178 8179 8180 8181 8182 8183 8184 8185 8186 8187 8188 8189 8190 8191 8192 8193 8194 8195 8196 8197 8198 8199 8200 8201 8202 8203 8204 8205 8206 8207 8208 8209 8210 8211 8212 8213 8214 8215 8216 8217 8218 8219 8220 8221 8222 8223 8224 8225 8226 8227 8228 8229 8230 8231 8232 8233 8234 8235 8236 8237 8238 8239 8240 8241 8242 8243 8244 8245 8246 8247 8248 8249 8250 8251 8252 8253 8254 8255 8256 8257 8258 8259 8260 8261 8262 8263 8264 8265 8266 8267 8268 8269 8270 8271 8272 8273 8274 8275 8276 8277 8278 8279 8280 8281 8282 8283 8284 8285 8286 8287 8288 8289 8290 8291 8292 8293 8294 8295 8296 8297 8298 8299 8300 8301 8302 8303 8304 8305 8306 8307 8308 8309 8310 8311 8312 8313 8314 8315 8316 8317 8318 8319 8320 8321 8322 8323 8324 8325 8326 8327 8328 8329 8330 8331 8332 8333 8334 8335 8336 8337 8338 8339 8340 8341 8342 8343 8344 8345 8346 8347 8348 8349 8350 8351 8352 8353 8354 8355 8356 8357 8358 8359 8360 8361 8362 8363 8364 8365 8366 8367 8368 8369 8370 8371 8372 8373 8374 8375 8376 8377 8378 8379 8380 8381 8382 8383 8384 8385 8386 8387 8388 8389 8390 8391 8392 8393 8394 8395 8396 8397 8398 8399 8400 8401 8402 8403 8404 8405 8406 8407 8408 8409 8410 8411 8412 8413 8414 8415 8416 8417 8418 8419 8420 8421 8422 8423 8424 8425 8426 8427 8428 8429 8430 8431 8432 8433 8434 8435 8436 8437 8438 8439 8440 8441 8442 8443 8444 8445 8446 8447 8448 8449 8450 8451 8452 8453 8454 8455 8456 8457 8458 8459 8460 8461 8462 8463 8464 8465 8466 8467 8468 8469 8470 8471 8472 8473 8474 8475 8476 8477 8478 8479 8480 8481 8482 8483 8484 8485 8486 8487 8488 8489 8490 8491 8492 8493 8494 8495 8496 8497 8498 8499 8500 8501 8502 8503 8504 8505 8506 8507 8508 8509 8510 8511 8512 8513 8514 8515 8516 8517 8518 8519 8520 8521 8522 8523 8524 8525 8526 8527 8528 8529 8530 8531 8532 8533 8534 8535 8536 8537 8538 8539 8540 8541 8542 8543 8544 8545 8546 8547 8548 8549 8550 8551 8552 8553 8554 8555 8556 8557 8558 8559 8560 8561 8562 8563 8564 8565 8566 8567 8568 8569 8570 8571 8572 8573 8574 8575 8576 8577 8578 8579 8580 8581 8582 8583 8584 8585 8586 8587 8588 8589 8590 8591 8592 8593 8594 8595 8596 8597 8598 8599 8600 8601 8602 8603 8604 8605 8606 8607 8608 8609 8610 8611 8612 8613 8614 8615 8616 8617 8618 8619 8620 8621 8622 8623 8624 8625 8626 8627 8628 8629 8630 8631 8632 8633 8634 8635 8636 8637 8638 8639 8640 8641 8642 8643 8644 8645 8646 8647 8648 8649 8650 8651 8652 8653 8654 8655 8656 8657 8658 8659 8660 8661 8662 8663 8664 8665 8666 8667 8668 8669 8670 8671 8672 8673 8674 8675 8676 8677 8678 8679 8680 8681 8682 8683 8684 8685 8686 8687 8688 8689 8690 8691 8692 8693 8694 8695 8696 8697 8698 8699 8700 8701 8702 8703 8704 8705 8706 8707 8708 8709 8710 8711 8712 8713 8714 8715 8716 8717 8718 8719 8720 8721 8722 8723 8724 8725 8726 8727 8728 8729 8730 8731 8732 8733 8734 8735 8736 8737 8738 8739 8740 8741 8742 8743 8744 8745 8746 8747 8748 8749 8750 8751 8752 8753 8754 8755 8756 8757 8758 8759 8760 8761 8762 8763 8764 8765 8766 8767 8768 8769 8770 8771 8772 8773 8774 8775 8776 8777 8778 8779 8780 8781 8782 8783 8784 8785 8786 8787 8788 8789 8790 8791 8792 8793 8794 8795 8796 8797 8798 8799 8800 8801 8802 8803 8804 8805 8806 8807 8808 8809 8810 8811 8812 8813 8814 8815 8816 8817 8818 8819 8820 8821 8822 8823 8824 8825 8826 8827 8828 8829 8830 8831 8832 8833 8834 8835 8836 8837 8838 8839 8840 8841 8842 8843 8844 8845 8846 8847 8848 8849 8850 8851 8852 8853 8854 8855 8856 8857 8858 8859 8860 8861 8862 8863 8864 8865 8866 8867 8868 8869 8870 8871 8872 8873 8874 8875 8876 8877 8878 8879 8880 8881 8882 8883 8884 8885 8886 8887 8888 8889 8890 8891 8892 8893 8894 8895 8896 8897 8898 8899 8900 8901 8902 8903 8904 8905 8906 8907 8908 8909 8910 8911 8912 8913 8914 8915 8916 8917 8918 8919 8920 8921 8922 8923 8924 8925 8926 8927 8928 8929 8930 8931 8932 8933 8934 8935 8936 8937 8938 8939 8940 8941 8942 8943 8944 8945 8946 8947 8948 8949 8950 8951 8952 8953 8954 8955 8956 8957 8958 8959 8960 8961 8962 8963 8964 8965 8966 8967 8968 8969 8970 8971 8972 8973 8974 8975 8976 8977 8978 8979 8980 8981 8982 8983 8984 8985 8986 8987 8988 8989 8990 8991 8992 8993 8994 8995 8996 8997 8998 8999 9000 9001 9002 9003 9004 9005 9006 9007 9008 9009 9010 9011 9012 9013 9014 9015 9016 9017 9018 9019 9020 9021 9022 9023 9024 9025 9026 9027 9028 9029 9030 9031 9032 9033 9034 9035 9036 9037 9038 9039 9040 9041 9042 9043 9044 9045 9046 9047 9048 9049 9050 9051 9052 9053 9054 9055 9056 9057 9058 9059 9060 9061 9062 9063 9064 9065 9066 9067 9068 9069 9070 9071 9072 9073 9074 9075 9076 9077 9078 9079 9080 9081 9082 9083 9084 9085 9086 9087 9088 9089 9090 9091 9092 9093 9094 9095 9096 9097 9098 9099 9100 9101 9102 9103 9104 9105 9106 9107 9108 9109 9110 9111 9112 9113 9114 9115 9116 9117 9118 9119 9120 9121 9122 9123 9124 9125 9126 9127 9128 9129 9130 9131 9132 9133 9134 9135 9136 9137 9138 9139 9140 9141 9142 9143 9144 9145 9146 9147 9148 9149 9150 9151 9152 9153 9154 9155 9156 9157 9158 9159 9160 9161 9162 9163 9164 9165 9166 9167 9168 9169 9170 9171 9172 9173 9174 9175 9176 9177 9178 9179 9180 9181 9182 9183 9184 9185 9186 9187 9188 9189 9190 9191 9192 9193 9194 9195 9196 9197 9198 9199 9200 9201 9202 9203 9204 9205 9206 9207 9208 9209 9210 9211 9212 9213 9214 9215 9216 9217 9218 9219 9220 9221 9222 9223 9224 9225 9226 9227 9228 9229 9230 9231 9232 9233 9234 9235 9236 9237 9238 9239 9240 9241 9242 9243 9244 9245 9246 9247 9248 9249 9250 9251 9252 9253 9254 9255 9256 9257 9258 9259 9260 9261 9262 9263 9264 9265 9266 9267 9268 9269 9270 9271 9272 9273 9274 9275 9276 9277 9278 9279 9280 9281 9282 9283 9284 9285 9286 9287 9288 9289 9290 9291 9292 9293 9294 9295 9296 9297 9298 9299 9300 9301 9302 9303 9304 9305 9306 9307 9308 9309 9310 9311 9312 9313 9314 9315 9316 9317 9318 9319 9320 9321 9322 9323 9324 9325 9326 9327 9328 9329 9330 9331 9332 9333 9334 9335 9336 9337 9338 9339 9340 9341 9342 9343 9344 9345 9346 9347 9348 9349 9350 9351 9352 9353 9354 9355 9356 9357 9358 9359 9360 9361 9362 9363 9364 9365 9366 9367 9368 9369 9370 9371 9372 9373 9374 9375 9376 9377 9378 9379 9380 9381 9382 9383 9384 9385 9386 9387 9388 9389 9390 9391 9392 9393 9394 9395 9396 9397 9398 9399 9400 9401 9402 9403 9404 9405 9406 9407 9408 9409 9410 9411 9412 9413 9414 9415 9416 9417 9418 9419 9420 9421 9422 9423 9424 9425 9426 9427 9428 9429 9430 9431 9432 9433 9434 9435 9436 9437 9438 9439 9440 9441 9442 9443 9444 9445 9446 9447 9448 9449 9450 9451 9452 9453 9454 9455 9456 9457 9458 9459 9460 9461 9462 9463 9464 9465 9466 9467 9468 9469 9470 9471 9472 9473 9474 9475 9476 9477 9478 9479 9480 9481 9482 9483 9484 9485 9486 9487 9488 9489 9490 9491 9492 9493 9494 9495 9496 9497 9498 9499 9500 9501 9502 9503 9504 9505 9506 9507 9508 9509 9510 9511 9512 9513 9514 9515 9516 9517 9518 9519 9520 9521 9522 9523 9524 9525 9526 9527 9528 9529 9530 9531 9532 9533 9534 9535 9536 9537 9538 9539 9540 9541 9542 9543 9544 9545 9546 9547 9548 9549 9550 9551 9552 9553 9554 9555 9556 9557 9558 9559 9560 9561 9562 9563 9564 9565 9566 9567 9568 9569 9570 9571 9572 9573 9574 9575 9576 9577 9578 9579 9580 9581 9582 9583 9584 9585 9586 9587 9588 9589 9590 9591 9592 9593 9594 9595 9596 9597 9598 9599 9600 9601 9602 9603 9604 9605 9606 9607 9608 9609 9610 9611 9612 9613 9614 9615 9616 9617 9618 9619 9620 9621 9622 9623 9624 9625 9626 9627 9628 9629 9630 9631 9632 9633 9634 9635 9636 9637 9638 9639 9640 9641 9642 9643 9644 9645 9646 9647 9648 9649 9650 9651 9652 9653 9654 9655 9656 9657 9658 9659 9660 9661 9662 9663 9664 9665 9666 9667 9668 9669 9670 9671 9672 9673 9674 9675 9676 9677 9678 9679 9680 9681 9682 9683 9684 9685 9686 9687 9688 9689 9690 9691 9692 9693 9694 9695 9696 9697 9698 9699 9700 9701 9702 9703 9704 9705 9706 9707 9708 9709 9710 9711 9712 9713 9714 9715 9716 9717 9718 9719 9720 9721 9722 9723 9724 9725 9726 9727 9728 9729 9730 9731 9732 9733 9734 9735 9736 9737 9738 9739 9740 9741 9742 9743 9744 9745 9746 9747 9748 9749 9750 9751 9752 9753 9754 9755 9756 9757 9758 9759 9760 9761 9762 9763 9764 9765 9766 9767 9768 9769 9770 9771 9772 9773 9774 9775 9776 9777 9778 9779 9780 9781 9782 9783 9784 9785 9786 9787 9788 9789 9790 9791 9792 9793 9794 9795 9796 9797 9798 9799 9800 9801 9802 9803 9804 9805 9806 9807 9808 9809 9810 9811 9812 9813 9814 9815 9816 9817 9818 9819 9820 9821 9822 9823 9824 9825 9826 9827 9828 9829 9830 9831 9832 9833 9834 9835 9836 9837 9838 9839 9840 9841 9842 9843 9844 9845 9846 9847 9848 9849 9850 9851 9852 9853 9854 9855 9856 9857 9858 9859 9860 9861 9862 9863 9864 9865 9866 9867 9868 9869 9870 9871 9872 9873 9874 9875 9876 9877 9878 9879 9880 9881 9882 9883 9884 9885 9886 9887 9888 9889 9890 9891 9892 9893 9894 9895 9896 9897 9898 9899 9900 9901 9902 9903 9904 9905 9906 9907 9908 9909 9910 9911 9912 9913 9914 9915 9916 9917 9918 9919 9920 9921 9922 9923 9924 9925 9926 9927 9928 9929 9930 9931 9932 9933 9934 9935 9936 9937 9938 9939 9940 9941 9942 9943 9944 9945 9946 9947 9948 9949 9950 9951 9952 9953 9954 9955 9956 9957 9958 9959 9960 9961 9962 9963 9964 9965 9966 9967 9968 9969 9970 9971 9972 9973 9974 9975 9976 9977 9978 9979 9980 9981 9982 9983 9984 9985 9986 9987 9988 9989 9990 9991 9992 9993 9994 9995 9996 9997 9998 9999 10000 10001 10002 10003 10004 10005 10006 10007 10008 10009 10010 10011 10012 10013 10014 10015 10016 10017 10018 10019 10020 10021 10022 10023 10024 10025 10026 10027 10028 10029 10030 10031 10032 10033 10034 10035 10036 10037 10038 10039 10040 10041 10042 10043 10044 10045 10046 10047 10048 10049 10050 10051 10052 10053 10054 10055 10056 10057 10058 10059 10060 10061 10062 10063 10064 10065 10066 10067 10068 10069 10070 10071 10072 10073 10074 10075 10076 10077 10078 10079 10080 10081 10082 10083 10084 10085 10086 10087 10088 10089 10090 10091 10092 10093 10094 10095 10096 10097 10098 10099 10100 10101 10102 10103 10104 10105 10106 10107 10108 10109 10110 10111 10112 10113 10114 10115 10116 10117 10118 10119 10120 10121 10122 10123 10124 10125 10126 10127 10128 10129 10130 10131 10132 10133 10134 10135 10136 10137 10138 10139 10140 10141 10142 10143 10144 10145 10146 10147 10148 10149 10150 10151 10152 10153 10154 10155 10156 10157 10158 10159 10160 10161 10162 10163 10164 10165 10166 10167 10168 10169 10170 10171 10172 10173 10174 10175 10176 10177 10178 10179 10180 10181 10182 10183 10184 10185 10186 10187 10188 10189 10190 10191 10192 10193 10194 10195 10196 10197 10198 10199 10200 10201 10202 10203 10204 10205 10206 10207 10208 10209 10210 10211 10212 10213 10214 10215 10216 10217 10218 10219 10220 10221 10222 10223 10224 10225 10226 10227 10228 10229 10230 10231 10232 10233 10234 10235 10236 10237 10238 10239 10240 10241 10242 10243 10244 10245 10246 10247 10248 10249 10250 10251 10252 10253 10254 10255 10256 10257 10258 10259 10260 10261 10262 10263 10264 10265 10266 10267 10268 10269 10270 10271 10272 10273 10274 10275 10276 10277 10278 10279 10280 10281 10282 10283 10284 10285 10286 10287 10288 10289 10290 10291 10292 10293 10294 10295 10296 10297 10298 10299 10300 10301 10302 10303 10304 10305 10306 10307 10308 10309 10310 10311 10312 10313 10314 10315 10316 10317 10318 10319 10320 10321 10322 10323 10324 10325 10326 10327 10328 10329 10330 10331 10332 10333 10334 10335 10336 10337 10338 10339 10340 10341 10342 10343 10344 10345 10346 10347 10348 10349 10350 10351 10352 10353 10354 10355 10356 10357 10358 10359 10360 10361 10362 10363 10364 10365 10366 10367 10368 10369 10370 10371 10372 10373 10374 10375 10376 10377 10378 10379 10380 10381 10382 10383 10384 10385 10386 10387 10388 10389 10390 10391 10392 10393 10394 10395 10396 10397 10398 10399 10400 10401 10402 10403 10404 10405 10406 10407 10408 10409 10410 10411 10412 10413 10414 10415 10416 10417 10418 10419 10420 10421 10422 10423 10424 10425 10426 10427 10428 10429 10430 10431 10432 10433 10434 10435 10436 10437 10438 10439 10440 10441 10442 10443 10444 10445 10446 10447 10448 10449 10450 10451 10452 10453 10454 10455 10456 10457 10458 10459 10460 10461 10462 10463 10464 10465 10466 10467 10468 10469 10470 10471 10472 10473 10474 10475 10476 10477 10478 10479 10480 10481 10482 10483 10484 10485 10486 10487 10488 10489 10490 10491 10492 10493 10494 10495 10496 10497 10498 10499 10500 10501 10502 10503 10504 10505 10506 10507 10508 10509 10510 10511 10512 10513 10514 10515 10516 10517 10518 10519 10520 10521 10522 10523 10524 10525 10526 10527 10528 10529 10530 10531 10532 10533 10534 10535 10536 10537 10538 10539 10540 10541 10542 10543 10544 10545 10546 10547 10548 10549 10550 10551 10552 10553 10554 10555 10556 10557 10558 10559 10560 10561 10562 10563 10564 10565 10566 10567 10568 10569 10570 10571 10572 10573 10574 10575 10576 10577 10578 10579 10580 10581 10582 10583 10584 10585 10586 10587 10588 10589 10590 10591 10592 10593 10594 10595 10596 10597 10598 10599 10600 10601 10602 10603 10604 10605 10606 10607 10608 10609 10610 10611 10612 10613 10614 10615 10616 10617 10618 10619 10620 10621 10622 10623 10624 10625 10626 10627 10628 10629 10630 10631 10632 10633 10634 10635 10636 10637 10638 10639 10640 10641 10642 10643 10644 10645 10646 10647 10648 10649 10650 10651 10652 10653 10654 10655 10656 10657 10658 10659 10660 10661 10662 10663 10664 10665 10666 10667 10668 10669 10670 10671 10672 10673 10674 10675 10676 10677 10678 10679 10680 10681 10682 10683 10684 10685 10686 10687 10688 10689 10690 10691 10692 10693 10694 10695 10696 10697 10698 10699 10700 10701 10702 10703 10704 10705 10706 10707 10708 10709 10710 10711 10712 10713 10714 10715 10716 10717 10718 10719 10720 10721 10722 10723 10724 10725 10726 10727 10728 10729 10730 10731 10732 10733 10734 10735 10736 10737 10738 10739 10740 10741 10742 10743 10744 10745 10746 10747 10748 10749 10750 10751 10752 10753 10754 10755 10756 10757 10758 10759 10760 10761 10762 10763 10764 10765 10766 10767 10768 10769 10770 10771 10772 10773 10774 10775 10776 10777 10778 10779 10780 10781 10782 10783 10784 10785 10786 10787 10788 10789 10790 10791 10792 10793 10794 10795 10796 10797 10798 10799 10800 10801 10802 10803 10804 10805 10806 10807 10808 10809 10810 10811 10812 10813 10814 10815 10816 10817 10818 10819 10820 10821 10822 10823 10824 10825 10826 10827 10828 10829 10830 10831 10832 10833 10834 10835 10836 10837 10838 10839 10840 10841 10842 10843 10844 10845 10846 10847 10848 10849 10850 10851 10852 10853 10854 10855 10856 10857 10858 10859 10860 10861 10862 10863 10864 10865 10866 10867 10868 10869 10870 10871 10872 10873 10874 10875 10876 10877 10878 10879 10880 10881 10882 10883 10884 10885 10886 10887 10888 10889 10890 10891 10892 10893 10894 10895 10896 10897 10898 10899 10900 10901 10902 10903 10904 10905 10906 10907 10908 10909 10910 10911 10912 10913 10914 10915 10916 10917 10918 10919 10920 10921 10922 10923 10924 10925 10926 10927 10928 10929 10930 10931 10932 10933 10934 10935 10936 10937 10938 10939 10940 10941 10942 10943 10944 10945 10946 10947 10948 10949 10950 10951 10952 10953 10954 10955 10956 10957 10958 10959 10960 10961 10962 10963 10964 10965 10966 10967 10968 10969 10970 10971 10972 10973 10974 10975 10976 10977 10978 10979 10980 10981 10982 10983 10984 10985 10986 10987 10988 10989 10990 10991 10992 10993 10994 10995 10996 10997 10998 10999 11000 11001 11002 11003 11004 11005 11006 11007 11008 11009 11010 11011 11012 11013 11014 11015 11016 11017 11018 11019 11020 11021 11022 11023 11024 11025 11026 11027 11028 11029 11030 11031 11032 11033 11034 11035 11036 11037 11038 11039 11040 11041 11042 11043 11044 11045 11046 11047 11048 11049 11050 11051 11052 11053 11054 11055 11056 11057 11058 11059 11060 11061 11062 11063 11064 11065 11066 11067 11068 11069 11070 11071 11072 11073 11074 11075 11076 11077 11078 11079 11080 11081 11082 11083 11084 11085 11086 11087 11088 11089 11090 11091 11092 11093 11094 11095 11096 11097 11098 11099 11100 11101 11102 11103 11104 11105 11106 11107 11108 11109 11110 11111 11112 11113 11114 11115 11116 11117 11118 11119 11120 11121 11122 11123 11124 11125 11126 11127 11128 11129 11130 11131 11132 11133 11134 11135 11136 11137 11138 11139 11140 11141 11142 11143 11144 11145 11146 11147 11148 11149 11150 11151 11152 11153 11154 11155 11156 11157 11158 11159 11160 11161 11162 11163 11164 11165 11166 11167 11168 11169 11170 11171 11172 11173 11174 11175 11176 11177 11178 11179 11180 11181 11182 11183 11184 11185 11186 11187 11188 11189 11190 11191 11192 11193 | from __future__ import annotations
import csv
from dataclasses import dataclass
from decimal import Decimal, InvalidOperation
from datetime import datetime, timezone
import gc
import hashlib
import inspect
import json
import math
import os
import random
import shutil
import sqlite3
import sys
import tempfile
import time
import traceback
from contextlib import contextmanager, nullcontext
from pathlib import Path
from typing import Any, Iterator
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np
import optuna
import pandas as pd
import segmentation_models_pytorch as smp
import torch
import torch.nn as nn
import torch.nn.functional as F
from optuna.storages import RDBStorage
from PIL import Image as PILImage
from scipy import ndimage
from torch.optim import Adam, AdamW
from torch.optim.lr_scheduler import CosineAnnealingLR
from torch.utils.data import DataLoader, Dataset
from tqdm.auto import tqdm
"""=============================================================================
EDIT ME
=============================================================================
"""
PROJECT_DIR = Path(__file__).resolve().parent #Path("/content/drive/MyDrive/SDP_ultrasound") ##
RUNS_ROOT = PROJECT_DIR / "runs"
HARD_CODED_PARAM_DIR = PROJECT_DIR
MODEL_NAME = "EfficientNetB0_Folds_5splits"
EXPERIMENT_MODE = "repeated_holdout" # "single_run" or "repeated_holdout"
SUPPORTED_EXPERIMENT_MODES = ("single_run", "repeated_holdout")
NUM_STRATIFIED_SPLIT_REPEATS = 5
DATASET_PERCENT_REPEAT_COUNTS: dict[int, int] = {
5: 4,
15: 3,
30: 3,
50: 2,
100: 1,
}
PERCENT_SAMPLING_MODE = "incremental" # "independent" or "incremental"
SUPPORTED_PERCENT_SAMPLING_MODES = ("independent", "incremental")
PERCENT_EXECUTION_MODE = "manual" # "auto" or "manual"
SUPPORTED_PERCENT_EXECUTION_MODES = ("auto", "manual")
SELECTED_DATASET_PERCENTS: list[int] = [5,15]
SPLIT_EXECUTION_MODE = "manual" # "auto" or "manual"
SUPPORTED_SPLIT_EXECUTION_MODES = ("auto", "manual")
SELECTED_SPLIT_INDICES: list[int] = [4,5]
REPEAT_EXECUTION_MODE = "manual" # "auto" or "manual"
SUPPORTED_REPEAT_EXECUTION_MODES = ("auto", "manual")
SELECTED_REPEAT_INDICES: list[int] = [1,2]
FOLDS_EXPERIMENT_NAME = "stratified_holdout_v1"
RESUME_FOLDS = False
DATASET_NAME = "BUSI_with_classes" # "BUSI" or "BUSI_with_classes"
SUPPORTED_DATASET_NAMES = ("BUSI", "BUSI_with_classes")
DATA_ROOT = PROJECT_DIR / DATASET_NAME
BUSI_WITH_CLASSES_SPLIT_POLICY = "stratified" # "balanced_train" or "stratified"
SUPPORTED_BUSI_WITH_CLASSES_SPLIT_POLICIES = ("balanced_train", "stratified")
STRATEGIES = [2, 3] #[1, 2, 3, 4, 5] #0.1, 0.15, 0.2,
DATASET_PERCENTS = [] #ignored in the folding [0.25, 0.3, 0.35, 0.4, 0.45, 0.5, 1.0] #, 0.5, 1.0] #, 0.5, 1.0]
SPLIT_TYPE = "80_10_10"
SUPPORTED_SPLIT_TYPES = ("80_10_10", "70_10_20")
DATASET_SPLITS_JSON = PROJECT_DIR / "dataset_splits.json"
DATASET_SPLITS_VERSION = 1
TRAIN_SUBSET_VARIANT = 1 # 0 uses the persisted subset; >0 deterministically resamples only the train subset from the frozen base train split.
NUM_TRIALS = 70
STUDY_DIRECTION = "maximize"
BEST_CHECKPOINT_METRICS = {
1: "val_iou",
2: "val_iou",
3: "val_iou_gain",
4: "val_iou_gain",
5: "val_iou_gain",
}
SEED = 42
IMG_SIZE = 128
BATCH_SIZE = 4 # Recommended to prevent OOM
NUM_WORKERS = 6 # Recommended with RAM-preloaded datasets to avoid worker RAM duplication.
USE_PIN_MEMORY = True
USE_PERSISTENT_WORKERS = True
PRELOAD_TO_RAM = True
SMP_ENCODER_NAME = "efficientnet-b0"
SMP_ENCODER_WEIGHTS = "imagenet"
SMP_ENCODER_DEPTH = 5
SMP_ENCODER_PROJ_DIM = 192
SMP_DECODER_TYPE = "Unet"
BACKBONE_FAMILY = "smp" # "smp" or "custom_vgg"
VGG_FEATURE_SCALES = 4
VGG_FEATURE_DILATION = 1
USE_IMAGENET_NORM = True
REPLACE_BN_WITH_GN = True
GN_NUM_GROUPS = 8
NUM_ACTIONS = 2
STRATEGY_1_MAX_EPOCHS = 100
STRATEGY_2_MAX_EPOCHS = 100
STRATEGY_3_MAX_EPOCHS = 250
STRATEGY_4_MAX_EPOCHS = 100
STRATEGY_5_MAX_EPOCHS = 100
VALIDATE_EVERY_N_EPOCHS = 1
CHECKPOINT_EVERY_N_EPOCHS = 0
SAVE_LATEST_EVERY_EPOCH = True
SAVE_HISTORY_INCREMENTALLY = False
EARLY_STOPPING_PATIENCE = 0
VERBOSE_EPOCH_LOG = False
DEFAULT_HEAD_LR = 1e-4
DEFAULT_ENCODER_LR = 1e-5
DEFAULT_WEIGHT_DECAY = 1e-4
DEFAULT_TMAX = 5
DEFAULT_GAMMA = 0.95
DEFAULT_CRITIC_LOSS_WEIGHT = 0.5
DEFAULT_ENTROPY_ALPHA_INIT = 0.2
DEFAULT_ENTROPY_TARGET_RATIO = 0.25
DEFAULT_ENTROPY_LR = 3e-4
DEFAULT_CE_WEIGHT = 0.5
DEFAULT_DICE_WEIGHT = 0.5
DEFAULT_DROPOUT_P = 0.2
DEFAULT_GRAD_CLIP_NORM = 6.0
DEFAULT_MASK_UPDATE_STEP = 0.1
DEFAULT_FOREGROUND_REWARD_WEIGHT = 0.0
DEFAULT_RECALL_REWARD_WEIGHT = 1.0
DEFAULT_DICE_REWARD_WEIGHT = 0.35
DEFAULT_BOUNDARY_REWARD_WEIGHT = 0.15
DEFAULT_PRIOR_REWARD_WEIGHT = 0.01
DEFAULT_DECODER_GAIN_REWARD_WEIGHT = 0.5
DEFAULT_REWARD_SCALE = 1.0
DEFAULT_STRATEGY3_FREEZE_BOOTSTRAPPED_SEGMENTATION = True
DEFAULT_STRATEGY3_PPO_CLIP_EPS = 0.2
DEFAULT_STRATEGY3_PPO_EPOCHS = 2
DEFAULT_STRATEGY3_RL_GRAD_CLIP_NORM = 2.0
DEFAULT_EARLY_STOPPING_MONITOR = "auto"
DEFAULT_EARLY_STOPPING_MODE = "auto"
DEFAULT_EARLY_STOPPING_MIN_DELTA = 0.0
DEFAULT_EARLY_STOPPING_START_EPOCH = 1
DEFAULT_EXPLORATION_EPS = 0.1
EXPLORATION_EPS_EPOCHS = 20
ATTENTION_MAX_TOKENS = 1024
ATTENTION_MIN_POOL_SIZE = 16
SCHEDULER_FACTOR = 0.5
SCHEDULER_PATIENCE = 5
SCHEDULER_THRESHOLD = 1e-3
SCHEDULER_MIN_LR = 1e-5
HEAD_LR_RANGE = (1e-5, 3e-3)
ENCODER_LR_RANGE = (1e-6, 3e-3)
WEIGHT_DECAY_RANGE = (1e-6, 1e-2)
TMAX_RANGE = (3, 10)
ENTROPY_LR_RANGE = (1e-5, 1e-3)
DROPOUT_P_RANGE = (0.0, 0.5)
USE_TRIAL_PRUNING = True
TRIAL_PRUNER_WARMUP_STEPS = 80
TRIAL_PRUNER_PATIENCE_STEPS = 40
LOAD_EXISTING_STUDIES = False
SKIP_EXISTING_FINALS = False
RUN_OPTUNA = False
RESET_ALL_STUDIES_EACH_RUN = False
USE_EXISTING_BEST_PARAMS_WHEN_OPTUNA_OFF = False
EXECUTION_MODE = "train_eval" # "train_eval" or "eval_only"
EVAL_CHECKPOINT_MODE = "best" # "latest", "best", or "specific"
EVAL_SPECIFIC_CHECKPOINT = ""
STRATEGY2_CHECKPOINT_MODE = "best" # "latest", "best", or "specific"
STRATEGY2_SPECIFIC_CHECKPOINT = {
0.1: "runs/EfficientNet_Strategy2_New/pct_10/strategy_2/final/checkpoints/epoch_0089.pt",
0.5: "Strategy2_Checkpoints/strat2_50_best.pt",
1.0: "runs/EfficientNet_Strategy2_New/pct_100/strategy_2/final/checkpoints/best.pt"
}
STRATEGY3_BOOTSTRAP_FROM_STRATEGY2 = True
TRAIN_RESUME_MODE = "off" # "off", "latest", "best", or "specific"
TRAIN_RESUME_SPECIFIC_CHECKPOINT = ""
OPTUNA_HEARTBEAT_INTERVAL = 60
OPTUNA_HEARTBEAT_GRACE_PERIOD = 180
USE_AMP = True
AMP_DTYPE = "bfloat16" # "auto", "bfloat16", or "float16"
USE_CHANNELS_LAST = False
USE_TORCH_COMPILE = True
STEPWISE_BACKWARD = True
ALLOW_TF32 = True
RUN_SMOKE_TEST = True
SMOKE_TEST_SAMPLE_INDEX = 0
RUN_OVERFIT_TEST = False
OVERFIT_N_BATCHES = 2
OVERFIT_N_EPOCHS = 100
OVERFIT_HEAD_LR = 1e-3
OVERFIT_ENCODER_LR = 1e-4
OVERFIT_PRINT_EVERY = 5
WRITE_EPOCH_DIAGNOSTIC = False
EPOCH_DIAGNOSTIC_TRAIN_BATCHES = 2
EPOCH_DIAGNOSTIC_VAL_BATCHES = 2
CONTROLLED_MASK_THRESHOLD = 0.50
REQUIRED_HPARAM_KEYS = ("head_lr", "encoder_lr", "weight_decay", "dropout_p", "tmax", "entropy_lr")
"""=============================================================================
IF OPTUNA IS OFF --> USE ME
=============================================================================
"""
# Key format: "<strategy>:<dataset_percent_label>"
# Each value is a JSON filename in HARD_CODED_PARAM_DIR containing the required hyperparameters.
MANUAL_HPARAMS_IF_OPTUNA_OFF: dict[str, str] = {
"2:5": "strat2_best_params.json",
"2:10": "hyperparams/strat2_best_params.json",
"2:15": "strat2_best_params.json",
"2:20": "hyperparams/strat2_best_params.json",
"2:25": "hyperparams/strat2_best_params.json",
"2:30": "hyperparams/strat2_best_params.json",
"2:35": "hyperparams/strat2_best_params.json",
"2:40": "hyperparams/strat2_best_params.json",
"2:45": "hyperparams/strat2_best_params.json",
"2:50": "hyperparams/strat2_best_params.json",
"2:100": "hyperparams/strat2_best_params.json",
"3:5": "strat3_best_params.json",
"3:10": "hyperparams/strat3_best_params.json",
"3:15": "strat3_best_params.json",
"3:20": "hyperparams/strat3_best_params.json",
"3:25": "hyperparams/strat3_best_params.json",
"3:30": "hyperparams/strat3_best_params.json",
"3:35": "hyperparams/strat3_best_params.json",
"3:40": "hyperparams/strat3_best_params.json",
"3:45": "hyperparams/strat3_best_params.json",
"3:50": "hyperparams/strat3_best_params.json",
"3:100": "hyperparams/strat3_best_params.json",
}
"""=============================================================================
RUNTIME SETUP
=============================================================================
"""
torch.set_float32_matmul_precision("high")
if torch.cuda.is_available():
torch.backends.cuda.matmul.allow_tf32 = ALLOW_TF32
torch.backends.cudnn.allow_tf32 = ALLOW_TF32
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
def select_runtime_device() -> tuple[torch.device, str]:
if torch.cuda.is_available():
return torch.device("cuda"), "cuda"
mps_backend = getattr(torch.backends, "mps", None)
if mps_backend is not None and mps_backend.is_available():
try:
_probe = torch.zeros(1, device="mps")
del _probe
return torch.device("mps"), "mps"
except Exception as exc:
print(f"[Device] MPS detected but failed to initialize ({exc}). Falling back to CPU.")
return torch.device("cpu"), "cpu"
DEVICE, DEVICE_FALLBACK_SOURCE = select_runtime_device()
CURRENT_JOB_PARAMS: dict[str, Any] = {}
@dataclass(frozen=True)
class RuntimeModelConfig:
backbone_family: str
smp_encoder_name: str
smp_encoder_weights: str | None
smp_encoder_depth: int
smp_encoder_proj_dim: int
smp_decoder_type: str
vgg_feature_scales: int
vgg_feature_dilation: int
@classmethod
def from_globals(cls) -> RuntimeModelConfig:
return cls(
backbone_family=str(BACKBONE_FAMILY).strip().lower(),
smp_encoder_name=str(SMP_ENCODER_NAME),
smp_encoder_weights=SMP_ENCODER_WEIGHTS,
smp_encoder_depth=int(SMP_ENCODER_DEPTH),
smp_encoder_proj_dim=int(SMP_ENCODER_PROJ_DIM),
smp_decoder_type=str(SMP_DECODER_TYPE),
vgg_feature_scales=int(VGG_FEATURE_SCALES),
vgg_feature_dilation=int(VGG_FEATURE_DILATION),
)
@classmethod
def from_payload(cls, payload: dict[str, Any] | None) -> RuntimeModelConfig:
payload = payload or {}
return cls(
backbone_family=str(payload.get("backbone_family", "smp")).strip().lower(),
smp_encoder_name=str(payload.get("smp_encoder_name", SMP_ENCODER_NAME)),
smp_encoder_weights=payload.get("smp_encoder_weights", SMP_ENCODER_WEIGHTS),
smp_encoder_depth=int(payload.get("smp_encoder_depth", SMP_ENCODER_DEPTH)),
smp_encoder_proj_dim=int(payload.get("smp_encoder_proj_dim", SMP_ENCODER_PROJ_DIM)),
smp_decoder_type=str(payload.get("smp_decoder_type", SMP_DECODER_TYPE)),
vgg_feature_scales=int(payload.get("vgg_feature_scales", VGG_FEATURE_SCALES)),
vgg_feature_dilation=int(payload.get("vgg_feature_dilation", VGG_FEATURE_DILATION)),
)
def validate(self) -> RuntimeModelConfig:
if self.backbone_family not in {"smp", "custom_vgg"}:
raise ValueError(f"BACKBONE_FAMILY must be 'smp' or 'custom_vgg', got {self.backbone_family!r}")
if self.vgg_feature_scales not in {3, 4}:
raise ValueError(f"VGG_FEATURE_SCALES must be 3 or 4, got {self.vgg_feature_scales}")
if self.vgg_feature_dilation < 1:
raise ValueError(f"VGG_FEATURE_DILATION must be >= 1, got {self.vgg_feature_dilation}")
if self.smp_encoder_depth < 1:
raise ValueError(f"SMP_ENCODER_DEPTH must be >= 1, got {self.smp_encoder_depth}")
if self.smp_encoder_proj_dim < 0:
raise ValueError(f"SMP_ENCODER_PROJ_DIM must be >= 0, got {self.smp_encoder_proj_dim}")
return self
def to_payload(self) -> dict[str, Any]:
return {
"backbone_family": self.backbone_family,
"smp_encoder_name": self.smp_encoder_name,
"smp_encoder_weights": self.smp_encoder_weights,
"smp_encoder_depth": self.smp_encoder_depth,
"smp_encoder_proj_dim": self.smp_encoder_proj_dim,
"smp_decoder_type": self.smp_decoder_type,
"vgg_feature_scales": self.vgg_feature_scales,
"vgg_feature_dilation": self.vgg_feature_dilation,
}
def backbone_tag(self) -> str:
return self.backbone_family
def backbone_display_name(self) -> str:
if self.backbone_family == "custom_vgg":
return f"Custom VGG (scales={self.vgg_feature_scales}, dilation={self.vgg_feature_dilation})"
return f"SMP {self.smp_encoder_name}"
def current_model_config() -> RuntimeModelConfig:
return RuntimeModelConfig.from_globals().validate()
"""=============================================================================
UTILITIES
=============================================================================
"""
def banner(title: str) -> None:
line = "=" * 80
print(f"\n{line}\n{title}\n{line}")
def section(title: str) -> None:
print(f"\n{'-' * 80}\n{title}\n{'-' * 80}")
def ensure_dir(path: str | Path) -> Path:
path = Path(path).expanduser().resolve()
path.mkdir(parents=True, exist_ok=True)
return path
def save_json(path: str | Path, payload: Any) -> None:
path = Path(path)
ensure_dir(path.parent)
with path.open("w", encoding="utf-8") as f:
json.dump(payload, f, indent=2)
def load_json(path: str | Path) -> Any:
with Path(path).open("r", encoding="utf-8") as f:
return json.load(f)
def _format_history_log_value(key: str, value: Any) -> str:
if isinstance(value, float):
if key == "lr" or key.endswith("_lr"):
return f"{value:.6e}"
return json.dumps(value)
return json.dumps(value)
def format_history_log_row(row: dict[str, Any]) -> str:
return ", ".join(f"{key}={_format_history_log_value(key, value)}" for key, value in row.items())
def _format_epoch_metric(value: Any, *, scientific: bool = False) -> str:
if value is None:
return "null"
if isinstance(value, (float, int, np.floating, np.integer)):
value = float(value)
return f"{value:.6e}" if scientific else f"{value:.4f}"
return str(value)
def format_concise_epoch_log(
row: dict[str, Any],
*,
best_metric_name: str,
best_metric_value: float,
) -> str:
fields: list[tuple[str, Any, bool]] = [
("train_loss", row.get("train_loss"), False),
("train_iou", row.get("train_iou"), False),
("train_entropy", row.get("train_entropy"), False),
("val_loss", row.get("val_loss"), False),
("val_iou", row.get("val_iou"), False),
("val_dice", row.get("val_dice"), False),
("val_iou_gain", row.get("val_iou_gain"), False),
("head_lr", row.get("lr"), True),
("encoder_lr", row.get("encoder_lr"), True),
(best_metric_name, best_metric_value, False),
]
parts = [
f"{name}={_format_epoch_metric(value, scientific=scientific)}"
for name, value, scientific in fields
if value is not None
]
early_monitor_name = row.get("early_stopping_monitor_name")
if early_monitor_name:
parts.append(f"es_monitor={early_monitor_name}")
if row.get("early_stopping_monitor_value") is not None:
parts.append(f"es_value={_format_epoch_metric(row.get('early_stopping_monitor_value'))}")
if row.get("early_stopping_best_value") is not None:
parts.append(f"es_best={_format_epoch_metric(row.get('early_stopping_best_value'))}")
if row.get("early_stopping_wait") is not None and row.get("early_stopping_patience") is not None:
parts.append(
f"es_wait={int(row.get('early_stopping_wait'))}/{int(row.get('early_stopping_patience'))}"
)
if row.get("early_stopping_active") is not None:
parts.append(f"es_active={bool(row.get('early_stopping_active'))}")
if row.get("strategy3_freeze_active") is not None:
parts.append(f"s3_frozen={bool(row.get('strategy3_freeze_active'))}")
return ", ".join(parts)
def set_global_seed(seed: int = 42) -> None:
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
if torch.cuda.is_available():
torch.cuda.manual_seed_all(seed)
os.environ["PYTHONHASHSEED"] = str(seed)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
def stable_int_from_text(text: str) -> int:
value = 0
for byte in text.encode("utf-8"):
value = (value * 131 + byte) % (2 ** 31 - 1)
return value
def seed_worker(worker_id: int) -> None:
del worker_id
worker_seed = torch.initial_seed() % (2 ** 32)
random.seed(worker_seed)
np.random.seed(worker_seed)
torch.manual_seed(worker_seed)
def make_seeded_generator(seed: int, tag: str) -> torch.Generator:
generator = torch.Generator()
generator.manual_seed(seed + stable_int_from_text(tag))
return generator
def cuda_memory_snapshot() -> str:
if DEVICE.type != "cuda" or not torch.cuda.is_available():
return "allocated=0.00 GB, reserved=0.00 GB, peak=0.00 GB"
allocated = torch.cuda.memory_allocated(device=DEVICE) / (1024 ** 3)
reserved = torch.cuda.memory_reserved(device=DEVICE) / (1024 ** 3)
peak = torch.cuda.max_memory_allocated(device=DEVICE) / (1024 ** 3)
return f"allocated={allocated:.2f} GB, reserved={reserved:.2f} GB, peak={peak:.2f} GB"
def run_cuda_cleanup(context: str | None = None) -> None:
gc.collect()
if DEVICE.type != "cuda" or not torch.cuda.is_available():
return
try:
torch.cuda.synchronize(device=DEVICE)
except Exception:
pass
try:
torch.cuda.empty_cache()
except Exception:
pass
try:
torch.cuda.ipc_collect()
except Exception:
pass
if context is not None:
print(f"[CUDA Cleanup] {context}: {cuda_memory_snapshot()}")
try:
torch.cuda.reset_peak_memory_stats(device=DEVICE)
except Exception:
pass
def prune_directory_except(root: Path, keep_file_names: set[str]) -> None:
if not root.exists():
return
keep_paths = {root / name for name in keep_file_names}
for path in sorted((p for p in root.rglob("*") if p.is_file()), reverse=True):
if path not in keep_paths:
path.unlink()
for path in sorted((p for p in root.rglob("*") if p.is_dir()), reverse=True):
if path != root:
try:
path.rmdir()
except OSError:
pass
def prune_optuna_trial_dir(trial_dir: Path) -> None:
if trial_dir.exists():
shutil.rmtree(trial_dir, ignore_errors=True)
def prune_optuna_study_dir(study_root: Path) -> None:
prune_directory_except(study_root, {"best_params.json", "summary.json", "study.sqlite3"})
def to_device(batch: Any, device: torch.device) -> Any:
if torch.is_tensor(batch):
return batch.to(device, non_blocking=True)
if isinstance(batch, dict):
return {k: to_device(v, device) for k, v in batch.items()}
if isinstance(batch, list):
return [to_device(v, device) for v in batch]
if isinstance(batch, tuple):
return tuple(to_device(v, device) for v in batch)
return batch
def _normalized_decimal_text(value: Decimal) -> str:
normalized = value.normalize()
text = format(normalized, "f")
if "." in text:
text = text.rstrip("0").rstrip(".")
return text or "0"
def _fraction_decimal(value: Any, *, field_name: str) -> Decimal:
if isinstance(value, bool):
raise TypeError(f"{field_name} must be a real number in (0, 1], got boolean {value!r}.")
try:
decimal_value = Decimal(str(value).strip())
except (InvalidOperation, ValueError) as exc:
raise ValueError(f"{field_name} must be a real number in (0, 1], got {value!r}.") from exc
if not decimal_value.is_finite():
raise ValueError(f"{field_name} must be finite, got {value!r}.")
if decimal_value <= 0 or decimal_value > 1:
raise ValueError(f"{field_name} must be in the interval (0, 1], got {value!r}.")
return decimal_value
def _percent_decimal(value: Any, *, field_name: str = "dataset percent") -> Decimal:
return _fraction_decimal(value, field_name=field_name) * Decimal("100")
def normalize_dataset_percents(values: list[float] | tuple[float, ...]) -> list[float]:
if not values:
raise ValueError("DATASET_PERCENTS must contain at least one fraction in (0, 1].")
normalized: dict[str, float] = {}
for value in values:
fraction = _fraction_decimal(value, field_name="DATASET_PERCENTS entry")
normalized[_normalized_decimal_text(fraction)] = float(fraction)
return [normalized[key] for key in sorted(normalized, key=Decimal)]
def percent_label(percent: float) -> str:
return _normalized_decimal_text(_percent_decimal(percent)).replace(".", "p")
def percent_display(percent: float) -> str:
return _normalized_decimal_text(_percent_decimal(percent))
def percent_text(percent: float) -> str:
return f"{percent_display(percent)}%"
def run_identity_parts(
*,
strategy: int | None = None,
percent: float | None = None,
trial_number: int | None = None,
split_payload: dict[str, Any] | None = None,
) -> list[str]:
parts: list[str] = []
payload = split_payload or {}
split_repeat_index = payload.get("split_repeat_index")
subset_repeat_index = payload.get("subset_repeat_index")
split_type = payload.get("split_type")
train_subset_variant = payload.get("train_subset_variant")
if split_repeat_index is not None:
parts.append(f"split={int(split_repeat_index):03d}")
elif split_type is not None:
parts.append(f"split={split_type}")
if subset_repeat_index is not None:
parts.append(f"repeat={int(subset_repeat_index):02d}")
elif train_subset_variant is not None and int(train_subset_variant) > 0:
parts.append(f"variant={int(train_subset_variant):02d}")
if strategy is not None:
parts.append(f"strategy={int(strategy)}")
effective_percent = percent
if effective_percent is None and payload.get("dataset_percent") is not None:
effective_percent = float(payload["dataset_percent"])
if effective_percent is not None:
parts.append(f"pct={percent_text(float(effective_percent))}")
if trial_number is not None:
parts.append(f"trial={int(trial_number):03d}")
return parts
def run_identity_label(
*,
strategy: int | None = None,
percent: float | None = None,
trial_number: int | None = None,
split_payload: dict[str, Any] | None = None,
) -> str:
parts = run_identity_parts(
strategy=strategy,
percent=percent,
trial_number=trial_number,
split_payload=split_payload,
)
return " | ".join(parts) if parts else "run"
def run_identity_slug(
*,
strategy: int | None = None,
percent: float | None = None,
trial_number: int | None = None,
split_payload: dict[str, Any] | None = None,
) -> str:
payload = split_payload or {}
parts: list[str] = []
split_repeat_index = payload.get("split_repeat_index")
subset_repeat_index = payload.get("subset_repeat_index")
split_type = payload.get("split_type")
train_subset_variant = payload.get("train_subset_variant")
if split_repeat_index is not None:
parts.append(f"split_{int(split_repeat_index):03d}")
elif split_type is not None:
parts.append(f"split_{str(split_type)}")
if subset_repeat_index is not None:
parts.append(f"repeat_{int(subset_repeat_index):02d}")
elif train_subset_variant is not None and int(train_subset_variant) > 0:
parts.append(f"variant_{int(train_subset_variant):02d}")
if strategy is not None:
parts.append(f"strategy_{int(strategy)}")
effective_percent = percent
if effective_percent is None and payload.get("dataset_percent") is not None:
effective_percent = float(payload["dataset_percent"])
if effective_percent is not None:
parts.append(f"pct_{percent_label(float(effective_percent))}")
if trial_number is not None:
parts.append(f"trial_{int(trial_number):03d}")
return "__".join(parts) if parts else "run"
def current_dataset_name() -> str:
dataset_name = str(DATASET_NAME).strip()
if dataset_name not in SUPPORTED_DATASET_NAMES:
raise ValueError(f"DATASET_NAME must be one of {SUPPORTED_DATASET_NAMES}, got {dataset_name!r}")
return dataset_name
def current_busi_with_classes_split_policy() -> str:
split_policy = str(BUSI_WITH_CLASSES_SPLIT_POLICY).strip().lower()
if split_policy not in SUPPORTED_BUSI_WITH_CLASSES_SPLIT_POLICIES:
raise ValueError(
f"BUSI_WITH_CLASSES_SPLIT_POLICY must be one of {SUPPORTED_BUSI_WITH_CLASSES_SPLIT_POLICIES}, "
f"got {split_policy!r}"
)
return split_policy
def current_dataset_splits_json_path() -> Path:
dataset_name = current_dataset_name()
if dataset_name == "BUSI":
return DATASET_SPLITS_JSON
return PROJECT_DIR / f"dataset_splits_{dataset_name.lower()}_{current_busi_with_classes_split_policy()}.json"
def current_dataset_dirs() -> tuple[Path, Path]:
dataset_name = current_dataset_name()
if dataset_name == "BUSI":
return DATA_ROOT / "images", DATA_ROOT / "annotations"
return DATA_ROOT / "all_images", DATA_ROOT / "all_masks"
def current_pipeline_check_path() -> Path | None:
if current_dataset_name() != "BUSI_with_classes":
return None
return DATA_ROOT / "pipeline_check.json"
def normalization_cache_tag() -> str:
dataset_name = current_dataset_name()
if dataset_name == "BUSI":
return "BUSI"
return f"{dataset_name}_{current_busi_with_classes_split_policy()}"
def resolve_amp_dtype(key: str) -> torch.dtype:
key = key.lower().strip()
if key == "auto":
if DEVICE.type == "cuda":
try:
if torch.cuda.is_bf16_supported():
return torch.bfloat16
except Exception:
major, _minor = torch.cuda.get_device_capability()
if major >= 8:
return torch.bfloat16
return torch.float16
if key in {"float16", "fp16", "half"}:
return torch.float16
if key in {"bfloat16", "bf16"}:
if DEVICE.type == "cuda":
try:
if torch.cuda.is_bf16_supported():
return torch.bfloat16
except Exception:
major, _minor = torch.cuda.get_device_capability()
if major >= 8:
return torch.bfloat16
print("[AMP] bfloat16 requested but unsupported here. Falling back to float16.")
return torch.float16
raise ValueError(f"Unsupported AMP_DTYPE: {key}")
def amp_autocast_enabled(device: torch.device) -> bool:
return USE_AMP and device.type in {"cuda", "mps"}
def autocast_ctx(enabled: bool, device: torch.device, amp_dtype: torch.dtype):
if not enabled:
return nullcontext()
return torch.autocast(device_type=device.type, dtype=amp_dtype, enabled=True)
def make_grad_scaler(enabled: bool, amp_dtype: torch.dtype, device: torch.device):
if not enabled or device.type != "cuda" or amp_dtype == torch.bfloat16:
return None
try:
return torch.amp.GradScaler("cuda", enabled=True, init_scale=8192.0)
except Exception:
return torch.cuda.amp.GradScaler(enabled=True, init_scale=8192.0)
def format_seconds(seconds: float) -> str:
seconds = int(seconds)
h, rem = divmod(seconds, 3600)
m, s = divmod(rem, 60)
return f"{h:02d}:{m:02d}:{s:02d}"
def tensor_bytes(t: torch.Tensor) -> int:
return t.numel() * t.element_size()
def bytes_to_gb(num_bytes: int) -> float:
return num_bytes / (1024 ** 3)
def set_current_job_params(payload: dict[str, Any] | None = None) -> None:
CURRENT_JOB_PARAMS.clear()
if payload:
CURRENT_JOB_PARAMS.update(dict(payload))
def _job_param(name: str, default: Any) -> Any:
return CURRENT_JOB_PARAMS.get(name, default)
def _alpha_log_floor() -> float:
return math.log(max(float(_job_param("min_alpha", math.exp(-5.0))), 1e-6))
def _keep_action_index(action_count: int) -> int:
action_count = max(int(action_count), 1)
if action_count == 5:
return 2
if action_count >= 3:
return 1
return action_count - 1
def _strategy3_training_progress(current_epoch: int, max_epochs: int) -> float:
if max_epochs <= 0:
return 0.0
return float(min(max(float(current_epoch) / float(max_epochs), 0.0), 1.0))
def _strategy_selection_metric_name(strategy: int) -> str:
metric_name = BEST_CHECKPOINT_METRICS.get(int(strategy))
if not isinstance(metric_name, str) or not metric_name.strip():
raise KeyError(
f"No best-checkpoint metric configured for strategy {strategy}. "
f"Set BEST_CHECKPOINT_METRICS[{strategy}] to a non-empty metric name."
)
return metric_name.strip()
def _strategy_selection_metric_value(strategy: int, metrics: dict[str, Any]) -> float:
metric_name = _strategy_selection_metric_name(strategy)
value = metrics.get(metric_name)
if value is None:
raise KeyError(
f"Configured best-checkpoint metric {metric_name!r} for strategy {strategy} "
f"is missing from metrics payload keys={sorted(metrics.keys())}."
)
return float(value)
def _early_stopping_monitor_name(strategy: int) -> str:
raw = str(_job_param("early_stopping_monitor", DEFAULT_EARLY_STOPPING_MONITOR)).strip()
if not raw or raw.lower() == "auto":
return _strategy_selection_metric_name(strategy)
return raw
def _early_stopping_mode(strategy: int, monitor_name: str | None = None) -> str:
raw = str(_job_param("early_stopping_mode", DEFAULT_EARLY_STOPPING_MODE)).strip().lower()
if raw in {"min", "max"}:
return raw
if raw != "auto":
raise ValueError(f"Unsupported early_stopping_mode={raw!r}. Expected 'auto', 'min', or 'max'.")
monitor_name = monitor_name or _early_stopping_monitor_name(strategy)
lowered = monitor_name.lower()
if "loss" in lowered or lowered.startswith("hd") or lowered.endswith("error"):
return "min"
return "max"
def _early_stopping_min_delta() -> float:
return max(float(_job_param("early_stopping_min_delta", DEFAULT_EARLY_STOPPING_MIN_DELTA)), 0.0)
def _early_stopping_start_epoch() -> int:
return max(int(_job_param("early_stopping_start_epoch", DEFAULT_EARLY_STOPPING_START_EPOCH)), 1)
def _early_stopping_patience() -> int:
return max(int(_job_param("early_stopping_patience", EARLY_STOPPING_PATIENCE)), 0)
def _early_stopping_monitor_value(
metrics: dict[str, Any],
*,
strategy: int,
monitor_name: str,
) -> float | None:
value = metrics.get(monitor_name)
if value is None and monitor_name == _strategy_selection_metric_name(strategy):
value = _strategy_selection_metric_value(strategy, metrics)
if value is None:
return None
return float(value)
def _early_stopping_improved(
current_value: float,
best_value: float | None,
*,
mode: str,
min_delta: float,
) -> bool:
if best_value is None:
return True
if mode == "min":
return current_value < (best_value - min_delta)
if mode == "max":
return current_value > (best_value + min_delta)
raise ValueError(f"Unsupported early stopping comparison mode: {mode!r}")
def _strategy3_direct_binary_actions(action_count: int | None = None) -> bool:
del action_count
return True
def _strategy3_requested_bootstrap_freeze() -> bool:
return bool(
_job_param(
"strategy3_freeze_bootstrapped_segmentation",
DEFAULT_STRATEGY3_FREEZE_BOOTSTRAPPED_SEGMENTATION,
)
)
def _module_freeze_state(module: nn.Module | None) -> str:
if not isinstance(module, nn.Module):
return "n/a"
requires_grad_flags = [bool(param.requires_grad) for param in module.parameters()]
if not requires_grad_flags:
return "n/a"
if all(not flag for flag in requires_grad_flags):
return "frozen"
if all(requires_grad_flags):
return "trainable"
return "mixed"
def _strategy3_bootstrap_freeze_status(model: nn.Module) -> dict[str, Any]:
raw = _raw_decoder_rl_model(model)
status = {
"bootstrap_loaded": False,
"freeze_requested": False,
"freeze_active": False,
"encoder_state": "n/a",
"decoder_state": "n/a",
"segmentation_head_state": "n/a",
}
if raw is None:
return status
status["bootstrap_loaded"] = bool(getattr(raw, "strategy2_bootstrap_loaded", False))
status["freeze_requested"] = bool(getattr(raw, "freeze_bootstrapped_segmentation", False))
smp_model = getattr(raw, "smp_model", None)
if smp_model is not None:
status["encoder_state"] = _module_freeze_state(getattr(smp_model, "encoder", None))
status["decoder_state"] = _module_freeze_state(getattr(smp_model, "decoder", None))
status["segmentation_head_state"] = _module_freeze_state(getattr(smp_model, "segmentation_head", None))
else:
status["encoder_state"] = _module_freeze_state(getattr(raw, "encoder", None))
status["segmentation_head_state"] = _module_freeze_state(getattr(raw, "segmentation_head", None))
relevant_states = [
state
for state in (
status["encoder_state"],
status["decoder_state"],
status["segmentation_head_state"],
)
if state != "n/a"
]
status["freeze_active"] = bool(
status["bootstrap_loaded"] and relevant_states and all(state == "frozen" for state in relevant_states)
)
return status
def _strategy3_decoder_is_frozen(model: nn.Module) -> bool:
return bool(_strategy3_bootstrap_freeze_status(model)["freeze_active"])
def _strategy3_loss_weights(
model: nn.Module,
*,
ce_weight: float,
dice_weight: float,
) -> dict[str, float]:
decoder_ce_default = 0.0 if _strategy3_decoder_is_frozen(model) else float(ce_weight)
decoder_dice_default = 0.0 if _strategy3_decoder_is_frozen(model) else float(dice_weight)
return {
"decoder_ce": float(_job_param("strategy3_decoder_ce_weight", decoder_ce_default)),
"decoder_dice": float(_job_param("strategy3_decoder_dice_weight", decoder_dice_default)),
"aux_ce": float(_job_param("strategy3_aux_ce_weight", ce_weight)),
"aux_dice": float(_job_param("strategy3_aux_dice_weight", dice_weight)),
}
def _strategy3_keep_frozen_modules_in_eval(model: nn.Module) -> None:
raw = _raw_decoder_rl_model(model)
if raw is None or not bool(_strategy3_bootstrap_freeze_status(model)["freeze_active"]):
return
smp_model = getattr(raw, "smp_model", None)
if smp_model is not None:
module_names = ("encoder", "decoder", "segmentation_head")
module_root = smp_model
else:
module_names = ("encoder", "segmentation_head")
module_root = raw
for module_name in module_names:
module = getattr(module_root, module_name, None)
if isinstance(module, nn.Module):
module.eval()
def _strategy3_apply_rollout_step(
seg: torch.Tensor,
actions: torch.Tensor,
*,
num_actions: int = 5,
decoder_prior: torch.Tensor | None = None,
) -> torch.Tensor:
return apply_actions(
seg,
actions,
soft_update_step=float(_job_param("refine_delta_small", 0.10)),
num_actions=num_actions,
decoder_prior=decoder_prior,
).to(dtype=seg.dtype)
def _refinement_deltas(*, device: torch.device, dtype: torch.dtype) -> torch.Tensor:
small = float(_job_param("refine_delta_small", 0.10))
large = float(_job_param("refine_delta_large", 0.25))
return torch.tensor([-large, -small, 0.0, small, large], device=device, dtype=dtype)
def threshold_binary_mask(mask: torch.Tensor, threshold: float | None = None) -> torch.Tensor:
threshold = float(_job_param("threshold", CONTROLLED_MASK_THRESHOLD)) if threshold is None else float(threshold)
return (mask > threshold).to(dtype=mask.dtype)
def threshold_binary_long(mask: torch.Tensor, threshold: float | None = None) -> torch.Tensor:
threshold = float(_job_param("threshold", CONTROLLED_MASK_THRESHOLD)) if threshold is None else float(threshold)
return (mask > threshold).long()
"""=============================================================================
BUSI SPLIT + NORMALIZATION
=============================================================================
"""
IMAGENET_MEAN = np.array([0.485, 0.456, 0.406], dtype=np.float32)
IMAGENET_STD = np.array([0.229, 0.224, 0.225], dtype=np.float32)
def validate_image_mask_consistency(images_dir: Path, annotations_dir: Path):
image_files = {f for f in os.listdir(images_dir) if not f.startswith(".") and f.lower().endswith(".png")}
mask_files = {f for f in os.listdir(annotations_dir) if not f.startswith(".") and f.lower().endswith(".png")}
matched = sorted(image_files & mask_files)
missing_masks = sorted(image_files - mask_files)
missing_images = sorted(mask_files - image_files)
return matched, missing_masks, missing_images
def parse_busi_with_classes_label(filename: str) -> str:
upper_name = str(filename).upper()
if upper_name.endswith("_B.PNG"):
return "benign"
if upper_name.endswith("_M.PNG"):
return "malignant"
raise ValueError(
f"BUSI_with_classes filename must end with '_B.png' or '_M.png', got {filename!r}"
)
def _candidate_report_dicts(payload: dict[str, Any]) -> list[dict[str, Any]]:
candidates = [payload]
for key in ("counts", "summary", "dataset", "report", "metadata"):
value = payload.get(key)
if isinstance(value, dict):
candidates.append(value)
return candidates
def _extract_report_int(payload: dict[str, Any], keys: tuple[str, ...]) -> int | None:
for candidate in _candidate_report_dicts(payload):
for key in keys:
value = candidate.get(key)
if isinstance(value, bool):
continue
if isinstance(value, (int, np.integer)):
return int(value)
if isinstance(value, float) and float(value).is_integer():
return int(value)
return None
def _extract_report_filenames(payload: dict[str, Any]) -> set[str] | None:
for candidate in _candidate_report_dicts(payload):
filenames = candidate.get("filenames")
if isinstance(filenames, list) and all(isinstance(item, str) for item in filenames):
return set(filenames)
pairs = candidate.get("pairs")
if isinstance(pairs, list):
extracted = {item["filename"] for item in pairs if isinstance(item, dict) and isinstance(item.get("filename"), str)}
if extracted:
return extracted
return None
def validate_busi_with_classes_pipeline_report(report_path: Path, sample_records: list[dict[str, str]]) -> None:
if not report_path.exists():
return
payload = load_json(report_path)
if not isinstance(payload, dict):
raise RuntimeError(f"Expected dict payload in {report_path}, found {type(payload).__name__}.")
benign_count = sum(1 for record in sample_records if record.get("class_label") == "benign")
malignant_count = sum(1 for record in sample_records if record.get("class_label") == "malignant")
expected_counts = {
"total_pairs": len(sample_records),
"benign": benign_count,
"malignant": malignant_count,
}
report_counts = {
"total_pairs": _extract_report_int(payload, ("total_pairs", "pair_count", "num_pairs", "total")),
"benign": _extract_report_int(payload, ("benign", "benign_count", "num_benign")),
"malignant": _extract_report_int(payload, ("malignant", "malignant_count", "num_malignant")),
}
for key, expected_value in expected_counts.items():
report_value = report_counts[key]
if report_value is not None and report_value != expected_value:
raise RuntimeError(
f"pipeline_check mismatch for {key}: discovered={expected_value}, report={report_value} ({report_path})"
)
report_filenames = _extract_report_filenames(payload)
if report_filenames is not None:
discovered_filenames = {record["filename"] for record in sample_records}
if report_filenames != discovered_filenames:
missing_from_report = sorted(discovered_filenames - report_filenames)[:10]
extra_in_report = sorted(report_filenames - discovered_filenames)[:10]
raise RuntimeError(
f"pipeline_check filenames mismatch for {report_path}: "
f"missing_from_report={missing_from_report}, extra_in_report={extra_in_report}"
)
print(f"[Pipeline Check] Validated BUSI_with_classes metadata from {report_path}")
def check_data_leakage(splits: dict[str, list[str]]) -> dict[str, list[str]]:
leaks: dict[str, list[str]] = {}
split_names = list(splits.keys())
for i, lhs in enumerate(split_names):
for rhs in split_names[i + 1 :]:
overlap = sorted(set(splits[lhs]) & set(splits[rhs]))
if overlap:
leaks[f"{lhs} ∩ {rhs}"] = overlap
return leaks
def _project_relative_path(path: Path) -> str:
resolved = Path(path).resolve()
try:
return str(resolved.relative_to(PROJECT_DIR.resolve()))
except ValueError:
return str(resolved)
def resolve_dataset_root_from_registry(split_registry: dict[str, Any]) -> Path:
dataset_root = Path(split_registry["dataset_root"])
if dataset_root.is_absolute():
return dataset_root
return (PROJECT_DIR / dataset_root).resolve()
def make_sample_record(
filename: str,
images_subdir: str,
annotations_subdir: str,
*,
class_label: str | None = None,
) -> dict[str, str]:
record = {
"filename": filename,
"image_rel_path": str(Path(images_subdir) / filename),
"mask_rel_path": str(Path(annotations_subdir) / filename),
}
if class_label is not None:
record["class_label"] = class_label
return record
def build_sample_records(
filenames: list[str],
*,
images_subdir: str,
annotations_subdir: str,
dataset_name: str,
) -> list[dict[str, str]]:
records = []
for filename in sorted(filenames):
class_label = parse_busi_with_classes_label(filename) if dataset_name == "BUSI_with_classes" else None
records.append(
make_sample_record(
filename,
images_subdir,
annotations_subdir,
class_label=class_label,
)
)
return records
def split_ratios_for_type(split_type: str) -> tuple[float, float]:
if split_type == "80_10_10":
return 0.80, 0.10
if split_type == "70_10_20":
return 0.70, 0.10
raise ValueError(f"Unsupported split_type: {split_type}")
def deterministic_shuffle_records(records: list[dict[str, str]], *, seed: int, tag: str) -> list[dict[str, str]]:
rng = random.Random(seed + stable_int_from_text(tag))
shuffled = [dict(record) for record in records]
rng.shuffle(shuffled)
return shuffled
def train_subset_variant_suffix(variant: int | None = None) -> str:
variant_value = int(TRAIN_SUBSET_VARIANT if variant is None else variant)
return "" if variant_value <= 0 else f"_variant{variant_value:02d}"
def group_records_by_class(sample_records: list[dict[str, str]]) -> dict[str, list[dict[str, str]]]:
grouped: dict[str, list[dict[str, str]]] = {}
for record in sample_records:
class_label = record.get("class_label")
if class_label is None:
raise RuntimeError("Expected class_label in sample record for class-aware splitting.")
grouped.setdefault(class_label, []).append(dict(record))
return grouped
def allocate_counts_by_ratio(total_size: int, available_counts: dict[str, int]) -> dict[str, int]:
allocation = {label: 0 for label in available_counts}
if total_size <= 0 or not available_counts:
return allocation
total_available = sum(available_counts.values())
if total_available <= 0:
return allocation
exact = {label: total_size * available_counts[label] / total_available for label in available_counts}
for label in available_counts:
allocation[label] = min(available_counts[label], int(math.floor(exact[label])))
remaining = min(total_size, total_available) - sum(allocation.values())
order = sorted(
available_counts.keys(),
key=lambda label: (exact[label] - math.floor(exact[label]), available_counts[label], label),
reverse=True,
)
while remaining > 0:
progressed = False
for label in order:
if allocation[label] < available_counts[label]:
allocation[label] += 1
remaining -= 1
progressed = True
if remaining == 0:
break
if not progressed:
break
return allocation
def allocate_balanced_counts(total_size: int, available_counts: dict[str, int]) -> dict[str, int]:
allocation = {label: 0 for label in available_counts}
if total_size <= 0 or not available_counts:
return allocation
labels = sorted(available_counts.keys())
half = total_size // 2
for label in labels:
allocation[label] = min(available_counts[label], half)
remaining = min(total_size, sum(available_counts.values())) - sum(allocation.values())
while remaining > 0:
candidates = [label for label in labels if allocation[label] < available_counts[label]]
if not candidates:
break
best_label = max(
candidates,
key=lambda label: (
available_counts[label] - allocation[label],
1 if label == "benign" else 0,
label,
),
)
allocation[best_label] += 1
remaining -= 1
return allocation
def build_unstratified_base_split(
sample_records: list[dict[str, str]],
*,
split_type: str,
seed: int,
) -> dict[str, list[dict[str, str]]]:
train_ratio, val_ratio = split_ratios_for_type(split_type)
records = deterministic_shuffle_records(sample_records, seed=seed, tag=f"base::{split_type}")
total_samples = len(records)
train_end = int(total_samples * train_ratio)
val_end = int(total_samples * (train_ratio + val_ratio))
return {
"train": records[:train_end],
"val": records[train_end:val_end],
"test": records[val_end:],
}
def build_stratified_base_split(
sample_records: list[dict[str, str]],
*,
split_type: str,
seed: int,
) -> dict[str, list[dict[str, str]]]:
train_ratio, val_ratio = split_ratios_for_type(split_type)
grouped = group_records_by_class(sample_records)
splits = {"train": [], "val": [], "test": []}
for class_label in sorted(grouped.keys()):
records = deterministic_shuffle_records(
grouped[class_label],
seed=seed,
tag=f"base::{split_type}::{class_label}",
)
total_samples = len(records)
train_end = int(total_samples * train_ratio)
val_end = int(total_samples * (train_ratio + val_ratio))
splits["train"].extend(records[:train_end])
splits["val"].extend(records[train_end:val_end])
splits["test"].extend(records[val_end:])
for split_name in splits:
splits[split_name] = deterministic_shuffle_records(
splits[split_name],
seed=seed,
tag=f"base::{split_type}::{split_name}",
)
return splits
def build_balanced_train_base_split(
sample_records: list[dict[str, str]],
*,
split_type: str,
seed: int,
) -> dict[str, list[dict[str, str]]]:
train_ratio, val_ratio = split_ratios_for_type(split_type)
test_ratio = 1.0 - train_ratio - val_ratio
grouped = group_records_by_class(sample_records)
if sorted(grouped.keys()) != ["benign", "malignant"]:
raise RuntimeError(
f"balanced_train split policy expects benign/malignant classes, found {sorted(grouped.keys())}"
)
shuffled = {
class_label: deterministic_shuffle_records(
records,
seed=seed,
tag=f"base::{split_type}::balanced_train::{class_label}",
)
for class_label, records in grouped.items()
}
nominal_train_size = int(len(sample_records) * train_ratio)
per_class_train = min(
nominal_train_size // 2,
*(len(records) for records in shuffled.values()),
)
train_records: list[dict[str, str]] = []
remaining_by_class: dict[str, list[dict[str, str]]] = {}
for class_label in sorted(shuffled.keys()):
records = shuffled[class_label]
train_records.extend(records[:per_class_train])
remaining_by_class[class_label] = records[per_class_train:]
remainder_val_fraction = val_ratio / max(val_ratio + test_ratio, 1e-8)
val_records: list[dict[str, str]] = []
test_records: list[dict[str, str]] = []
for class_label in sorted(remaining_by_class.keys()):
records = remaining_by_class[class_label]
val_count = int(len(records) * remainder_val_fraction)
val_records.extend(records[:val_count])
test_records.extend(records[val_count:])
return {
"train": deterministic_shuffle_records(
train_records,
seed=seed,
tag=f"base::{split_type}::balanced_train::train",
),
"val": deterministic_shuffle_records(
val_records,
seed=seed,
tag=f"base::{split_type}::balanced_train::val",
),
"test": deterministic_shuffle_records(
test_records,
seed=seed,
tag=f"base::{split_type}::balanced_train::test",
),
}
def build_nested_train_subsets(
train_records: list[dict[str, str]],
train_fractions: list[float],
*,
split_type: str,
seed: int,
split_policy: str | None = None,
subset_variant: int = 0,
) -> dict[str, list[dict[str, str]]]:
if not train_records:
return {}
variant_tag = "" if int(subset_variant) <= 0 else f"::variant::{int(subset_variant)}"
ordered_records = deterministic_shuffle_records(train_records, seed=seed, tag=f"subset::{split_type}{variant_tag}")
use_class_labels = any("class_label" in record for record in train_records)
if not use_class_labels:
subsets: dict[str, list[dict[str, str]]] = {}
for fraction in normalize_dataset_percents(train_fractions):
if fraction <= 0.0 or fraction > 1.0:
raise ValueError(f"Invalid training fraction: {fraction}")
subset_key = percent_label(fraction)
subset_size = len(ordered_records) if fraction >= 1.0 else max(1, int(len(ordered_records) * fraction))
subsets[subset_key] = [dict(record) for record in ordered_records[:subset_size]]
return subsets
grouped = {
class_label: deterministic_shuffle_records(
records,
seed=seed,
tag=f"subset::{split_type}::{split_policy or 'stratified'}::{class_label}{variant_tag}",
)
for class_label, records in group_records_by_class(train_records).items()
}
available_counts = {class_label: len(records) for class_label, records in grouped.items()}
subsets: dict[str, list[dict[str, str]]] = {}
for fraction in normalize_dataset_percents(train_fractions):
if fraction <= 0.0 or fraction > 1.0:
raise ValueError(f"Invalid training fraction: {fraction}")
subset_key = percent_label(fraction)
subset_size = len(ordered_records) if fraction >= 1.0 else max(1, int(len(ordered_records) * fraction))
if split_policy == "balanced_train":
class_counts = allocate_balanced_counts(subset_size, available_counts)
else:
class_counts = allocate_counts_by_ratio(subset_size, available_counts)
subset_records: list[dict[str, str]] = []
for class_label in sorted(grouped.keys()):
subset_records.extend([dict(record) for record in grouped[class_label][: class_counts[class_label]]])
subsets[subset_key] = deterministic_shuffle_records(
subset_records,
seed=seed,
tag=f"subset::{split_type}::{split_policy or 'stratified'}::{subset_key}{variant_tag}",
)
return subsets
def train_fraction_from_subset_key(subset_key: str) -> float:
subset_text = str(subset_key).strip().lower()
if not subset_text:
raise RuntimeError(f"Invalid train subset key {subset_key!r} in dataset_splits.json.")
try:
percent = Decimal(subset_text.replace("p", "."))
except InvalidOperation as exc:
raise RuntimeError(f"Invalid train subset key {subset_key!r} in dataset_splits.json.") from exc
if not percent.is_finite() or percent <= 0 or percent > 100:
raise RuntimeError(f"Train subset key {subset_key!r} must represent a percentage in the range (0, 100].")
return float(percent / Decimal("100"))
def validate_persisted_split_no_leakage(split_type: str, split_entry: dict[str, Any], *, source: str) -> None:
base_splits = split_entry["base_splits"]
base_filenames: dict[str, list[str]] = {}
for split_name, records in base_splits.items():
filenames = [record["filename"] for record in records]
if len(filenames) != len(set(filenames)):
raise RuntimeError(f"Duplicate filenames detected inside {split_name} for split_type={split_type}.")
base_filenames[split_name] = filenames
leaks = check_data_leakage(base_filenames)
if leaks:
raise RuntimeError(f"Data leakage detected for split_type={split_type}: {list(leaks.keys())}")
base_train = set(base_filenames["train"])
previous_subset: set[str] = set()
for subset_key in sorted(split_entry["train_subsets"].keys(), key=train_fraction_from_subset_key):
subset_filenames = [record["filename"] for record in split_entry["train_subsets"][subset_key]]
if len(subset_filenames) != len(set(subset_filenames)):
raise RuntimeError(
f"Duplicate filenames detected inside train subset {subset_key} for split_type={split_type}."
)
subset_set = set(subset_filenames)
missing = sorted(subset_set - base_train)
if missing:
raise RuntimeError(
f"Train subset {subset_key} contains files outside the base train split for split_type={split_type}."
)
if previous_subset and not previous_subset.issubset(subset_set):
raise RuntimeError(
f"Train subsets are not nested for split_type={split_type}."
)
previous_subset = subset_set
print(f"[Split Check] No data leakage detected for split_type={split_type} ({source}).")
def repair_persisted_train_subsets(
split_registry: dict[str, Any],
requested_train_fractions: list[float],
*,
split_json_path: Path,
seed: int,
) -> bool:
split_entries = split_registry.get("split_types", {})
requested_fractions = normalize_dataset_percents(requested_train_fractions)
combined_fractions = {float(value) for value in split_registry.get("train_fractions", [])}
combined_fractions.update(requested_fractions)
dataset_name = str(split_registry.get("dataset_name", "BUSI"))
split_policy = split_registry.get("split_policy") if dataset_name == "BUSI_with_classes" else None
for split_type in SUPPORTED_SPLIT_TYPES:
split_entry = split_entries[split_type]
train_subsets = split_entry.get("train_subsets", {})
for subset_key in train_subsets.keys():
combined_fractions.add(train_fraction_from_subset_key(subset_key))
combined_fractions_list = normalize_dataset_percents(list(combined_fractions))
requested_keys = {percent_label(fraction) for fraction in requested_fractions}
registry_seed = int(split_registry.get("seed", seed))
repaired = False
if split_registry.get("train_fractions") != combined_fractions_list:
split_registry["train_fractions"] = combined_fractions_list
repaired = True
for split_type in SUPPORTED_SPLIT_TYPES:
split_entry = split_entries[split_type]
train_subsets = split_entry.get("train_subsets", {})
missing_requested_keys = sorted(requested_keys - set(train_subsets.keys()), key=train_fraction_from_subset_key)
if not missing_requested_keys:
continue
split_entry["train_subsets"] = build_nested_train_subsets(
split_entry["base_splits"]["train"],
combined_fractions_list,
split_type=split_type,
seed=registry_seed,
split_policy=split_policy,
)
print(
f"[Splits] Rebuilt missing train subsets {missing_requested_keys} "
f"for split_type={split_type} in {split_json_path}"
)
repaired = True
if repaired:
save_json(split_json_path, split_registry)
print(f"[Splits] Updated persisted dataset splits at {split_json_path}")
return repaired
def load_or_create_dataset_splits(
images_dir: Path,
annotations_dir: Path,
split_json_path: Path,
train_fractions: list[float],
seed: int,
) -> tuple[dict[str, Any], str]:
train_fractions = normalize_dataset_percents(train_fractions)
images_dir = Path(images_dir).resolve()
annotations_dir = Path(annotations_dir).resolve()
split_json_path = Path(split_json_path).resolve()
dataset_name = current_dataset_name()
split_policy = current_busi_with_classes_split_policy() if dataset_name == "BUSI_with_classes" else None
if split_json_path.exists():
split_registry = load_json(split_json_path)
if split_registry.get("version") != DATASET_SPLITS_VERSION:
raise RuntimeError(
f"Unsupported dataset_splits.json version in {split_json_path}. "
f"Expected version={DATASET_SPLITS_VERSION}."
)
persisted_dataset_name = str(split_registry.get("dataset_name", "BUSI"))
if persisted_dataset_name != dataset_name:
raise RuntimeError(
f"dataset_splits.json at {split_json_path} targets dataset_name={persisted_dataset_name!r}, "
f"but current DATASET_NAME={dataset_name!r}."
)
persisted_split_policy = split_registry.get("split_policy")
if dataset_name == "BUSI_with_classes" and persisted_split_policy != split_policy:
raise RuntimeError(
f"dataset_splits.json at {split_json_path} targets split_policy={persisted_split_policy!r}, "
f"but current BUSI_WITH_CLASSES_SPLIT_POLICY={split_policy!r}."
)
split_entries = split_registry.get("split_types")
if not isinstance(split_entries, dict):
raise RuntimeError(f"Invalid split_types payload in {split_json_path}.")
for split_type in SUPPORTED_SPLIT_TYPES:
if split_type not in split_entries:
raise RuntimeError(
f"dataset_splits.json is missing split_type={split_type}. Delete it to regenerate cleanly."
)
repaired = repair_persisted_train_subsets(
split_registry,
train_fractions,
split_json_path=split_json_path,
seed=seed,
)
source = "repaired" if repaired else "loaded"
if dataset_name == "BUSI_with_classes":
sample_records = build_sample_records(
validate_image_mask_consistency(images_dir, annotations_dir)[0],
images_subdir=split_registry["images_subdir"],
annotations_subdir=split_registry["annotations_subdir"],
dataset_name=dataset_name,
)
pipeline_check_path = current_pipeline_check_path()
if pipeline_check_path is not None:
validate_busi_with_classes_pipeline_report(pipeline_check_path, sample_records)
for split_type in SUPPORTED_SPLIT_TYPES:
validate_persisted_split_no_leakage(split_type, split_entries[split_type], source=source)
if repaired:
print(f"[Splits] Loaded and repaired persisted dataset splits from {split_json_path}")
else:
print(f"[Splits] Loaded persisted dataset splits from {split_json_path}")
return split_registry, source
matched, missing_masks, missing_images = validate_image_mask_consistency(images_dir, annotations_dir)
if missing_masks or missing_images:
raise RuntimeError(
"BUSI image/mask mismatch detected. "
f"missing_masks={len(missing_masks)}, missing_images={len(missing_images)}"
)
dataset_root = images_dir.parent.resolve()
images_subdir = images_dir.relative_to(dataset_root).as_posix()
annotations_subdir = annotations_dir.relative_to(dataset_root).as_posix()
sample_records = build_sample_records(
matched,
images_subdir=images_subdir,
annotations_subdir=annotations_subdir,
dataset_name=dataset_name,
)
if dataset_name == "BUSI_with_classes":
pipeline_check_path = current_pipeline_check_path()
if pipeline_check_path is not None:
validate_busi_with_classes_pipeline_report(pipeline_check_path, sample_records)
split_registry = {
"version": DATASET_SPLITS_VERSION,
"dataset_name": dataset_name,
"split_policy": split_policy,
"dataset_root": _project_relative_path(dataset_root),
"images_subdir": images_subdir,
"annotations_subdir": annotations_subdir,
"seed": seed,
"train_fractions": list(train_fractions),
"split_types": {},
}
for split_type in SUPPORTED_SPLIT_TYPES:
if dataset_name == "BUSI_with_classes":
if split_policy == "balanced_train":
base_splits = build_balanced_train_base_split(
sample_records,
split_type=split_type,
seed=seed,
)
else:
base_splits = build_stratified_base_split(
sample_records,
split_type=split_type,
seed=seed,
)
else:
base_splits = build_unstratified_base_split(
sample_records,
split_type=split_type,
seed=seed,
)
train_subsets = build_nested_train_subsets(
base_splits["train"],
train_fractions,
split_type=split_type,
seed=seed,
split_policy=split_policy,
)
split_entry = {
"split_type": split_type,
"base_splits": base_splits,
"train_subsets": train_subsets,
}
validate_persisted_split_no_leakage(split_type, split_entry, source="created")
split_registry["split_types"][split_type] = split_entry
save_json(split_json_path, split_registry)
print(f"[Splits] Created persisted dataset splits at {split_json_path}")
return split_registry, "created"
def select_persisted_split(
split_registry: dict[str, Any],
split_type: str,
train_fraction: float,
) -> dict[str, Any]:
if split_type not in SUPPORTED_SPLIT_TYPES:
raise ValueError(f"Unsupported split_type: {split_type}")
split_entries = split_registry.get("split_types", {})
if split_type not in split_entries:
raise KeyError(
f"Requested split_type={split_type} is not available in dataset_splits.json. "
"Delete the JSON file to regenerate it with the new configuration."
)
subset_key = percent_label(train_fraction)
split_entry = split_entries[split_type]
train_subsets = split_entry.get("train_subsets", {})
if subset_key not in train_subsets:
raise KeyError(
f"Requested train fraction={train_fraction} (key={subset_key}) is not available in dataset_splits.json."
)
return {
"dataset_root": resolve_dataset_root_from_registry(split_registry),
"split_type": split_type,
"train_fraction": float(train_fraction),
"train_subset_key": subset_key,
"train_subset_variant": 0,
"train_subset_source": "persisted",
"base_train_records": split_entry["base_splits"]["train"],
"train_records": train_subsets[subset_key],
"val_records": split_entry["base_splits"]["val"],
"test_records": split_entry["base_splits"]["test"],
}
def apply_train_subset_variant(
selected_split: dict[str, Any],
split_registry: dict[str, Any],
*,
subset_variant: int,
) -> dict[str, Any]:
variant = int(subset_variant)
if variant <= 0 or float(selected_split["train_fraction"]) >= 1.0:
return selected_split
split_policy = split_registry.get("split_policy") if current_dataset_name() == "BUSI_with_classes" else None
variant_subsets = build_nested_train_subsets(
selected_split["base_train_records"],
[float(selected_split["train_fraction"])],
split_type=str(selected_split["split_type"]),
seed=int(split_registry.get("seed", SEED)),
split_policy=split_policy,
subset_variant=variant,
)
subset_key = str(selected_split["train_subset_key"])
updated_split = dict(selected_split)
updated_split["train_records"] = variant_subsets[subset_key]
updated_split["train_subset_variant"] = variant
updated_split["train_subset_source"] = "variant_override"
return updated_split
def export_selected_split_manifest(
pct_root: Path,
*,
percent: float,
split_source: str,
selected_split: dict[str, Any],
) -> Path:
variant_suffix = train_subset_variant_suffix(int(selected_split.get("train_subset_variant", 0)))
manifest_path = pct_root / (
f"selected_split_{selected_split['split_type']}_{percent_label(percent)}pct{variant_suffix}.json"
)
payload = {
"dataset_name": current_dataset_name(),
"dataset_root": str(Path(selected_split["dataset_root"]).resolve()),
"dataset_percent": float(percent),
"dataset_percent_label": percent_label(percent),
"split_source": split_source,
"split_type": str(selected_split["split_type"]),
"train_fraction": float(selected_split["train_fraction"]),
"train_subset_key": str(selected_split["train_subset_key"]),
"train_subset_variant": int(selected_split.get("train_subset_variant", 0)),
"train_subset_source": str(selected_split.get("train_subset_source", "persisted")),
"selected_split_manifest_path": str(manifest_path.resolve()),
"base_train_records": [dict(record) for record in selected_split["base_train_records"]],
"train_records": [dict(record) for record in selected_split["train_records"]],
"val_records": [dict(record) for record in selected_split["val_records"]],
"test_records": [dict(record) for record in selected_split["test_records"]],
}
save_json(manifest_path, payload)
return manifest_path
def compute_busi_statistics(
dataset_root: Path,
sample_records: list[dict[str, str]],
cache_path: Path,
) -> tuple[float, float, str]:
filenames = [record["filename"] for record in sample_records]
if cache_path.exists():
stats = load_json(cache_path)
if stats.get("filenames") == filenames:
print(f"[Normalization] Loaded cached normalization stats from {cache_path}")
return float(stats["global_mean"]), float(stats["global_std"]), "loaded_from_cache"
total_sum = np.float64(0.0)
total_sq_sum = np.float64(0.0)
total_pixels = 0
for record in tqdm(sample_records, desc="Computing BUSI train mean/std", leave=False):
image_path = dataset_root / record["image_rel_path"]
img = np.array(PILImage.open(image_path)).astype(np.float64)
total_sum += img.sum()
total_sq_sum += (img ** 2).sum()
total_pixels += img.size
global_mean = float(total_sum / total_pixels)
global_std = float(np.sqrt(total_sq_sum / total_pixels - global_mean ** 2))
if global_std < 1e-6:
global_std = 1.0
save_json(
cache_path,
{
"global_mean": global_mean,
"global_std": global_std,
"total_pixels": int(total_pixels),
"num_images": len(sample_records),
"filenames": filenames,
},
)
print(f"[Normalization] Computed and saved normalization stats to {cache_path}")
return global_mean, global_std, "computed_fresh"
def compute_class_distribution(sample_records: list[dict[str, str]]) -> dict[str, int] | None:
if not sample_records or not any("class_label" in record for record in sample_records):
return None
return {
"benign": sum(1 for record in sample_records if record.get("class_label") == "benign"),
"malignant": sum(1 for record in sample_records if record.get("class_label") == "malignant"),
}
def format_class_distribution(class_distribution: dict[str, int] | None) -> str:
if class_distribution is None:
return "unavailable"
benign = int(class_distribution.get("benign", 0))
malignant = int(class_distribution.get("malignant", 0))
total = benign + malignant
return f"benign={benign}, malignant={malignant}, total={total}"
def print_loaded_class_distribution(
*,
split_type: str,
train_subset_key: str,
base_train_records: list[dict[str, str]],
train_records: list[dict[str, str]],
val_records: list[dict[str, str]],
test_records: list[dict[str, str]],
) -> None:
if not any("class_label" in record for record in train_records):
return
section(f"Loaded Class Distribution | {split_type} | {train_subset_key}%")
print(f"Base train classes : {format_class_distribution(compute_class_distribution(base_train_records))}")
print(f"Train subset classes : {format_class_distribution(compute_class_distribution(train_records))}")
print(f"Validation classes : {format_class_distribution(compute_class_distribution(val_records))}")
print(f"Test classes : {format_class_distribution(compute_class_distribution(test_records))}")
def print_split_summary(payload: dict[str, Any]) -> None:
section(f"Split Summary | {payload['split_type']} | {payload['train_subset_key']}%")
print(f"Dataset name : {payload['dataset_name']}")
if payload.get("dataset_split_policy") is not None:
print(f"Dataset split policy : {payload['dataset_split_policy']}")
print(f"Dataset splits JSON : {payload['dataset_splits_path']}")
print(f"Split source : {payload['split_source']}")
print(f"Split type used : {payload['split_type']}")
if payload.get("percent_sampling_mode") is not None:
print(f"Percent sampling mode : {payload['percent_sampling_mode']}")
print(f"Train fraction : {payload['train_subset_key']}% of frozen base train")
print(f"Train subset variant : {payload.get('train_subset_variant', 0)}")
print(f"Train subset source : {payload.get('train_subset_source', 'persisted')}")
if payload.get("sampling_chain_dataset_percents") is not None:
print(f"Sampling chain percents: {payload['sampling_chain_dataset_percents']}")
print(f"Base train samples : {payload['base_train_count']}")
print(f"Train subset samples : {payload['train_count']}")
print(f"Validation samples : {payload['val_count']}")
print(f"Test samples : {payload['test_count']}")
if payload.get("base_train_class_distribution") is not None:
print(f"Base train classes : {format_class_distribution(payload['base_train_class_distribution'])}")
print(f"Train subset classes : {format_class_distribution(payload['train_class_distribution'])}")
print(f"Validation classes : {format_class_distribution(payload['val_class_distribution'])}")
print(f"Test classes : {format_class_distribution(payload['test_class_distribution'])}")
print(f"Validation/Test frozen : {payload['val_test_frozen']}")
print(f"Leakage check : {payload['leakage_check']}")
def print_normalization_summary(payload: dict[str, Any]) -> None:
mode = "ImageNet mean/std" if USE_IMAGENET_NORM else "Dataset train mean/std"
print(f"Dataset name : {payload['dataset_name']}")
print(f"Normalization mode : {mode}")
print(f"Stats cache path : {payload['normalization_cache_path']}")
print(f"Stats source : {payload['normalization_source']}")
print(f"Split type used : {payload['split_type']}")
variant_suffix = train_subset_variant_suffix(int(payload.get("train_subset_variant", 0)))
print(
f"Stats computed from : {payload['train_count']} train samples "
f"({payload['train_subset_key']}%{variant_suffix})"
)
# =============================================================================
# IMAGE PREPARATION + DATASETS
# =============================================================================
def _to_three_channels(image: np.ndarray) -> np.ndarray:
if image.ndim == 2:
image = image[..., None]
if image.shape[2] == 1:
image = np.repeat(image, 3, axis=2)
elif image.shape[2] > 3:
image = image[..., :3]
return image
def _prepare_image(raw: np.ndarray, global_mean: float, global_std: float) -> np.ndarray:
img = raw.astype(np.float32)
img = _to_three_channels(img)
if IMG_SIZE > 0 and (img.shape[0] != IMG_SIZE or img.shape[1] != IMG_SIZE):
img = np.array(
PILImage.fromarray(img.astype(np.uint8)).resize((IMG_SIZE, IMG_SIZE), PILImage.BILINEAR)
).astype(np.float32)
if USE_IMAGENET_NORM:
if img.max() > 1.0:
img = img / 255.0
img = (img - IMAGENET_MEAN) / IMAGENET_STD
else:
img = (img - global_mean) / global_std
return np.transpose(img, (2, 0, 1)).copy()
def _prepare_mask(raw: np.ndarray) -> np.ndarray:
mask = raw.astype(np.uint8)
if mask.ndim == 3:
mask = mask[..., 0]
if IMG_SIZE > 0 and (mask.shape[0] != IMG_SIZE or mask.shape[1] != IMG_SIZE):
pil_mask = PILImage.fromarray(mask)
if pil_mask.mode != "L":
pil_mask = pil_mask.convert("L")
mask = np.array(pil_mask.resize((IMG_SIZE, IMG_SIZE), PILImage.NEAREST))
return ((mask > 0).astype(np.float32))[None, ...].copy()
def print_imagenet_normalization_status() -> bool:
uses_imagenet_norm = bool(USE_IMAGENET_NORM)
if uses_imagenet_norm:
print("✅🖼️ ImageNet normalization is ACTIVE in `_prepare_image`.")
else:
print("⚠️🧪 ImageNet normalization is NOT active in `_prepare_image`.")
print("⚠️📊 Using dataset global mean/std normalization instead.")
if SMP_ENCODER_WEIGHTS == "imagenet" and not uses_imagenet_norm:
print("⚠️🚨 Encoder weights are set to ImageNet, but ImageNet normalization is disabled.")
return uses_imagenet_norm
def _apply_minimal_train_aug(image: torch.Tensor, mask: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
if torch.rand(1).item() < 0.5:
image = torch.flip(image, dims=(2,))
mask = torch.flip(mask, dims=(2,))
if torch.rand(1).item() < 0.5:
image = torch.flip(image, dims=(1,))
mask = torch.flip(mask, dims=(1,))
if torch.rand(1).item() < 0.5:
k = 1 if torch.rand(1).item() < 0.5 else 3
image = torch.rot90(image, k=k, dims=(1, 2))
mask = torch.rot90(mask, k=k, dims=(1, 2))
return image.contiguous(), mask.contiguous()
class BUSIDataset(Dataset):
def __init__(
self,
sample_records: list[dict[str, str]],
dataset_root: Path,
global_mean: float,
global_std: float,
*,
preload: bool,
augment: bool,
split_name: str,
) -> None:
super().__init__()
self.sample_records = [dict(record) for record in sample_records]
self.dataset_root = Path(dataset_root)
self.global_mean = float(global_mean)
self.global_std = float(global_std)
self.preload = preload
self.augment = augment
self.split_name = split_name
self._images: list[torch.Tensor] = []
self._masks: list[torch.Tensor] = []
self._raw_cache_bytes = 0
if not self.preload:
raise ValueError("PRELOAD_TO_RAM is mandatory in this RunPod runner.")
self._preload_to_ram()
def _preload_to_ram(self) -> None:
desc = f"Preloading {self.split_name} ({len(self.sample_records)} samples) to RAM"
for record in tqdm(self.sample_records, desc=desc, leave=False):
raw_img = np.array(PILImage.open(self.dataset_root / record["image_rel_path"]))
raw_mask = np.array(PILImage.open(self.dataset_root / record["mask_rel_path"]))
if raw_img.shape[:2] != raw_mask.shape[:2]:
raise RuntimeError(
f"Image/mask spatial size mismatch for {record['filename']}: "
f"image={raw_img.shape[:2]}, mask={raw_mask.shape[:2]}"
)
image = torch.from_numpy(_prepare_image(raw_img, self.global_mean, self.global_std))
mask = torch.from_numpy(_prepare_mask(raw_mask))
self._raw_cache_bytes += tensor_bytes(image) + tensor_bytes(mask)
self._images.append(image)
self._masks.append(mask)
def __len__(self) -> int:
return len(self.sample_records)
def __getitem__(self, index: int) -> dict[str, Any]:
image = self._images[index].clone()
mask = self._masks[index].clone()
if self.augment:
image, mask = _apply_minimal_train_aug(image, mask)
return {
"image": image,
"mask": mask,
"sample_id": Path(self.sample_records[index]["filename"]).stem,
"dataset": current_dataset_name(),
}
@property
def cache_bytes(self) -> int:
return self._raw_cache_bytes
class CUDAPrefetcher:
def __init__(self, loader: DataLoader, device: torch.device) -> None:
self.loader = loader
self.device = device
self._use_cuda = device.type == "cuda"
self._iter = None
self._stream = None
self._next_batch = None
def __len__(self) -> int:
return len(self.loader)
def __iter__(self):
self._iter = iter(self.loader)
self._stream = torch.cuda.Stream(device=self.device) if self._use_cuda else None
self._next_batch = None
self._preload()
return self
def close(self) -> None:
self._next_batch = None
self._iter = None
self._stream = None
def _preload(self) -> None:
if self._iter is None:
self._next_batch = None
return
try:
self._next_batch = next(self._iter)
except StopIteration:
self._next_batch = None
return
if self._use_cuda:
assert self._stream is not None
with torch.cuda.stream(self._stream):
self._next_batch = to_device(self._next_batch, self.device)
else:
self._next_batch = to_device(self._next_batch, self.device)
def __next__(self):
if self._next_batch is None:
self.close()
raise StopIteration
if self._use_cuda:
assert self._stream is not None
torch.cuda.current_stream(self.device).wait_stream(self._stream)
batch = self._next_batch
self._preload()
if self._next_batch is None:
self._iter = None
self._stream = None
return batch
class DataBundle:
def __init__(
self,
*,
percent: float,
split_payload: dict[str, Any],
train_ds: BUSIDataset,
val_ds: BUSIDataset,
test_ds: BUSIDataset,
train_loader: DataLoader,
val_loader: DataLoader,
test_loader: DataLoader,
) -> None:
self.percent = percent
self.split_payload = split_payload
self.train_ds = train_ds
self.val_ds = val_ds
self.test_ds = test_ds
self.train_loader = train_loader
self.val_loader = val_loader
self.test_loader = test_loader
@property
def global_mean(self) -> float:
return float(self.split_payload["global_mean"])
@property
def global_std(self) -> float:
return float(self.split_payload["global_std"])
@property
def total_cache_bytes(self) -> int:
return self.train_ds.cache_bytes + self.val_ds.cache_bytes + self.test_ds.cache_bytes
def make_loader(dataset: Dataset, shuffle: bool, *, loader_tag: str) -> DataLoader:
num_workers = NUM_WORKERS
persistent_workers = USE_PERSISTENT_WORKERS and num_workers > 0
pin_memory = USE_PIN_MEMORY and DEVICE.type == "cuda"
generator = make_seeded_generator(SEED, loader_tag)
return DataLoader(
dataset,
batch_size=BATCH_SIZE,
shuffle=shuffle,
num_workers=num_workers,
pin_memory=pin_memory,
drop_last=False,
persistent_workers=persistent_workers,
worker_init_fn=seed_worker,
generator=generator,
)
def build_data_bundle(percent: float, split_registry: dict[str, Any], split_source: str) -> DataBundle:
pct_label = percent_label(percent)
pct_text = percent_text(percent)
selected_split = select_persisted_split(split_registry, SPLIT_TYPE, percent)
selected_split = apply_train_subset_variant(
selected_split,
split_registry,
subset_variant=TRAIN_SUBSET_VARIANT,
)
pct_root = ensure_dir(RUNS_ROOT / MODEL_NAME / f"pct_{pct_label}")
split_manifest_path = export_selected_split_manifest(
pct_root,
percent=percent,
split_source=split_source,
selected_split=selected_split,
)
stats_cache_path = pct_root / (
f"norm_stats_{normalization_cache_tag()}_{SPLIT_TYPE}_{pct_label}pct"
f"{train_subset_variant_suffix(int(selected_split.get('train_subset_variant', 0)))}.json"
)
base_train_class_distribution = compute_class_distribution(selected_split["base_train_records"])
train_class_distribution = compute_class_distribution(selected_split["train_records"])
val_class_distribution = compute_class_distribution(selected_split["val_records"])
test_class_distribution = compute_class_distribution(selected_split["test_records"])
print_loaded_class_distribution(
split_type=selected_split["split_type"],
train_subset_key=selected_split["train_subset_key"],
base_train_records=selected_split["base_train_records"],
train_records=selected_split["train_records"],
val_records=selected_split["val_records"],
test_records=selected_split["test_records"],
)
dataset_root = Path(selected_split["dataset_root"]).resolve()
global_mean, global_std, normalization_source = compute_busi_statistics(
dataset_root=dataset_root,
sample_records=selected_split["train_records"],
cache_path=stats_cache_path,
)
split_payload = {
"dataset_name": current_dataset_name(),
"dataset_split_policy": split_registry.get("split_policy"),
"dataset_splits_path": str(current_dataset_splits_json_path().resolve()),
"dataset_root": str(dataset_root),
"split_source": split_source,
"split_type": SPLIT_TYPE,
"dataset_percent": percent,
"train_subset_key": selected_split["train_subset_key"],
"train_subset_variant": int(selected_split.get("train_subset_variant", 0)),
"train_subset_source": str(selected_split.get("train_subset_source", "persisted")),
"selected_split_manifest_path": str(split_manifest_path.resolve()),
"base_train_count": len(selected_split["base_train_records"]),
"train_count": len(selected_split["train_records"]),
"val_count": len(selected_split["val_records"]),
"test_count": len(selected_split["test_records"]),
"base_train_class_distribution": base_train_class_distribution,
"train_class_distribution": train_class_distribution,
"val_class_distribution": val_class_distribution,
"test_class_distribution": test_class_distribution,
"val_test_frozen": True,
"leakage_check": "passed",
"global_mean": global_mean,
"global_std": global_std,
"normalization_cache_path": str(stats_cache_path.resolve()),
"normalization_source": normalization_source,
}
print_split_summary(split_payload)
print_normalization_summary(split_payload)
train_ds = BUSIDataset(
selected_split["train_records"],
dataset_root,
global_mean,
global_std,
preload=PRELOAD_TO_RAM,
augment=True,
split_name=f"train {SPLIT_TYPE} {pct_text}",
)
val_ds = BUSIDataset(
selected_split["val_records"],
dataset_root,
global_mean,
global_std,
preload=PRELOAD_TO_RAM,
augment=False,
split_name=f"val {SPLIT_TYPE}",
)
test_ds = BUSIDataset(
selected_split["test_records"],
dataset_root,
global_mean,
global_std,
preload=PRELOAD_TO_RAM,
augment=False,
split_name=f"test {SPLIT_TYPE}",
)
bundle = DataBundle(
percent=percent,
split_payload=split_payload,
train_ds=train_ds,
val_ds=val_ds,
test_ds=test_ds,
train_loader=make_loader(train_ds, shuffle=True, loader_tag=f"{SPLIT_TYPE}:{pct_label}:train"),
val_loader=make_loader(val_ds, shuffle=False, loader_tag=f"{SPLIT_TYPE}:{pct_label}:val"),
test_loader=make_loader(test_ds, shuffle=False, loader_tag=f"{SPLIT_TYPE}:{pct_label}:test"),
)
print_preload_summary(bundle)
return bundle
def print_preload_summary(bundle: DataBundle) -> None:
section(
f"RAM Preload Summary | {bundle.split_payload['split_type']} | {int(bundle.percent * 100)}%"
)
print(f"Train samples : {len(bundle.train_ds)}")
print(f"Val samples : {len(bundle.val_ds)}")
print(f"Test samples : {len(bundle.test_ds)}")
print(f"Train batches : {len(bundle.train_loader)}")
print(f"Val batches : {len(bundle.val_loader)}")
print(f"Test batches : {len(bundle.test_loader)}")
print(f"Global mean : {bundle.global_mean:.6f}")
print(f"Global std : {bundle.global_std:.6f}")
first = bundle.train_ds[0]
print(f"Sample image shape : {tuple(first['image'].shape)}")
print(f"Sample mask shape : {tuple(first['mask'].shape)}")
print(f"Sample image dtype : {first['image'].dtype}")
print(f"Sample mask dtype : {first['mask'].dtype}")
print(f"Estimated RAM preload : {bytes_to_gb(bundle.total_cache_bytes):.3f} GB")
"""=============================================================================
MODEL DEFINITIONS
=============================================================================
"""
def strategy_name(strategy: int, model_config: RuntimeModelConfig | None = None) -> str:
model_config = (model_config or current_model_config()).validate()
if model_config.backbone_family == "custom_vgg":
if strategy == 1:
return "Strategy 1: Custom VGG + RL"
if strategy == 2:
return "Strategy 2: Custom VGG + Segmentation Head (Supervised)"
if strategy == 3:
return "Strategy 3: Custom VGG + Segmentation Head + RL"
if strategy == 4:
return "Strategy 4: Frozen Custom VGG + Segmentation Head + RL"
if strategy == 5:
return "Strategy 5: Frozen Custom VGG + RL"
raise ValueError(f"Unsupported strategy: {strategy}")
if strategy == 1:
return f"Strategy 1: SMP Encoder ({model_config.smp_encoder_name}) + RL"
if strategy == 2:
return f"Strategy 2: SMP {model_config.smp_decoder_type} ({model_config.smp_encoder_name}) supervised"
if strategy == 3:
return f"Strategy 3: SMP {model_config.smp_decoder_type} ({model_config.smp_encoder_name}) + RL"
if strategy == 4:
return f"Strategy 4: Frozen SMP {model_config.smp_decoder_type} ({model_config.smp_encoder_name}) + RL"
if strategy == 5:
return f"Strategy 5: Frozen SMP Encoder ({model_config.smp_encoder_name}) + RL"
raise ValueError(f"Unsupported strategy: {strategy}")
def _apply_omega_conv(omega_conv: nn.Conv2d, value_next: torch.Tensor) -> torch.Tensor:
weight = omega_conv.weight
value_next = value_next.to(device=weight.device, dtype=weight.dtype)
return omega_conv(value_next)
def _conv3x3(in_ch: int, out_ch: int, dilation: int = 1) -> nn.Conv2d:
return nn.Conv2d(
in_ch,
out_ch,
kernel_size=3,
stride=1,
padding=dilation,
dilation=dilation,
bias=True,
)
class _ConvBlock(nn.Module):
def __init__(
self,
in_ch: int,
out_ch: int,
dilation: int = 1,
*,
num_groups: int = 0,
dropout: float = 0.0,
) -> None:
super().__init__()
self.conv = _conv3x3(in_ch, out_ch, dilation=dilation)
self.norm = _group_norm(out_ch, num_groups=num_groups) if num_groups > 0 else nn.Identity()
self.act = nn.ReLU(inplace=True)
self.drop = nn.Dropout2d(p=dropout) if dropout > 0 else nn.Identity()
def forward(self, x: torch.Tensor) -> torch.Tensor:
return self.drop(self.act(self.norm(self.conv(x))))
def _group_norm(num_channels: int, *, num_groups: int = GN_NUM_GROUPS) -> nn.GroupNorm:
groups = min(num_groups, num_channels)
while groups > 1 and num_channels % groups != 0:
groups -= 1
return nn.GroupNorm(groups, num_channels)
class _MultiScaleRefineBranch(nn.Module):
"""Processes raw encoder features at each scale independently, then fuses
them into a single feature map. This gives the refinement head access to
multi-resolution spatial cues (edges at low levels, semantics at high
levels) that the 1x1 projection squashes away."""
def __init__(
self,
encoder_channels: list[int] | tuple[int, ...],
out_channels: int,
per_scale_channels: int = 32,
) -> None:
super().__init__()
self._valid_indices: list[int] = [i for i, c in enumerate(encoder_channels) if c > 0]
self.scale_convs = nn.ModuleList()
for i in self._valid_indices:
self.scale_convs.append(nn.Sequential(
nn.Conv2d(encoder_channels[i], per_scale_channels, kernel_size=1, bias=False),
_group_norm(per_scale_channels),
nn.ReLU(inplace=True),
))
total_ch = per_scale_channels * len(self._valid_indices)
self.fuse = nn.Sequential(
nn.Conv2d(total_ch, out_channels, kernel_size=3, padding=1, bias=False),
_group_norm(out_channels),
nn.ReLU(inplace=True),
nn.Conv2d(out_channels, out_channels, kernel_size=3, padding=2, dilation=2, bias=False),
_group_norm(out_channels),
nn.ReLU(inplace=True),
)
self._init_small()
def _init_small(self) -> None:
"""Small-magnitude init so the branch starts as a near-zero residual."""
for m in self.modules():
if isinstance(m, nn.Conv2d):
nn.init.kaiming_normal_(m.weight, mode="fan_out", nonlinearity="relu")
m.weight.data.mul_(0.1)
if m.bias is not None:
nn.init.zeros_(m.bias)
def forward(
self,
encoder_features: list[torch.Tensor] | tuple[torch.Tensor, ...],
output_size: tuple[int, int],
) -> torch.Tensor:
h, w = output_size
parts: list[torch.Tensor] = []
for idx, conv in zip(self._valid_indices, self.scale_convs):
out = conv(encoder_features[idx])
if out.shape[-2] != h or out.shape[-1] != w:
out = F.interpolate(out, size=(h, w), mode="bilinear", align_corners=False)
parts.append(out)
return self.fuse(torch.cat(parts, dim=1))
class SelfAttentionModule(nn.Module):
def __init__(self, channels: int) -> None:
super().__init__()
mid = max(channels // 8, 1)
self.query = nn.Conv2d(channels, mid, 1)
self.key = nn.Conv2d(channels, mid, 1)
self.value = nn.Conv2d(channels, channels, 1)
self.gamma = nn.Parameter(torch.zeros(1))
def forward(self, f: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
b, c, h, w = f.shape
pooled = f
if h * w > ATTENTION_MAX_TOKENS:
stride_h = max(1, math.ceil(h / ATTENTION_MIN_POOL_SIZE))
stride_w = max(1, math.ceil(w / ATTENTION_MIN_POOL_SIZE))
pooled = F.avg_pool2d(f, kernel_size=(stride_h, stride_w), stride=(stride_h, stride_w))
ph, pw = pooled.shape[-2:]
q = self.query(pooled).view(b, -1, ph * pw).permute(0, 2, 1)
k = self.key(pooled).view(b, -1, ph * pw)
v = self.value(pooled).view(b, -1, ph * pw).permute(0, 2, 1)
attn = torch.softmax(q @ k / (q.shape[-1] ** 0.5), dim=-1)
out = (attn @ v).permute(0, 2, 1).view(b, c, ph, pw)
if ph != h or pw != w:
out = F.interpolate(out, size=(h, w), mode="bilinear", align_corners=False)
return f + self.gamma * out, attn
class DilatedPolicyHead(nn.Module):
def __init__(self, in_channels: int) -> None:
super().__init__()
self.body = nn.Sequential(
_ConvBlock(in_channels, 512, dilation=1),
_ConvBlock(512, 256, dilation=2),
_ConvBlock(256, 128, dilation=3),
_ConvBlock(128, 64, dilation=4),
)
self.classifier = nn.Conv2d(64, NUM_ACTIONS, kernel_size=1)
nn.init.zeros_(self.classifier.weight)
bias = torch.full((NUM_ACTIONS,), -2.0, dtype=torch.float32)
keep_index = NUM_ACTIONS // 2 if NUM_ACTIONS >= 3 else NUM_ACTIONS - 1
bias[keep_index] = 2.0
with torch.no_grad():
self.classifier.bias.copy_(bias)
def forward(self, x: torch.Tensor) -> torch.Tensor:
return self.classifier(self.body(x))
class DilatedValueHead(nn.Module):
def __init__(self, in_channels: int) -> None:
super().__init__()
self.net = nn.Sequential(
_ConvBlock(in_channels, 512, dilation=1),
_ConvBlock(512, 256, dilation=2),
_ConvBlock(256, 128, dilation=3),
_ConvBlock(128, 64, dilation=4),
nn.Conv2d(64, 1, kernel_size=1),
)
def forward(self, x: torch.Tensor) -> torch.Tensor:
return self.net(x)
def replace_bn_with_gn(model: nn.Module, num_groups: int = 8) -> nn.Module:
for name, module in model.named_children():
if isinstance(module, (nn.BatchNorm2d, nn.BatchNorm1d)):
num_channels = module.num_features
groups = min(num_groups, num_channels)
while groups > 1 and num_channels % groups != 0:
groups -= 1
setattr(model, name, nn.GroupNorm(groups, num_channels, eps=module.eps, affine=module.affine))
else:
replace_bn_with_gn(module, num_groups=num_groups)
return model
def inject_decoder_dropout(decoder: nn.Module, p: float = 0.1) -> int:
"""Insert Dropout2d after every ReLU/GELU in the SMP decoder so that
MC Dropout forward passes produce meaningful variance. Returns the
number of dropout layers injected."""
injected = 0
for name, module in list(decoder.named_children()):
if isinstance(module, nn.Sequential):
new_layers: list[nn.Module] = []
for child in module:
new_layers.append(child)
if isinstance(child, (nn.ReLU, nn.GELU, nn.LeakyReLU, nn.PReLU, nn.SiLU)):
new_layers.append(nn.Dropout2d(p=p))
injected += 1
setattr(decoder, name, nn.Sequential(*new_layers))
elif isinstance(module, (nn.ReLU, nn.GELU, nn.LeakyReLU, nn.PReLU, nn.SiLU)):
setattr(decoder, name, nn.Sequential(module, nn.Dropout2d(p=p)))
injected += 1
else:
injected += inject_decoder_dropout(module, p=p)
return injected
class HalfVGG16DilatedExtractor(nn.Module):
def __init__(self, *, dilation: int = 1, num_scales: int = 3) -> None:
super().__init__()
self.num_scales = num_scales
deep_dropout = 0.1
self.conv1_1 = _ConvBlock(3, 32, dilation=dilation, num_groups=GN_NUM_GROUPS)
self.conv1_2 = _ConvBlock(32, 32, dilation=dilation, num_groups=GN_NUM_GROUPS)
self.conv2_1 = _ConvBlock(32, 64, dilation=dilation, num_groups=GN_NUM_GROUPS)
self.conv2_2 = _ConvBlock(64, 64, dilation=dilation, num_groups=GN_NUM_GROUPS)
self.conv3_1 = _ConvBlock(64, 128, dilation=dilation, num_groups=GN_NUM_GROUPS, dropout=deep_dropout)
self.conv3_2 = _ConvBlock(128, 128, dilation=dilation, num_groups=GN_NUM_GROUPS, dropout=deep_dropout)
self.conv3_3 = _ConvBlock(128, 128, dilation=dilation, num_groups=GN_NUM_GROUPS, dropout=deep_dropout)
self.conv4_1 = _ConvBlock(128, 256, dilation=dilation, num_groups=GN_NUM_GROUPS, dropout=deep_dropout)
self.conv4_2 = _ConvBlock(256, 256, dilation=dilation, num_groups=GN_NUM_GROUPS, dropout=deep_dropout)
self.conv4_3 = _ConvBlock(256, 256, dilation=dilation, num_groups=GN_NUM_GROUPS, dropout=deep_dropout)
self.pool = nn.MaxPool2d(kernel_size=2, stride=2)
@property
def out_channels(self) -> int:
return (32 + 64 + 128) if self.num_scales == 3 else (32 + 64 + 128 + 256)
@property
def pyramid_channels(self) -> list[int]:
return [32, 64, 128] if self.num_scales == 3 else [32, 64, 128, 256]
def forward_pyramid(self, x: torch.Tensor) -> list[torch.Tensor]:
x = self.conv1_1(x)
src1 = self.conv1_2(x)
x = self.pool(src1)
x = self.conv2_1(x)
src2 = self.conv2_2(x)
x = self.pool(src2)
x = self.conv3_1(x)
x = self.conv3_2(x)
src3 = self.conv3_3(x)
if self.num_scales == 3:
return [src1, src2, src3]
x = self.pool(src3)
x = self.conv4_1(x)
x = self.conv4_2(x)
src4 = self.conv4_3(x)
return [src1, src2, src3, src4]
def forward(self, x: torch.Tensor) -> torch.Tensor:
h, w = x.shape[-2:]
pyramid = self.forward_pyramid(x)
upsampled = []
for feat in pyramid:
if feat.shape[-2] != h or feat.shape[-1] != w:
feat = F.interpolate(feat, size=(h, w), mode="bilinear", align_corners=False)
upsampled.append(feat)
return torch.cat(upsampled, dim=1)
class CustomVGGEncoderWrapper(nn.Module):
def __init__(self, *, num_scales: int, dilation: int) -> None:
super().__init__()
self.encoder = HalfVGG16DilatedExtractor(dilation=dilation, num_scales=num_scales)
self.projection = None
@property
def out_channels(self) -> int:
return self.encoder.out_channels
@property
def pyramid_channels(self) -> list[int]:
return self.encoder.pyramid_channels
def forward_pyramid(self, x: torch.Tensor) -> list[torch.Tensor]:
return self.encoder.forward_pyramid(x)
def forward(self, x: torch.Tensor) -> torch.Tensor:
return self.encoder(x)
class SMPEncoderWrapper(nn.Module):
def __init__(
self,
*,
encoder_name: str,
encoder_weights: str | None,
depth: int,
in_channels: int,
proj_dim: int,
) -> None:
super().__init__()
self.encoder = smp.encoders.get_encoder(
encoder_name,
in_channels=in_channels,
depth=depth,
weights=encoder_weights,
)
if REPLACE_BN_WITH_GN:
replace_bn_with_gn(self.encoder, num_groups=GN_NUM_GROUPS)
raw_channels = sum(c for c in self.encoder.out_channels if c > 0)
if proj_dim > 0:
groups = min(GN_NUM_GROUPS, proj_dim)
while groups > 1 and proj_dim % groups != 0:
groups -= 1
self.projection = nn.Sequential(
nn.Conv2d(raw_channels, proj_dim, kernel_size=1, bias=False),
nn.GroupNorm(groups, proj_dim) if REPLACE_BN_WITH_GN else nn.BatchNorm2d(proj_dim),
nn.ReLU(inplace=True),
)
self._out_channels = proj_dim
else:
self.projection = None
self._out_channels = raw_channels
@property
def out_channels(self) -> int:
return self._out_channels
def forward(self, x: torch.Tensor) -> torch.Tensor:
h, w = x.shape[-2:]
features = self.encoder(x)
upsampled = []
for feat in features:
if feat.shape[1] == 0:
continue
if feat.shape[-2] != h or feat.shape[-1] != w:
feat = F.interpolate(feat, size=(h, w), mode="bilinear", align_corners=False)
upsampled.append(feat)
out = torch.cat(upsampled, dim=1)
if self.projection is not None:
out = self.projection(out)
return out
class VGGDecoderBlock(nn.Module):
def __init__(self, *, in_channels: int, skip_channels: int, out_channels: int) -> None:
super().__init__()
self.block = nn.Sequential(
_ConvBlock(in_channels + skip_channels, out_channels, num_groups=GN_NUM_GROUPS),
_ConvBlock(out_channels, out_channels, num_groups=GN_NUM_GROUPS),
)
def forward(self, x: torch.Tensor, skip: torch.Tensor) -> torch.Tensor:
x = F.interpolate(x, size=skip.shape[-2:], mode="bilinear", align_corners=False)
return self.block(torch.cat([x, skip], dim=1))
class VGGSegmentationHead(nn.Module):
def __init__(self, *, pyramid_channels: list[int], dropout_p: float) -> None:
super().__init__()
if len(pyramid_channels) not in {3, 4}:
raise ValueError(f"Expected 3 or 4 VGG pyramid channels, got {pyramid_channels}")
self.dropout = nn.Dropout2d(p=dropout_p)
self.num_scales = len(pyramid_channels)
deepest = pyramid_channels[-1]
self.bridge = _ConvBlock(deepest, deepest, num_groups=GN_NUM_GROUPS)
if self.num_scales == 4:
self.up3 = VGGDecoderBlock(in_channels=deepest, skip_channels=pyramid_channels[2], out_channels=128)
self.up2 = VGGDecoderBlock(in_channels=128, skip_channels=pyramid_channels[1], out_channels=64)
self.up1 = VGGDecoderBlock(in_channels=64, skip_channels=pyramid_channels[0], out_channels=32)
else:
self.up2 = VGGDecoderBlock(in_channels=deepest, skip_channels=pyramid_channels[1], out_channels=64)
self.up1 = VGGDecoderBlock(in_channels=64, skip_channels=pyramid_channels[0], out_channels=32)
self.out_conv = nn.Conv2d(32, 1, kernel_size=1)
def forward(self, pyramid: list[torch.Tensor] | tuple[torch.Tensor, ...]) -> torch.Tensor:
features = list(pyramid)
x = self.bridge(self.dropout(features[-1]))
if self.num_scales == 4:
x = self.up3(x, features[2])
x = self.up2(x, features[1])
x = self.up1(x, features[0])
else:
x = self.up2(x, features[1])
x = self.up1(x, features[0])
return self.out_conv(x)
class PixelDRLMG_SMP(nn.Module):
def __init__(
self,
*,
encoder_name: str,
encoder_weights: str | None,
encoder_depth: int,
proj_dim: int,
dropout_p: float,
) -> None:
super().__init__()
self.extractor = SMPEncoderWrapper(
encoder_name=encoder_name,
encoder_weights=encoder_weights,
depth=encoder_depth,
in_channels=3,
proj_dim=proj_dim,
)
ch = self.extractor.out_channels
self.sam = SelfAttentionModule(channels=ch)
self.policy_head = DilatedPolicyHead(in_channels=ch)
self.value_head = DilatedValueHead(in_channels=ch)
self.head_dropout = nn.Dropout2d(p=dropout_p)
self.omega_conv = nn.Conv2d(1, 1, kernel_size=3, stride=1, padding=1, bias=False)
nn.init.constant_(self.omega_conv.weight, 1.0 / 9.0)
def forward_state(self, x: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
features = self.extractor(x)
return self.sam(features)
def forward_from_state(self, state: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
state = self.head_dropout(state)
return self.policy_head(state), self.value_head(state)
def value_from_state(self, state: torch.Tensor) -> torch.Tensor:
state = self.head_dropout(state)
return self.value_head(state)
def forward(self, x: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
state, attention = self.forward_state(x)
state = self.head_dropout(state)
return self.policy_head(state), self.value_head(state), attention
def forward_policy_only(self, x: torch.Tensor) -> torch.Tensor:
state, _ = self.forward_state(x)
state = self.head_dropout(state)
return self.policy_head(state)
def neighborhood_value(self, value_next: torch.Tensor) -> torch.Tensor:
return _apply_omega_conv(self.omega_conv, value_next)
class PixelDRLMG_VGG(nn.Module):
def __init__(
self,
*,
num_scales: int,
dilation: int,
dropout_p: float,
) -> None:
super().__init__()
self.extractor = CustomVGGEncoderWrapper(num_scales=num_scales, dilation=dilation)
ch = self.extractor.out_channels
self.sam = SelfAttentionModule(channels=ch)
self.policy_head = DilatedPolicyHead(in_channels=ch)
self.value_head = DilatedValueHead(in_channels=ch)
self.head_dropout = nn.Dropout2d(p=dropout_p)
self.omega_conv = nn.Conv2d(1, 1, kernel_size=3, stride=1, padding=1, bias=False)
nn.init.constant_(self.omega_conv.weight, 1.0 / 9.0)
def forward_state(self, x: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
return self.sam(self.extractor(x))
def forward_from_state(self, state: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
state = self.head_dropout(state)
return self.policy_head(state), self.value_head(state)
def value_from_state(self, state: torch.Tensor) -> torch.Tensor:
state = self.head_dropout(state)
return self.value_head(state)
def forward(self, x: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
state, attention = self.forward_state(x)
state = self.head_dropout(state)
return self.policy_head(state), self.value_head(state), attention
def forward_policy_only(self, x: torch.Tensor) -> torch.Tensor:
state, _ = self.forward_state(x)
state = self.head_dropout(state)
return self.policy_head(state)
def neighborhood_value(self, value_next: torch.Tensor) -> torch.Tensor:
return _apply_omega_conv(self.omega_conv, value_next)
class SupervisedSMPModel(nn.Module):
def __init__(
self,
*,
arch: str,
encoder_name: str,
encoder_weights: str | None,
encoder_depth: int = 5,
dropout_p: float,
) -> None:
super().__init__()
self.smp_model = smp.create_model(
arch=arch,
encoder_name=encoder_name,
encoder_weights=encoder_weights,
encoder_depth=encoder_depth,
in_channels=3,
classes=1,
)
self.smp_encoder = self.smp_model.encoder
if REPLACE_BN_WITH_GN:
replace_bn_with_gn(self.smp_encoder, num_groups=GN_NUM_GROUPS)
self.dropout = nn.Dropout2d(p=dropout_p)
def forward(self, x: torch.Tensor) -> torch.Tensor:
encoder_features = self.smp_encoder(x)
decoder_output = run_smp_decoder(self.smp_model.decoder, encoder_features)
decoder_output = self.dropout(decoder_output)
logits = self.smp_model.segmentation_head(decoder_output)
if getattr(self.smp_model, "classification_head", None) is not None:
_ = self.smp_model.classification_head(encoder_features[-1])
return logits
class SupervisedVGGModel(nn.Module):
def __init__(
self,
*,
num_scales: int,
dilation: int,
dropout_p: float,
) -> None:
super().__init__()
self.encoder = CustomVGGEncoderWrapper(num_scales=num_scales, dilation=dilation)
self.segmentation_head = VGGSegmentationHead(
pyramid_channels=self.encoder.pyramid_channels,
dropout_p=dropout_p,
)
def forward(self, x: torch.Tensor) -> torch.Tensor:
return self.segmentation_head(self.encoder.forward_pyramid(x))
class RefinementPolicyHead(nn.Module):
A3C_NUM_ACTIONS = 5 # [-large, -small, keep, +small, +large]
def __init__(self, in_channels: int) -> None:
super().__init__()
self.body = nn.Sequential(
_ConvBlock(in_channels, 256, dilation=1, num_groups=GN_NUM_GROUPS),
_ConvBlock(256, 128, dilation=2, num_groups=GN_NUM_GROUPS),
_ConvBlock(128, 64, dilation=3, num_groups=GN_NUM_GROUPS),
)
self.classifier = nn.Conv2d(64, self.A3C_NUM_ACTIONS, kernel_size=1)
nn.init.zeros_(self.classifier.weight)
if self.classifier.bias is not None:
with torch.no_grad():
# Slight bias toward the "keep" action (middle index) so the policy
# starts by preserving the decoder's output rather than corrupting it.
self.classifier.bias.fill_(-0.1)
self.classifier.bias[self.A3C_NUM_ACTIONS // 2] = 0.3
def forward(self, x: torch.Tensor) -> torch.Tensor:
return self.classifier(self.body(x))
class PixelDRLMG_WithDecoder(nn.Module):
def __init__(
self,
*,
arch: str,
encoder_name: str,
encoder_weights: str | None,
encoder_depth: int,
proj_dim: int,
dropout_p: float,
) -> None:
super().__init__()
self.smp_model = smp.create_model(
arch=arch,
encoder_name=encoder_name,
encoder_weights=encoder_weights,
encoder_depth=encoder_depth,
in_channels=3,
classes=1,
)
self.smp_encoder = self.smp_model.encoder
if REPLACE_BN_WITH_GN:
replace_bn_with_gn(self.smp_encoder, num_groups=GN_NUM_GROUPS)
mc_drop_p = 0.1
n_injected = inject_decoder_dropout(self.smp_model.decoder, p=mc_drop_p)
if n_injected == 0:
self._mc_fallback_noise_std = 0.05
else:
self._mc_fallback_noise_std = 0.0
self._mc_n_passes = 5
raw_channels = sum(c for c in self.smp_encoder.out_channels if c > 0)
if proj_dim > 0:
groups = min(GN_NUM_GROUPS, proj_dim)
while groups > 1 and proj_dim % groups != 0:
groups -= 1
self.projection = nn.Sequential(
nn.Conv2d(raw_channels, proj_dim, kernel_size=1, bias=False),
nn.GroupNorm(groups, proj_dim) if REPLACE_BN_WITH_GN else nn.BatchNorm2d(proj_dim),
nn.ReLU(inplace=True),
)
ch = proj_dim
else:
self.projection = None
ch = raw_channels
self.refinement_adapter = nn.Sequential(
nn.Conv2d(ch + 10, ch, kernel_size=3, stride=1, padding=1, bias=False),
_group_norm(ch),
nn.ReLU(inplace=True),
_ConvBlock(ch, ch, num_groups=GN_NUM_GROUPS),
)
self.multi_scale_refine = _MultiScaleRefineBranch(
encoder_channels=list(self.smp_encoder.out_channels),
out_channels=ch,
per_scale_channels=32,
)
self.sam = SelfAttentionModule(channels=ch)
self.policy_head = RefinementPolicyHead(in_channels=ch)
self.value_head = DilatedValueHead(in_channels=ch)
self.head_dropout = nn.Dropout2d(p=dropout_p)
self.omega_conv = nn.Conv2d(1, 1, kernel_size=3, stride=1, padding=1, bias=False)
nn.init.constant_(self.omega_conv.weight, 1.0 / 9.0)
self.use_refinement = True
def configure_mc_dropout(self, mc_dropout_p: float, mc_n_passes: int) -> None:
self._mc_n_passes = max(int(mc_n_passes), 2)
has_dropout = any(
isinstance(m, (nn.Dropout, nn.Dropout2d))
for m in self.smp_model.decoder.modules()
)
if has_dropout:
for m in self.smp_model.decoder.modules():
if isinstance(m, (nn.Dropout, nn.Dropout2d)):
m.p = mc_dropout_p
self._mc_fallback_noise_std = 0.0
else:
self._mc_fallback_noise_std = mc_dropout_p
def set_refinement_mode(self, enabled: bool) -> None:
self.use_refinement = bool(enabled)
self.refinement_adapter.requires_grad_(self.use_refinement)
self.multi_scale_refine.requires_grad_(self.use_refinement)
def _keep_bootstrapped_segmentation_in_eval(self) -> None:
if not (bool(getattr(self, "strategy2_bootstrap_loaded", False)) and bool(getattr(self, "freeze_bootstrapped_segmentation", False))):
return
for module_name in ("encoder", "decoder", "segmentation_head"):
module = getattr(self.smp_model, module_name, None)
if isinstance(module, nn.Module):
module.eval()
def train(self, mode: bool = True):
super().train(mode)
if mode:
self._keep_bootstrapped_segmentation_in_eval()
return self
def _concat_from_features(
self,
features: list[torch.Tensor] | tuple[torch.Tensor, ...],
*,
output_size: tuple[int, int],
) -> torch.Tensor:
h, w = output_size
upsampled = []
for feat in features:
if feat.shape[1] == 0:
continue
if feat.shape[-2] != h or feat.shape[-1] != w:
feat = F.interpolate(feat, size=(h, w), mode="bilinear", align_corners=False)
upsampled.append(feat)
out = torch.cat(upsampled, dim=1)
if self.projection is not None:
out = self.projection(out)
return out
def _encoder_concat(self, x: torch.Tensor) -> torch.Tensor:
return self._concat_from_features(self.smp_encoder(x), output_size=x.shape[-2:])
def forward_decoder_from_features(
self,
encoder_features: list[torch.Tensor] | tuple[torch.Tensor, ...],
) -> torch.Tensor:
decoder_output = run_smp_decoder(self.smp_model.decoder, encoder_features)
logits = self.smp_model.segmentation_head(decoder_output)
if getattr(self.smp_model, "classification_head", None) is not None:
_ = self.smp_model.classification_head(encoder_features[-1])
return logits
def forward_decoder(self, x: torch.Tensor) -> torch.Tensor:
return self.smp_model(x)
def _mc_dropout_uncertainty(
self,
encoder_features: list[torch.Tensor] | tuple[torch.Tensor, ...],
) -> torch.Tensor:
"""Run K stochastic decoder passes and return per-pixel variance."""
K = self._mc_n_passes
decoder = self.smp_model.decoder
seg_head = self.smp_model.segmentation_head
dropout_modules = [
module for module in decoder.modules()
if isinstance(module, (nn.Dropout, nn.Dropout2d))
]
dropout_states = [module.training for module in dropout_modules]
for module in dropout_modules:
module.train(True)
mc_preds: list[torch.Tensor] = []
try:
with torch.no_grad():
for _ in range(K):
if self._mc_fallback_noise_std > 0:
noisy_feats = [
f + torch.randn_like(f) * self._mc_fallback_noise_std if f.shape[1] > 0 else f
for f in encoder_features
]
else:
noisy_feats = encoder_features
dec_out = run_smp_decoder(decoder, noisy_feats)
logits = seg_head(dec_out)
mc_preds.append(torch.sigmoid(logits))
finally:
for module, was_training in zip(dropout_modules, dropout_states):
module.train(was_training)
stacked = torch.stack(mc_preds, dim=0)
mc_var = stacked.var(dim=0)
mc_max = 0.25
return (mc_var / mc_max).clamp_(0.0, 1.0)
def _mc_cache_key(self, x: torch.Tensor) -> tuple:
return (x.data_ptr(), x.shape[0], x.shape[2], x.shape[3])
def clear_mc_cache(self) -> None:
if hasattr(self, "_mc_cache"):
self._mc_cache.clear()
def prepare_refinement_context(self, x: torch.Tensor) -> dict[str, Any]:
encoder_features = self.smp_encoder(x)
decoder_logits = self.forward_decoder_from_features(encoder_features)
if not hasattr(self, "_mc_cache"):
self._mc_cache: dict[tuple, torch.Tensor] = {}
cache_key = self._mc_cache_key(x)
mc_uncertainty = self._mc_cache.get(cache_key)
if mc_uncertainty is None:
mc_uncertainty = self._mc_dropout_uncertainty(encoder_features)
self._mc_cache[cache_key] = mc_uncertainty.detach()
else:
mc_uncertainty = mc_uncertainty.to(device=x.device, dtype=x.dtype)
return {
"base_features": self._concat_from_features(encoder_features, output_size=x.shape[-2:]),
"encoder_features": list(encoder_features),
"decoder_logits": decoder_logits,
"decoder_prob": torch.sigmoid(decoder_logits),
"mc_uncertainty": mc_uncertainty,
}
def forward_refinement_state(
self,
base_features: torch.Tensor,
current_mask: torch.Tensor,
decoder_prob: torch.Tensor,
gt_error_channels: torch.Tensor | None = None,
encoder_features: list[torch.Tensor] | None = None,
mc_uncertainty: torch.Tensor | None = None,
) -> tuple[torch.Tensor, torch.Tensor]:
residual = decoder_prob - current_mask
uncertainty = (decoder_prob * (1.0 - decoder_prob)).clamp_(0.0, 0.25) * 4.0
boundary = (current_mask - F.avg_pool2d(current_mask, kernel_size=3, stride=1, padding=1)).abs()
decoder_binary = (decoder_prob > 0.5).float()
if gt_error_channels is None:
gt_error_channels = torch.zeros(
base_features.shape[0], 2, base_features.shape[2], base_features.shape[3],
device=base_features.device, dtype=base_features.dtype,
)
if mc_uncertainty is None:
mc_uncertainty = torch.zeros(
base_features.shape[0], 1, base_features.shape[2], base_features.shape[3],
device=base_features.device, dtype=base_features.dtype,
)
conditioning = torch.cat(
[decoder_prob, current_mask, residual, residual.abs(), uncertainty, boundary, decoder_binary,
gt_error_channels, mc_uncertainty],
dim=1,
)
fused = self.refinement_adapter(torch.cat([base_features, conditioning], dim=1))
if encoder_features is not None:
ms_feat = self.multi_scale_refine(encoder_features, output_size=fused.shape[-2:])
fused = fused + ms_feat
return self.sam(fused)
def forward_state(self, x: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
concat_feat = self._encoder_concat(x)
return self.sam(concat_feat)
def forward_from_state(self, state: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
state = self.head_dropout(state)
return self.policy_head(state), self.value_head(state)
def value_from_state(self, state: torch.Tensor) -> torch.Tensor:
state = self.head_dropout(state)
return self.value_head(state)
def forward(self, x: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
if not self.use_refinement:
state, attention = self.forward_state(x)
return self.policy_head(state), self.value_head(state), attention
context = self.prepare_refinement_context(x)
state, attention = self.forward_refinement_state(
context["base_features"],
context["decoder_prob"].detach(),
context["decoder_prob"],
encoder_features=context.get("encoder_features"),
mc_uncertainty=context.get("mc_uncertainty"),
)
policy_logits, value = self.forward_from_state(state)
return policy_logits, value, attention
def forward_policy_only(self, x: torch.Tensor) -> torch.Tensor:
if not self.use_refinement:
state, _ = self.forward_state(x)
state = self.head_dropout(state)
return self.policy_head(state)
context = self.prepare_refinement_context(x)
state, _ = self.forward_refinement_state(
context["base_features"],
context["decoder_prob"].detach(),
context["decoder_prob"],
encoder_features=context.get("encoder_features"),
mc_uncertainty=context.get("mc_uncertainty"),
)
state = self.head_dropout(state)
return self.policy_head(state)
def neighborhood_value(self, value_next: torch.Tensor) -> torch.Tensor:
return _apply_omega_conv(self.omega_conv, value_next)
class PixelDRLMG_VGGWithDecoder(nn.Module):
def __init__(
self,
*,
num_scales: int,
dilation: int,
dropout_p: float,
) -> None:
super().__init__()
self.encoder = CustomVGGEncoderWrapper(num_scales=num_scales, dilation=dilation)
self.segmentation_head = VGGSegmentationHead(
pyramid_channels=self.encoder.pyramid_channels,
dropout_p=dropout_p,
)
ch = self.encoder.out_channels
self.refinement_adapter = nn.Sequential(
nn.Conv2d(ch + 6, ch, kernel_size=3, stride=1, padding=1, bias=False),
_group_norm(ch),
nn.ReLU(inplace=True),
_ConvBlock(ch, ch, num_groups=GN_NUM_GROUPS),
)
self.sam = SelfAttentionModule(channels=ch)
self.policy_head = RefinementPolicyHead(in_channels=ch)
self.value_head = DilatedValueHead(in_channels=ch)
self.head_dropout = nn.Dropout2d(p=dropout_p)
self.omega_conv = nn.Conv2d(1, 1, kernel_size=3, stride=1, padding=1, bias=False)
nn.init.constant_(self.omega_conv.weight, 1.0 / 9.0)
self.use_refinement = True
def set_refinement_mode(self, enabled: bool) -> None:
self.use_refinement = bool(enabled)
self.refinement_adapter.requires_grad_(self.use_refinement)
def _keep_bootstrapped_segmentation_in_eval(self) -> None:
if not (bool(getattr(self, "strategy2_bootstrap_loaded", False)) and bool(getattr(self, "freeze_bootstrapped_segmentation", False))):
return
for module_name in ("encoder", "segmentation_head"):
module = getattr(self, module_name, None)
if isinstance(module, nn.Module):
module.eval()
def train(self, mode: bool = True):
super().train(mode)
if mode:
self._keep_bootstrapped_segmentation_in_eval()
return self
def _concat_pyramid(
self,
pyramid: list[torch.Tensor] | tuple[torch.Tensor, ...],
*,
output_size: tuple[int, int],
) -> torch.Tensor:
h, w = output_size
upsampled = []
for feat in pyramid:
if feat.shape[-2] != h or feat.shape[-1] != w:
feat = F.interpolate(feat, size=(h, w), mode="bilinear", align_corners=False)
upsampled.append(feat)
return torch.cat(upsampled, dim=1)
def forward_decoder(self, x: torch.Tensor) -> torch.Tensor:
return self.segmentation_head(self.encoder.forward_pyramid(x))
def prepare_refinement_context(self, x: torch.Tensor) -> dict[str, torch.Tensor]:
pyramid = self.encoder.forward_pyramid(x)
decoder_logits = self.segmentation_head(pyramid)
return {
"base_features": self._concat_pyramid(pyramid, output_size=x.shape[-2:]),
"decoder_logits": decoder_logits,
"decoder_prob": torch.sigmoid(decoder_logits),
}
def forward_refinement_state(
self,
base_features: torch.Tensor,
current_mask: torch.Tensor,
decoder_prob: torch.Tensor,
gt_error_channels: torch.Tensor | None = None,
encoder_features: list[torch.Tensor] | None = None,
mc_uncertainty: torch.Tensor | None = None,
) -> tuple[torch.Tensor, torch.Tensor]:
decoder_binary = (decoder_prob > 0.5).float()
if gt_error_channels is None:
gt_error_channels = torch.zeros(
base_features.shape[0], 2, base_features.shape[2], base_features.shape[3],
device=base_features.device, dtype=base_features.dtype,
)
conditioning = torch.cat(
[decoder_prob, current_mask, decoder_prob - current_mask, decoder_binary, gt_error_channels],
dim=1,
)
fused = self.refinement_adapter(torch.cat([base_features, conditioning], dim=1))
if encoder_features is not None and hasattr(self, "multi_scale_refine"):
ms_feat = self.multi_scale_refine(encoder_features, output_size=fused.shape[-2:])
fused = fused + ms_feat
return self.sam(fused)
def forward_state(self, x: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
return self.sam(self.encoder(x))
def forward_from_state(self, state: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
state = self.head_dropout(state)
return self.policy_head(state), self.value_head(state)
def value_from_state(self, state: torch.Tensor) -> torch.Tensor:
state = self.head_dropout(state)
return self.value_head(state)
def forward(self, x: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
if not self.use_refinement:
state, attention = self.forward_state(x)
return self.policy_head(state), self.value_head(state), attention
context = self.prepare_refinement_context(x)
state, attention = self.forward_refinement_state(
context["base_features"],
context["decoder_prob"].detach(),
context["decoder_prob"],
encoder_features=context.get("encoder_features"),
mc_uncertainty=context.get("mc_uncertainty"),
)
policy_logits, value = self.forward_from_state(state)
return policy_logits, value, attention
def forward_policy_only(self, x: torch.Tensor) -> torch.Tensor:
if not self.use_refinement:
state, _ = self.forward_state(x)
state = self.head_dropout(state)
return self.policy_head(state)
context = self.prepare_refinement_context(x)
state, _ = self.forward_refinement_state(
context["base_features"],
context["decoder_prob"].detach(),
context["decoder_prob"],
encoder_features=context.get("encoder_features"),
mc_uncertainty=context.get("mc_uncertainty"),
)
state = self.head_dropout(state)
return self.policy_head(state)
def neighborhood_value(self, value_next: torch.Tensor) -> torch.Tensor:
return _apply_omega_conv(self.omega_conv, value_next)
def run_smp_decoder(decoder: nn.Module, encoder_features: list[torch.Tensor] | tuple[torch.Tensor, ...]) -> torch.Tensor:
signature = inspect.signature(decoder.forward)
parameters = list(signature.parameters.values())
if any(param.kind == inspect.Parameter.VAR_POSITIONAL for param in parameters):
return decoder(*encoder_features)
if len(parameters) == 1:
return decoder(encoder_features)
return decoder(*encoder_features)
def checkpoint_run_config_payload(payload: dict[str, Any]) -> dict[str, Any]:
return payload.get("run_config") or payload.get("config") or {}
def _raw_decoder_rl_model(
model: nn.Module,
) -> PixelDRLMG_WithDecoder | PixelDRLMG_VGGWithDecoder | None:
raw = _unwrap_compiled(model)
if isinstance(raw, (PixelDRLMG_WithDecoder, PixelDRLMG_VGGWithDecoder)):
return raw
return None
def _configure_mc_dropout_from_params(model: nn.Module) -> None:
raw = _raw_decoder_rl_model(model)
if raw is None or not isinstance(raw, PixelDRLMG_WithDecoder):
return
mc_p = float(_job_param("mc_dropout_p", 0.3))
mc_k = int(_job_param("mc_n_passes", 5))
raw.configure_mc_dropout(mc_p, mc_k)
def _uses_refinement_runtime(model: nn.Module, *, strategy: int | None = None) -> bool:
raw = _raw_decoder_rl_model(model)
if raw is None:
return False
if strategy is not None and strategy not in (3, 4):
return False
return bool(getattr(raw, "use_refinement", False))
def _policy_action_count_from_state_dict(state_dict: dict[str, Any]) -> int | None:
for key in (
"policy_head.classifier.weight",
"policy_head.classifier.bias",
"policy_head.net.4.weight",
"policy_head.net.4.bias",
):
tensor = state_dict.get(key)
if torch.is_tensor(tensor):
return int(tensor.shape[0])
return None
def _model_policy_action_count(model: nn.Module) -> int | None:
raw = _unwrap_compiled(model)
classifier = getattr(getattr(raw, "policy_head", None), "classifier", None)
if isinstance(classifier, nn.Conv2d):
return int(classifier.out_channels)
return None
def _set_model_policy_action_count(model: nn.Module, action_count: int) -> bool:
raw = _unwrap_compiled(model)
policy_head = getattr(raw, "policy_head", None)
classifier = getattr(policy_head, "classifier", None)
if not isinstance(classifier, nn.Conv2d):
return False
if int(classifier.out_channels) == int(action_count):
return False
new_classifier = nn.Conv2d(
classifier.in_channels,
int(action_count),
kernel_size=classifier.kernel_size,
stride=classifier.stride,
padding=classifier.padding,
dilation=classifier.dilation,
groups=classifier.groups,
bias=classifier.bias is not None,
padding_mode=classifier.padding_mode,
).to(device=classifier.weight.device, dtype=classifier.weight.dtype)
nn.init.xavier_uniform_(new_classifier.weight)
if new_classifier.bias is not None:
nn.init.zeros_(new_classifier.bias)
policy_head.classifier = new_classifier
return True
def _configure_policy_head_compatibility(
model: nn.Module,
state_dict: dict[str, Any],
*,
source: str,
) -> int | None:
action_count = _policy_action_count_from_state_dict(state_dict)
if action_count is None:
return None
if _set_model_policy_action_count(model, action_count):
print(f"[Policy Compatibility] source={source} num_actions={action_count}")
return action_count
def _strategy34_checkpoint_layout_info(
state_dict: dict[str, Any],
run_config: dict[str, Any] | None = None,
) -> dict[str, Any]:
run_config = run_config or {}
strategy = run_config.get("strategy")
has_legacy_policy_head = any(key.startswith("policy_head.net.") for key in state_dict)
has_new_policy_body = any(key.startswith("policy_head.body.") for key in state_dict)
has_new_policy_classifier = any(key.startswith("policy_head.classifier.") for key in state_dict)
has_refinement_adapter = any(key.startswith("refinement_adapter.") for key in state_dict)
is_strategy34_decoder_checkpoint = bool(
strategy in (3, 4)
or has_legacy_policy_head
or has_new_policy_body
or has_new_policy_classifier
or has_refinement_adapter
)
use_refinement = bool(
has_refinement_adapter or ((has_new_policy_body or has_new_policy_classifier) and not has_legacy_policy_head)
)
return {
"strategy": strategy,
"is_strategy34_decoder_checkpoint": is_strategy34_decoder_checkpoint,
"has_legacy_policy_head": has_legacy_policy_head,
"has_new_policy_head": bool(has_new_policy_body or has_new_policy_classifier),
"has_refinement_adapter": has_refinement_adapter,
"requires_policy_remap": has_legacy_policy_head,
"policy_action_count": _policy_action_count_from_state_dict(state_dict),
"use_refinement": use_refinement,
"compatibility_mode": "refinement" if use_refinement else "legacy",
}
def inspect_strategy34_checkpoint_compatibility(path: str | Path) -> dict[str, Any]:
checkpoint_path = Path(path).expanduser().resolve()
payload = torch.load(checkpoint_path, map_location="cpu", weights_only=False)
layout = _strategy34_checkpoint_layout_info(payload.get("model_state_dict", {}), checkpoint_run_config_payload(payload))
layout["path"] = str(checkpoint_path)
return layout
def _configure_strategy34_model_compatibility(
model: nn.Module,
layout: dict[str, Any],
*,
source: str,
) -> None:
raw = _raw_decoder_rl_model(model)
if raw is None or not layout.get("is_strategy34_decoder_checkpoint"):
return
raw.set_refinement_mode(bool(layout["use_refinement"]))
if not bool(layout["use_refinement"]):
raw.refinement_adapter.eval()
if hasattr(raw, "multi_scale_refine"):
raw.multi_scale_refine.eval()
print(
"[Strategy34 Compatibility] "
f"source={source} mode={layout['compatibility_mode']} "
f"legacy_policy_head={layout['has_legacy_policy_head']} "
f"refinement_adapter={layout['has_refinement_adapter']}"
)
def _ensure_strategy34_refinement_adapter_compatible(
model: nn.Module,
state_dict: dict[str, Any],
*,
checkpoint_path: str | Path,
) -> None:
raw_model = _unwrap_compiled(model)
if not isinstance(raw_model, (PixelDRLMG_WithDecoder, PixelDRLMG_VGGWithDecoder)):
return
target_state = raw_model.state_dict()
mismatched: list[str] = []
for key, value in state_dict.items():
if not key.startswith("refinement_adapter."):
continue
target_value = target_state.get(key)
if target_value is None:
continue
if tuple(target_value.shape) != tuple(value.shape):
mismatched.append(
f"{key}: checkpoint={tuple(value.shape)} model={tuple(target_value.shape)}"
)
if mismatched:
raise RuntimeError(
"Incompatible Strategy 3/4 checkpoint detected after the refinement conditioning channel update. "
f"Checkpoint={Path(checkpoint_path).resolve()} mismatches={mismatched[:4]}. "
"Resume/eval from legacy S3 checkpoints is not supported; retrain Strategy 3 from the Strategy 2 bootstrap checkpoint."
)
def _configure_model_from_checkpoint_path(
model: nn.Module,
checkpoint_path: str | Path,
) -> dict[str, Any]:
checkpoint_path = Path(checkpoint_path).expanduser().resolve()
payload = torch.load(checkpoint_path, map_location="cpu", weights_only=False)
state_dict = payload.get("model_state_dict", {})
_configure_policy_head_compatibility(model, state_dict, source=str(checkpoint_path))
layout = _strategy34_checkpoint_layout_info(state_dict, checkpoint_run_config_payload(payload))
_configure_strategy34_model_compatibility(model, layout, source=str(checkpoint_path))
layout["path"] = str(checkpoint_path)
return layout
def _remap_legacy_policy_head_state_dict(state_dict: dict[str, Any]) -> dict[str, Any]:
remapped: dict[str, Any] = {}
for key, value in state_dict.items():
if key.startswith("policy_head.net."):
suffix = key[len("policy_head.net."):]
layer_idx, dot, rest = suffix.partition(".")
if dot:
if layer_idx in {"0", "1", "2", "3"}:
remapped[f"policy_head.body.{layer_idx}.{rest}"] = value
continue
if layer_idx == "4":
remapped[f"policy_head.classifier.{rest}"] = value
continue
remapped[key] = value
return remapped
def _load_strategy2_checkpoint_payload(
path: str | Path,
*,
model_config: RuntimeModelConfig,
) -> dict[str, Any]:
checkpoint_path = Path(path).expanduser().resolve()
ckpt = torch.load(checkpoint_path, map_location=DEVICE, weights_only=False)
saved_config = checkpoint_run_config_payload(ckpt)
if saved_config:
saved_model_config = RuntimeModelConfig.from_payload(saved_config).validate()
if saved_model_config.backbone_family != model_config.backbone_family:
raise ValueError(
f"Strategy 2 checkpoint backbone family mismatch: requested {model_config.backbone_family!r}, "
f"checkpoint has {saved_model_config.backbone_family!r} at {checkpoint_path}."
)
return ckpt
def _preview_state_keys(keys: list[str], *, limit: int = 8) -> str:
if not keys:
return "none"
preview = ", ".join(keys[:limit])
if len(keys) > limit:
preview += ", ..."
return preview
def _strict_load_strategy2_submodule(
target_module: nn.Module,
*,
checkpoint_state_dict: dict[str, Any],
checkpoint_prefix: str,
checkpoint_path: str | Path,
target_name: str,
) -> None:
extracted = {
key[len(checkpoint_prefix):]: value
for key, value in checkpoint_state_dict.items()
if key.startswith(checkpoint_prefix)
}
if not extracted:
raise RuntimeError(
f"Strategy 2 bootstrap failed for {target_name}: no checkpoint keys found with prefix "
f"{checkpoint_prefix!r} in {Path(checkpoint_path).resolve()}."
)
target_state = target_module.state_dict()
missing = sorted(set(target_state.keys()) - set(extracted.keys()))
unexpected = sorted(set(extracted.keys()) - set(target_state.keys()))
if missing or unexpected:
section(f"Strategy 2 Bootstrap Mismatch | {target_name}")
print(f"Checkpoint : {Path(checkpoint_path).resolve()}")
print(f"Checkpoint prefix : {checkpoint_prefix}")
print(f"Target tensors : {len(target_state)}")
print(f"Checkpoint tensors : {len(extracted)}")
print(f"Missing keys ({len(missing)}) : {_preview_state_keys(missing)}")
print(f"Unexpected keys ({len(unexpected)}): {_preview_state_keys(unexpected)}")
raise RuntimeError(
f"Strict Strategy 2 bootstrap failed for {target_name} from {Path(checkpoint_path).resolve()}. "
f"Missing keys={len(missing)}, unexpected keys={len(unexpected)}."
)
try:
load_result = target_module.load_state_dict(extracted, strict=True)
except Exception as exc:
section(f"Strategy 2 Bootstrap Strict Load Failure | {target_name}")
print(f"Checkpoint : {Path(checkpoint_path).resolve()}")
print(f"Checkpoint prefix : {checkpoint_prefix}")
print(f"Target tensors : {len(target_state)}")
print(f"Checkpoint tensors : {len(extracted)}")
raise RuntimeError(
f"Strict Strategy 2 bootstrap load failed for {target_name} from "
f"{Path(checkpoint_path).resolve()}: {exc}"
) from exc
post_missing = list(getattr(load_result, "missing_keys", []))
post_unexpected = list(getattr(load_result, "unexpected_keys", []))
if post_missing or post_unexpected:
raise RuntimeError(
f"Strict Strategy 2 bootstrap reported residual mismatches for {target_name}: "
f"missing={post_missing}, unexpected={post_unexpected}"
)
section(f"Strategy 2 Bootstrap OK | {target_name}")
print(f"Checkpoint : {Path(checkpoint_path).resolve()}")
print(f"Checkpoint prefix : {checkpoint_prefix}")
print(f"Loaded tensors : {len(extracted)}")
print("Strict load : passed")
def _use_channels_last_for_run(model_config: RuntimeModelConfig | None = None) -> bool:
model_config = (model_config or current_model_config()).validate()
if not USE_CHANNELS_LAST:
return False
if DEVICE.type != "cuda":
return False
amp_dtype = resolve_amp_dtype(AMP_DTYPE)
if (
model_config.backbone_family == "smp"
and "efficientnet" in model_config.smp_encoder_name.lower()
and USE_AMP
and amp_dtype in {torch.float16, torch.bfloat16}
):
print("[MemoryFormat] Disabling channels_last for EfficientNet + AMP stability.")
return False
return True
def build_model(
strategy: int,
dropout_p: float,
*,
model_config: RuntimeModelConfig,
strategy2_checkpoint_path: str | Path | None = None,
) -> tuple[nn.Module, str, bool]:
model_config = model_config.validate()
if model_config.backbone_family == "custom_vgg":
if strategy == 1:
model = PixelDRLMG_VGG(
num_scales=model_config.vgg_feature_scales,
dilation=model_config.vgg_feature_dilation,
dropout_p=dropout_p,
)
elif strategy == 2:
model = SupervisedVGGModel(
num_scales=model_config.vgg_feature_scales,
dilation=model_config.vgg_feature_dilation,
dropout_p=dropout_p,
)
elif strategy == 3:
model = PixelDRLMG_VGGWithDecoder(
num_scales=model_config.vgg_feature_scales,
dilation=model_config.vgg_feature_dilation,
dropout_p=dropout_p,
)
model.strategy2_bootstrap_loaded = bool(strategy2_checkpoint_path is not None)
model.freeze_bootstrapped_segmentation = False
if strategy2_checkpoint_path is not None:
freeze_bootstrapped_segmentation = _strategy3_requested_bootstrap_freeze()
ckpt = _load_strategy2_checkpoint_payload(strategy2_checkpoint_path, model_config=model_config)
s2_state = ckpt["model_state_dict"]
_strict_load_strategy2_submodule(
model.encoder,
checkpoint_state_dict=s2_state,
checkpoint_prefix="encoder.",
checkpoint_path=strategy2_checkpoint_path,
target_name="strategy3.encoder",
)
_strict_load_strategy2_submodule(
model.segmentation_head,
checkpoint_state_dict=s2_state,
checkpoint_prefix="segmentation_head.",
checkpoint_path=strategy2_checkpoint_path,
target_name="strategy3.segmentation_head",
)
if freeze_bootstrapped_segmentation:
model.encoder.requires_grad_(False)
model.segmentation_head.requires_grad_(False)
if hasattr(model.encoder, "projection") and model.encoder.projection is not None:
model.encoder.projection.requires_grad_(True)
model.freeze_bootstrapped_segmentation = bool(freeze_bootstrapped_segmentation)
model._keep_bootstrapped_segmentation_in_eval()
elif strategy == 4:
if strategy2_checkpoint_path is None:
raise ValueError("Strategy 4 requires a Strategy 2 checkpoint path.")
model = PixelDRLMG_VGGWithDecoder(
num_scales=model_config.vgg_feature_scales,
dilation=model_config.vgg_feature_dilation,
dropout_p=dropout_p,
)
ckpt = _load_strategy2_checkpoint_payload(strategy2_checkpoint_path, model_config=model_config)
s2_state = ckpt["model_state_dict"]
_strict_load_strategy2_submodule(
model.encoder,
checkpoint_state_dict=s2_state,
checkpoint_prefix="encoder.",
checkpoint_path=strategy2_checkpoint_path,
target_name="strategy4.encoder",
)
_strict_load_strategy2_submodule(
model.segmentation_head,
checkpoint_state_dict=s2_state,
checkpoint_prefix="segmentation_head.",
checkpoint_path=strategy2_checkpoint_path,
target_name="strategy4.segmentation_head",
)
model.encoder.requires_grad_(False)
model.segmentation_head.requires_grad_(False)
if hasattr(model.encoder, "projection") and model.encoder.projection is not None:
model.encoder.projection.requires_grad_(True)
model.strategy2_bootstrap_loaded = True
model.freeze_bootstrapped_segmentation = True
model._keep_bootstrapped_segmentation_in_eval()
elif strategy == 5:
if strategy2_checkpoint_path is None:
raise ValueError("Strategy 5 requires a Strategy 2 checkpoint path.")
model = PixelDRLMG_VGG(
num_scales=model_config.vgg_feature_scales,
dilation=model_config.vgg_feature_dilation,
dropout_p=dropout_p,
)
ckpt = _load_strategy2_checkpoint_payload(strategy2_checkpoint_path, model_config=model_config)
s2_state = ckpt["model_state_dict"]
_strict_load_strategy2_submodule(
model.extractor.encoder,
checkpoint_state_dict=s2_state,
checkpoint_prefix="encoder.encoder.",
checkpoint_path=strategy2_checkpoint_path,
target_name="strategy5.extractor.encoder",
)
model.extractor.encoder.requires_grad_(False)
else:
raise ValueError(f"Unsupported strategy: {strategy}")
else:
if strategy == 1:
model = PixelDRLMG_SMP(
encoder_name=model_config.smp_encoder_name,
encoder_weights=model_config.smp_encoder_weights,
encoder_depth=model_config.smp_encoder_depth,
proj_dim=model_config.smp_encoder_proj_dim,
dropout_p=dropout_p,
)
elif strategy == 2:
model = SupervisedSMPModel(
arch=model_config.smp_decoder_type,
encoder_name=model_config.smp_encoder_name,
encoder_weights=model_config.smp_encoder_weights,
encoder_depth=model_config.smp_encoder_depth,
dropout_p=dropout_p,
)
elif strategy == 3:
model = PixelDRLMG_WithDecoder(
arch=model_config.smp_decoder_type,
encoder_name=model_config.smp_encoder_name,
encoder_weights=model_config.smp_encoder_weights,
encoder_depth=model_config.smp_encoder_depth,
proj_dim=model_config.smp_encoder_proj_dim,
dropout_p=dropout_p,
)
model.strategy2_bootstrap_loaded = bool(strategy2_checkpoint_path is not None)
model.freeze_bootstrapped_segmentation = False
if strategy2_checkpoint_path is not None:
freeze_bootstrapped_segmentation = _strategy3_requested_bootstrap_freeze()
ckpt = _load_strategy2_checkpoint_payload(strategy2_checkpoint_path, model_config=model_config)
s2_state = ckpt["model_state_dict"]
_strict_load_strategy2_submodule(
model.smp_model,
checkpoint_state_dict=s2_state,
checkpoint_prefix="smp_model.",
checkpoint_path=strategy2_checkpoint_path,
target_name="strategy3.smp_model",
)
if freeze_bootstrapped_segmentation:
model.smp_model.encoder.requires_grad_(False)
model.smp_model.decoder.requires_grad_(False)
if hasattr(model.smp_model, "segmentation_head"):
model.smp_model.segmentation_head.requires_grad_(False)
if hasattr(model, "projection") and model.projection is not None:
model.projection.requires_grad_(True)
model.freeze_bootstrapped_segmentation = bool(freeze_bootstrapped_segmentation)
model._keep_bootstrapped_segmentation_in_eval()
elif strategy == 4:
if strategy2_checkpoint_path is None:
raise ValueError("Strategy 4 requires a Strategy 2 checkpoint path.")
model = PixelDRLMG_WithDecoder(
arch=model_config.smp_decoder_type,
encoder_name=model_config.smp_encoder_name,
encoder_weights=None,
encoder_depth=model_config.smp_encoder_depth,
proj_dim=model_config.smp_encoder_proj_dim,
dropout_p=dropout_p,
)
ckpt = _load_strategy2_checkpoint_payload(strategy2_checkpoint_path, model_config=model_config)
s2_state = ckpt["model_state_dict"]
_strict_load_strategy2_submodule(
model.smp_model,
checkpoint_state_dict=s2_state,
checkpoint_prefix="smp_model.",
checkpoint_path=strategy2_checkpoint_path,
target_name="strategy4.smp_model",
)
model.smp_model.encoder.requires_grad_(False)
model.smp_model.decoder.requires_grad_(False)
if hasattr(model.smp_model, "segmentation_head"):
model.smp_model.segmentation_head.requires_grad_(False)
if hasattr(model, "projection") and model.projection is not None:
model.projection.requires_grad_(True)
model.strategy2_bootstrap_loaded = True
model.freeze_bootstrapped_segmentation = True
model._keep_bootstrapped_segmentation_in_eval()
elif strategy == 5:
if strategy2_checkpoint_path is None:
raise ValueError("Strategy 5 requires a Strategy 2 checkpoint path.")
model = PixelDRLMG_SMP(
encoder_name=model_config.smp_encoder_name,
encoder_weights=None,
encoder_depth=model_config.smp_encoder_depth,
proj_dim=model_config.smp_encoder_proj_dim,
dropout_p=dropout_p,
)
ckpt = _load_strategy2_checkpoint_payload(strategy2_checkpoint_path, model_config=model_config)
s2_state = ckpt["model_state_dict"]
_strict_load_strategy2_submodule(
model.extractor.encoder,
checkpoint_state_dict=s2_state,
checkpoint_prefix="smp_model.encoder.",
checkpoint_path=strategy2_checkpoint_path,
target_name="strategy5.extractor.encoder",
)
model.extractor.encoder.requires_grad_(False)
else:
raise ValueError(f"Unsupported strategy: {strategy}")
use_channels_last_now = _use_channels_last_for_run(model_config)
if strategy == 3:
_set_model_policy_action_count(model, int(_job_param("num_actions", 3)))
model = model.to(DEVICE)
if use_channels_last_now:
model = model.to(memory_format=torch.channels_last)
compiled = False
if USE_TORCH_COMPILE and hasattr(torch, "compile"):
try:
model = torch.compile(model)
compiled = True
except Exception as exc:
print(f"[Compile] torch.compile skipped: {exc}")
return model, strategy_name(strategy, model_config), compiled
def _unwrap_compiled(model: nn.Module) -> nn.Module:
return getattr(model, "_orig_mod", model)
def count_parameters(module: nn.Module | None, *, only_trainable: bool = False) -> int:
if module is None:
return 0
if only_trainable:
return sum(p.numel() for p in module.parameters() if p.requires_grad)
return sum(p.numel() for p in module.parameters())
def print_model_parameter_summary(
*,
model: nn.Module,
description: str,
strategy: int,
model_config: RuntimeModelConfig,
dropout_p: float,
amp_dtype: torch.dtype,
compiled: bool,
) -> None:
raw = _unwrap_compiled(model)
total_params = count_parameters(raw)
trainable_params = count_parameters(raw, only_trainable=True)
frozen_params = total_params - trainable_params
bn_count = sum(1 for m in raw.modules() if isinstance(m, (nn.BatchNorm2d, nn.BatchNorm1d)))
gn_count = sum(1 for m in raw.modules() if isinstance(m, nn.GroupNorm))
section(f"Model Parameter Summary | {description}")
print(f"Strategy : {strategy}")
print(f"Model : {description}")
print(f"Dropout p : {dropout_p:.4f}")
print(f"Total params : {total_params:,}")
print(f"Trainable params : {trainable_params:,}")
print(f"Frozen params : {frozen_params:,}")
print(f"BN layers : {bn_count}")
print(f"GN layers : {gn_count}")
print(f"channels_last : {_use_channels_last_for_run(model_config)}")
print(f"AMP dtype : {amp_dtype}")
print(f"torch.compile : {compiled}")
print(f"Backbone family : {model_config.backbone_family}")
if strategy == 3:
freeze_status = _strategy3_bootstrap_freeze_status(model)
print(f"S3 bootstrap loaded : {freeze_status['bootstrap_loaded']}")
print(f"S3 freeze requested : {freeze_status['freeze_requested']}")
print(f"S3 frozen now : {freeze_status['freeze_active']}")
print(f"S3 encoder state : {freeze_status['encoder_state']}")
if freeze_status["decoder_state"] != "n/a":
print(f"S3 decoder state : {freeze_status['decoder_state']}")
if freeze_status["segmentation_head_state"] != "n/a":
print(f"S3 seg head state : {freeze_status['segmentation_head_state']}")
block_counts: dict[str, int] = {}
if strategy == 1:
block_counts["encoder"] = count_parameters(getattr(raw.extractor, "encoder", None))
block_counts["projection"] = count_parameters(getattr(raw.extractor, "projection", None))
block_counts["sam"] = count_parameters(getattr(raw, "sam", None))
block_counts["policy_head"] = count_parameters(getattr(raw, "policy_head", None))
block_counts["value_head"] = count_parameters(getattr(raw, "value_head", None))
block_counts["omega"] = count_parameters(getattr(raw, "omega_conv", None))
elif strategy == 2:
if hasattr(raw, "smp_model"):
smp_model = raw.smp_model
block_counts["encoder"] = count_parameters(getattr(smp_model, "encoder", None))
block_counts["decoder"] = count_parameters(getattr(smp_model, "decoder", None))
block_counts["segmentation_head"] = count_parameters(getattr(smp_model, "segmentation_head", None))
block_counts["dropout"] = count_parameters(getattr(raw, "dropout", None))
else:
block_counts["encoder"] = count_parameters(getattr(raw, "encoder", None))
block_counts["segmentation_head"] = count_parameters(getattr(raw, "segmentation_head", None))
elif strategy in (3, 4):
if hasattr(raw, "smp_model"):
smp_model = raw.smp_model
block_counts["encoder"] = count_parameters(getattr(smp_model, "encoder", None))
block_counts["decoder"] = count_parameters(getattr(smp_model, "decoder", None))
block_counts["segmentation_head"] = count_parameters(getattr(smp_model, "segmentation_head", None))
else:
block_counts["encoder"] = count_parameters(getattr(raw, "encoder", None))
block_counts["segmentation_head"] = count_parameters(getattr(raw, "segmentation_head", None))
block_counts["sam"] = count_parameters(getattr(raw, "sam", None))
block_counts["policy_head"] = count_parameters(getattr(raw, "policy_head", None))
block_counts["value_head"] = count_parameters(getattr(raw, "value_head", None))
block_counts["omega"] = count_parameters(getattr(raw, "omega_conv", None))
elif strategy == 5:
block_counts["encoder"] = count_parameters(getattr(raw.extractor, "encoder", None))
block_counts["projection"] = count_parameters(getattr(raw.extractor, "projection", None))
block_counts["sam"] = count_parameters(getattr(raw, "sam", None))
block_counts["policy_head"] = count_parameters(getattr(raw, "policy_head", None))
block_counts["value_head"] = count_parameters(getattr(raw, "value_head", None))
block_counts["omega"] = count_parameters(getattr(raw, "omega_conv", None))
for name, value in block_counts.items():
print(f"{name:22s}: {value:,}")
"""=============================================================================
METRICS + CHECKPOINTS
=============================================================================
"""
_EPS = 1e-4
def _as_bool(mask: np.ndarray) -> np.ndarray:
return (mask[0] if mask.ndim == 3 else mask).astype(bool)
def _tp_fp_fn(pred: np.ndarray, target: np.ndarray):
p, t = _as_bool(pred), _as_bool(target)
tp = float((p & t).sum())
fp = float((p & ~t).sum())
fn = float((~p & t).sum())
return tp, fp, fn, float(t.sum()), float(p.sum())
def dice_score(pred: np.ndarray, target: np.ndarray) -> float:
tp, _, _, t, p = _tp_fp_fn(pred, target)
return (2 * tp + _EPS) / (t + p + _EPS)
def ppv_score(pred: np.ndarray, target: np.ndarray) -> float:
tp, fp, *_ = _tp_fp_fn(pred, target)
return (tp + _EPS) / (tp + fp + _EPS)
def sensitivity_score(pred: np.ndarray, target: np.ndarray) -> float:
tp, _, fn, *_ = _tp_fp_fn(pred, target)
return (tp + _EPS) / (tp + fn + _EPS)
def iou_score(pred: np.ndarray, target: np.ndarray) -> float:
tp, _, _, t, p = _tp_fp_fn(pred, target)
return (tp + _EPS) / (t + p - tp + _EPS)
def _boundary(mask: np.ndarray) -> np.ndarray:
m = _as_bool(mask)
if not m.any():
return m
return m ^ ndimage.binary_erosion(m, iterations=1, border_value=0)
def boundary_iou_score(pred: np.ndarray, target: np.ndarray) -> float:
pb, tb = _boundary(pred), _boundary(target)
inter = float((pb & tb).sum())
union = float((pb | tb).sum())
return (inter + _EPS) / (union + _EPS)
def _surf_dist(a: np.ndarray, b: np.ndarray) -> np.ndarray:
a, b = _as_bool(a), _as_bool(b)
if not a.any() and not b.any():
return np.array([0.0], dtype=np.float32)
if not a.any() or not b.any():
return np.array([np.inf], dtype=np.float32)
ba, bb = _boundary(a), _boundary(b)
return ndimage.distance_transform_edt(~bb)[ba].astype(np.float32)
def hd95_score(pred: np.ndarray, target: np.ndarray) -> float:
distances = np.concatenate([_surf_dist(pred, target), _surf_dist(target, pred)])
return float("inf") if np.isinf(distances).any() else float(np.percentile(distances, 95))
def compute_all_metrics(pred: np.ndarray, target: np.ndarray) -> dict[str, float]:
return {
"dice": dice_score(pred, target),
"ppv": ppv_score(pred, target),
"sen": sensitivity_score(pred, target),
"iou": iou_score(pred, target),
"biou": boundary_iou_score(pred, target),
"hd95": hd95_score(pred, target),
}
def checkpoint_manifest_path(path: Path) -> Path:
path = Path(path)
return path.with_name(f"{path.name}.meta.json")
def checkpoint_history_path(run_dir: Path, run_type: str) -> Path:
if run_type == "overfit":
return Path(run_dir) / "overfit_history.json"
return Path(run_dir) / "history.json"
def checkpoint_state_presence(payload: dict[str, Any]) -> dict[str, bool]:
tracked = [
"model_state_dict",
"optimizer_state_dict",
"scheduler_state_dict",
"scaler_state_dict",
"log_alpha",
"alpha_optimizer_state_dict",
"best_metric_name",
"best_metric_value",
"patience_counter",
"elapsed_seconds",
"run_config",
"epoch_metrics",
"history",
"resume_source",
]
return {name: name in payload for name in tracked}
def write_checkpoint_manifest(
path: Path,
payload: dict[str, Any],
*,
extra: dict[str, Any] | None = None,
) -> dict[str, Any]:
run_config = checkpoint_run_config_payload(payload)
manifest = {
"checkpoint_path": str(Path(path).resolve()),
"run_type": payload.get("run_type", "unknown"),
"epoch": int(payload.get("epoch", 0)),
"strategy": run_config.get("strategy"),
"dataset_percent": run_config.get("dataset_percent"),
"backbone_family": run_config.get("backbone_family", "smp"),
"saved_keys": sorted(payload.keys()),
"state_presence": checkpoint_state_presence(payload),
}
if "resume_source" in payload:
manifest["resume_source"] = payload["resume_source"]
if extra:
manifest.update(extra)
save_json(checkpoint_manifest_path(path), manifest)
return manifest
def checkpoint_required_keys(
*,
optimizer: torch.optim.Optimizer | None,
scheduler: CosineAnnealingLR | None,
scaler: Any | None,
log_alpha: torch.Tensor | None,
alpha_optimizer: torch.optim.Optimizer | None,
require_run_metadata: bool,
) -> list[str]:
keys = ["epoch", "model_state_dict"]
if require_run_metadata:
keys.extend(
[
"run_type",
"best_metric_name",
"best_metric_value",
"patience_counter",
"elapsed_seconds",
"run_config",
"epoch_metrics",
]
)
if optimizer is not None:
keys.append("optimizer_state_dict")
if scheduler is not None:
keys.append("scheduler_state_dict")
if scaler is not None:
keys.append("scaler_state_dict")
if log_alpha is not None:
keys.append("log_alpha")
if alpha_optimizer is not None:
keys.append("alpha_optimizer_state_dict")
return keys
def validate_checkpoint_payload(
path: Path,
payload: dict[str, Any],
*,
required_keys: list[str],
expected_run_type: str | None = None,
) -> None:
missing = [name for name in required_keys if name not in payload]
if missing:
raise KeyError(f"Checkpoint {path} is missing required keys: {missing}")
if expected_run_type is not None and payload.get("run_type") != expected_run_type:
raise ValueError(
f"Checkpoint {path} run_type mismatch: expected {expected_run_type!r}, "
f"got {payload.get('run_type')!r}."
)
def save_checkpoint(
path: Path,
*,
run_type: str,
model: nn.Module,
optimizer: torch.optim.Optimizer,
scheduler: ReduceLROnPlateau | None,
scaler: Any | None,
epoch: int,
best_metric_value: float,
best_metric_name: str,
run_config: dict[str, Any],
epoch_metrics: dict[str, Any],
patience_counter: int,
elapsed_seconds: float,
history: list[dict[str, Any]] | None = None,
log_alpha: torch.Tensor | None = None,
alpha_optimizer: torch.optim.Optimizer | None = None,
resume_source: dict[str, Any] | None = None,
) -> None:
payload = {
"run_type": run_type,
"epoch": epoch,
"model_state_dict": _unwrap_compiled(model).state_dict(),
"optimizer_state_dict": optimizer.state_dict(),
"best_metric_name": best_metric_name,
"best_metric_value": best_metric_value,
"patience_counter": int(patience_counter),
"elapsed_seconds": float(elapsed_seconds),
"run_config": run_config,
"config": run_config,
"epoch_metrics": epoch_metrics,
}
if history is not None:
payload["history"] = [dict(row) for row in history]
if scheduler is not None:
payload["scheduler_state_dict"] = scheduler.state_dict()
if scaler is not None:
payload["scaler_state_dict"] = scaler.state_dict()
if log_alpha is not None:
payload["log_alpha"] = float(log_alpha.detach().item())
if alpha_optimizer is not None:
payload["alpha_optimizer_state_dict"] = alpha_optimizer.state_dict()
if resume_source is not None:
payload["resume_source"] = resume_source
validate_checkpoint_payload(
path,
payload,
required_keys=checkpoint_required_keys(
optimizer=optimizer,
scheduler=scheduler,
scaler=scaler,
log_alpha=log_alpha,
alpha_optimizer=alpha_optimizer,
require_run_metadata=True,
),
expected_run_type=run_type,
)
torch.save(payload, path)
write_checkpoint_manifest(path, payload)
def load_checkpoint(
path: Path,
*,
model: nn.Module,
optimizer: torch.optim.Optimizer | None = None,
scheduler: ReduceLROnPlateau | None = None,
scaler: Any | None = None,
device: torch.device,
log_alpha: torch.Tensor | None = None,
alpha_optimizer: torch.optim.Optimizer | None = None,
expected_run_type: str | None = None,
require_run_metadata: bool = False,
) -> dict[str, Any]:
ckpt = torch.load(path, map_location=device, weights_only=False)
validate_checkpoint_payload(
path,
ckpt,
required_keys=checkpoint_required_keys(
optimizer=optimizer,
scheduler=scheduler,
scaler=scaler,
log_alpha=log_alpha,
alpha_optimizer=alpha_optimizer,
require_run_metadata=require_run_metadata,
),
expected_run_type=expected_run_type,
)
raw_model = _unwrap_compiled(model)
state_dict = ckpt["model_state_dict"]
load_strict = True
compat_layout: dict[str, Any] | None = None
_configure_policy_head_compatibility(model, state_dict, source=str(path))
if any(key.startswith("policy_head.net.") for key in state_dict):
state_dict = _remap_legacy_policy_head_state_dict(state_dict)
if isinstance(raw_model, (PixelDRLMG_WithDecoder, PixelDRLMG_VGGWithDecoder)):
compat_layout = _strategy34_checkpoint_layout_info(ckpt["model_state_dict"], checkpoint_run_config_payload(ckpt))
if compat_layout["is_strategy34_decoder_checkpoint"]:
_configure_strategy34_model_compatibility(model, compat_layout, source=str(path))
_ensure_strategy34_refinement_adapter_compatible(model, state_dict, checkpoint_path=path)
load_strict = bool(compat_layout["use_refinement"])
incompatible = raw_model.load_state_dict(state_dict, strict=load_strict)
if not load_strict:
missing_keys = [key for key in incompatible.missing_keys if not key.startswith(("refinement_adapter.", "multi_scale_refine."))]
unexpected_keys = list(incompatible.unexpected_keys)
if missing_keys or unexpected_keys:
print(
"[Checkpoint Restore] Non-strict legacy Strategy 3/4 load "
f"missing={missing_keys} unexpected={unexpected_keys}"
)
if optimizer is not None and "optimizer_state_dict" in ckpt:
try:
optimizer.load_state_dict(ckpt["optimizer_state_dict"])
except ValueError:
if compat_layout is None or compat_layout.get("compatibility_mode") != "legacy":
raise
print(
f"[Checkpoint Restore] Skipping optimizer state for legacy Strategy 3/4 checkpoint at {path} "
"because the parameter layout differs from the refinement-capable model."
)
if scheduler is not None and "scheduler_state_dict" in ckpt:
scheduler.load_state_dict(ckpt["scheduler_state_dict"])
if scaler is not None and "scaler_state_dict" in ckpt:
scaler.load_state_dict(ckpt["scaler_state_dict"])
if log_alpha is not None and "log_alpha" in ckpt:
with torch.no_grad():
log_alpha.fill_(float(ckpt["log_alpha"]))
if alpha_optimizer is not None and "alpha_optimizer_state_dict" in ckpt:
alpha_optimizer.load_state_dict(ckpt["alpha_optimizer_state_dict"])
restored = checkpoint_state_presence(ckpt)
restore_info = {
"restored_keys": restored,
"restored_at_epoch": int(ckpt.get("epoch", 0)),
"expected_run_type": expected_run_type,
}
write_checkpoint_manifest(path, ckpt, extra={"last_restore": restore_info})
print(
f"[Checkpoint Restore] path={path} epoch={ckpt.get('epoch')} "
f"run_type={ckpt.get('run_type', 'unknown')} "
f"backbone={checkpoint_run_config_payload(ckpt).get('backbone_family', 'unknown')}"
)
return ckpt
"""=============================================================================
TRAINING + VALIDATION
=============================================================================
"""
def _policy_log_probs_and_entropy(policy_logits: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
logits = policy_logits.float()
log_probs = F.log_softmax(logits, dim=1)
probs = log_probs.exp()
entropy = -(probs * log_probs).sum(dim=1).mean()
return log_probs, entropy
def _log_prob_for_actions(log_probs: torch.Tensor, actions: torch.Tensor) -> torch.Tensor:
return log_probs.gather(1, actions.unsqueeze(1))
def sample_actions(policy_logits: torch.Tensor, stochastic: bool, exploration_eps: float = 0.0) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
logits = policy_logits.float()
log_probs, entropy = _policy_log_probs_and_entropy(policy_logits)
if stochastic:
uniform = torch.rand_like(logits)
gumbel = -torch.log(-torch.log(uniform + 1e-8) + 1e-8)
actions = (logits + gumbel).argmax(dim=1)
if exploration_eps > 0:
random_mask = torch.rand(actions.shape, device=actions.device) < exploration_eps
random_actions = torch.randint(0, logits.shape[1], actions.shape, device=actions.device)
actions = torch.where(random_mask, random_actions, actions)
else:
actions = logits.argmax(dim=1)
log_prob = _log_prob_for_actions(log_probs, actions)
return actions, log_prob, entropy
def apply_actions(
seg: torch.Tensor,
actions: torch.Tensor,
*,
soft_update_step: float | None = None,
num_actions: int | None = None,
decoder_prior: torch.Tensor | None = None,
) -> torch.Tensor:
num_actions = int(num_actions if num_actions is not None else _job_param("num_actions", NUM_ACTIONS))
if num_actions == 5:
action_map = actions.long()
if soft_update_step is not None:
deltas = _refinement_deltas(device=seg.device, dtype=seg.dtype)
delta = deltas[action_map].unsqueeze(1)
if decoder_prior is not None:
prior_f = decoder_prior.to(device=seg.device, dtype=seg.dtype)
uncertainty = (4.0 * prior_f * (1.0 - prior_f)).clamp(0.0, 1.0)
disagreement = ((prior_f - seg).abs() * 2.0).clamp(0.0, 1.0)
scale = (
1.0
+ float(_job_param("delta_scale_uncertainty_weight", 0.0)) * uncertainty
+ float(_job_param("delta_scale_disagreement_weight", 0.0)) * disagreement
)
scale = scale.clamp(
min=float(_job_param("delta_scale_min", 1.0)),
max=float(_job_param("delta_scale_max", 1.0)),
)
delta = delta * scale
return (seg + delta).clamp_(0.0, 1.0)
return torch.where(
action_map.unsqueeze(1) <= 1,
torch.zeros_like(seg),
torch.where(action_map.unsqueeze(1) >= 3, torch.ones_like(seg), seg),
)
action_map = actions.unsqueeze(1)
if num_actions >= 3:
if soft_update_step is not None and not _strategy3_direct_binary_actions(num_actions):
delta = torch.where(
action_map == 0,
torch.full_like(seg, -soft_update_step),
torch.where(action_map == 2, torch.full_like(seg, soft_update_step), torch.zeros_like(seg)),
)
return (seg + delta).clamp_(0.0, 1.0)
return torch.where(
action_map == 0,
torch.zeros_like(seg),
torch.where(action_map == 2, torch.ones_like(seg), seg),
)
return seg * (action_map == 1).to(dtype=seg.dtype)
def _soft_dice_tensor(pred: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
inter = (pred * target).sum(dim=(1, 2, 3))
denom = pred.sum(dim=(1, 2, 3)) + target.sum(dim=(1, 2, 3))
return (2.0 * inter + 1e-6) / (denom + 1e-6)
def _soft_iou_tensor(pred: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
inter = (pred * target).sum(dim=(1, 2, 3))
union = pred.sum(dim=(1, 2, 3)) + target.sum(dim=(1, 2, 3)) - inter
return (inter + 1e-6) / (union + 1e-6)
def _soft_recall_tensor(pred: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
true_positive = (pred * target).sum(dim=(1, 2, 3))
positives = target.sum(dim=(1, 2, 3))
return (true_positive + 1e-6) / (positives + 1e-6)
def _soft_boundary(mask: torch.Tensor) -> torch.Tensor:
return (mask - F.avg_pool2d(mask, kernel_size=3, stride=1, padding=1)).abs()
def _strategy3_expected_next_mask(
policy_logits: torch.Tensor,
base_seg: torch.Tensor,
) -> tuple[torch.Tensor, torch.Tensor]:
logits_f = policy_logits.float()
base_seg_f = base_seg.float()
probs = F.softmax(logits_f, dim=1)
deltas = _refinement_deltas(device=logits_f.device, dtype=logits_f.dtype)
expected_delta = (probs * deltas.view(1, -1, 1, 1)).sum(dim=1, keepdim=True)
predicted_next = (base_seg_f + expected_delta).clamp(1e-4, 1.0 - 1e-4)
return predicted_next, deltas
def _strategy3_action_targets(
seg_mask: torch.Tensor,
gt_mask: torch.Tensor,
deltas: torch.Tensor,
) -> torch.Tensor:
target_delta = gt_mask.float() - seg_mask.float()
return (target_delta - deltas.view(1, -1, 1, 1)).abs().argmin(dim=1)
def compute_refinement_reward(
seg: torch.Tensor,
seg_next: torch.Tensor,
gt_mask: torch.Tensor,
*,
decoder_prior: torch.Tensor | None = None,
training_progress: float = 0.0,
) -> torch.Tensor:
del decoder_prior, training_progress
seg_f = seg.float()
seg_next_f = seg_next.float()
gt_f = gt_mask.float()
threshold = float(_job_param("threshold", CONTROLLED_MASK_THRESHOLD))
binary_reward_weight = float(_job_param("binary_reward_weight", 0.7))
boundary_focus = float(_job_param("reward_boundary_focus", 0.8))
# --- Component 1: Continuous MSE improvement ---
# With alpha=1.0 (new default), "keep" gives exactly 0 reward.
# Higher alpha penalizes new errors more than it rewards corrections.
alpha = float(_job_param("asymmetric_reward_alpha", 1.0))
continuous = (seg_f - gt_f).pow(2) - alpha * (seg_next_f - gt_f).pow(2)
# --- Component 2: Binary correctness change ---
# +1 when a pixel flips to the correct class, -1 for flipping wrong, 0 otherwise.
gt_binary = (gt_f > 0.5).float()
pred_before = (seg_f > threshold).float()
pred_next = (seg_next_f > threshold).float()
correct_before = (pred_before - gt_binary).abs() < 0.5 # was correct
correct_next = (pred_next - gt_binary).abs() < 0.5 # now correct
binary = correct_next.float() - correct_before.float()
reward = (1.0 - binary_reward_weight) * continuous + binary_reward_weight * binary
# --- Component 3: Focus reward on pixels near the decision boundary ---
# Pixels far from threshold contribute almost nothing to IoU changes,
# so suppress their reward to prevent the "amplify confidence" degeneracy.
dist_to_boundary = (seg_f - threshold).abs()
proximity = (1.0 - 2.0 * dist_to_boundary).clamp(0.0, 1.0)
if boundary_focus > 0:
reward = reward * ((1.0 - boundary_focus) + boundary_focus * proximity)
# --- Component 4: Small inaction cost for uncertain pixels ---
# Prevents keep-collapse: when the decoder is uncertain (pixel near threshold),
# "keep" gets a small negative reward proportional to how wrong the current
# prediction is. For confident correct pixels, cost is ~0.
# Only activates when the mask didn't change (keep or ineffective action).
inaction_cost = float(_job_param("reward_inaction_cost", 0.05))
if inaction_cost > 0:
no_change = (seg_f - seg_next_f).abs() < 1e-6
current_error = (pred_before - gt_binary).abs() # 1 if wrong, 0 if correct
penalty = inaction_cost * current_error * proximity
reward = reward - no_change.float() * penalty
boundary_weight = float(_job_param("boundary_reward_weight", 0.0))
if boundary_weight > 0:
gt_boundary = _soft_boundary(gt_f)
boundary_boost = 1.0 + boundary_weight * gt_boundary
reward = reward * boundary_boost
return reward.clamp(-2.0, 2.0)
def compute_strategy1_aux_segmentation_loss(
policy_logits: torch.Tensor,
gt_mask: torch.Tensor,
*,
ce_weight: float,
dice_weight: float,
seg_mask: torch.Tensor | None = None,
) -> tuple[torch.Tensor, float, float]:
logits_f = policy_logits.float()
gt_mask_f = gt_mask.float()
num_actions = int(logits_f.shape[1])
if num_actions == 3 and _strategy3_direct_binary_actions(num_actions):
base_seg = seg_mask.float() if seg_mask is not None else torch.full_like(gt_mask_f, 0.5)
base_seg_scalar = base_seg.squeeze(1)
gt_bin = gt_mask[:, 0].long()
fg_margin = float(_job_param("aux_fg_margin", 0.75))
bg_margin = float(_job_param("aux_bg_margin", 0.25))
fg_margin = min(max(fg_margin, 0.0), 1.0)
bg_margin = min(max(bg_margin, 0.0), 1.0)
keep_target = torch.ones_like(gt_bin)
force_bg_target = torch.zeros_like(gt_bin)
force_fg_target = torch.full_like(gt_bin, 2)
needs_fg = (gt_bin == 1) & (base_seg_scalar < fg_margin)
needs_bg = (gt_bin == 0) & (base_seg_scalar > bg_margin)
hard_mask = needs_fg | needs_bg
aux_target = torch.where(
needs_fg,
force_fg_target,
torch.where(needs_bg, force_bg_target, keep_target),
)
probs = F.softmax(logits_f, dim=1)
predicted_next = (probs[:, 1:2] * base_seg.float() + probs[:, 2:3]).clamp(1e-4, 1.0 - 1e-4)
aux_loss = torch.zeros((), device=policy_logits.device, dtype=torch.float32)
ce_loss_value = 0.0
dice_loss_value = 0.0
if ce_weight > 0:
if bool(_job_param("aux_hard_mask_only", True)):
logits_hw = logits_f.permute(0, 2, 3, 1)
if bool(hard_mask.any().item()):
ce_loss = F.cross_entropy(logits_hw[hard_mask], aux_target[hard_mask])
else:
ce_loss = torch.zeros((), device=policy_logits.device, dtype=torch.float32)
else:
ce_loss = F.cross_entropy(logits_f, aux_target)
aux_loss = aux_loss + ce_weight * ce_loss
ce_loss_value = float(ce_loss.detach().item())
if dice_weight > 0:
if bool(_job_param("aux_hard_mask_only", True)):
hard_mask_f = hard_mask.unsqueeze(1).to(dtype=gt_mask_f.dtype)
if bool(hard_mask.any().item()):
masked_pred = predicted_next * hard_mask_f
masked_gt = gt_mask_f * hard_mask_f
inter = (masked_pred * masked_gt).sum()
dice_loss = 1.0 - (2.0 * inter + 1e-6) / (masked_pred.sum() + masked_gt.sum() + 1e-6)
else:
dice_loss = torch.zeros((), device=policy_logits.device, dtype=torch.float32)
else:
inter = (predicted_next * gt_mask_f).sum()
dice_loss = 1.0 - (2.0 * inter + 1e-6) / (predicted_next.sum() + gt_mask_f.sum() + 1e-6)
aux_loss = aux_loss + dice_weight * dice_loss
dice_loss_value = float(dice_loss.detach().item())
return aux_loss, ce_loss_value, dice_loss_value
if int(policy_logits.shape[1]) == 5:
base_seg = seg_mask.float() if seg_mask is not None else torch.full_like(gt_mask_f, 0.5)
predicted_next, deltas = _strategy3_expected_next_mask(policy_logits, base_seg)
action_targets = _strategy3_action_targets(base_seg, gt_mask_f, deltas)
aux_loss = torch.zeros((), device=policy_logits.device, dtype=torch.float32)
ce_loss_value = 0.0
dice_loss_value = 0.0
threshold = float(_job_param("threshold", CONTROLLED_MASK_THRESHOLD))
delta_large = float(_job_param("refine_delta_large", 0.25))
hard_margin = delta_large * 1.5
with torch.no_grad():
dist_to_thresh = (base_seg - threshold).abs()
hard_mask = (dist_to_thresh < hard_margin).squeeze(1)
if ce_weight > 0:
action_ce_mix = float(_job_param("aux_action_ce_mix", 0.75))
action_ce_mix = min(max(action_ce_mix, 0.0), 1.0)
if hard_mask.any():
logits_hw = policy_logits.float().permute(0, 2, 3, 1)
targets_hw = action_targets
action_ce = F.cross_entropy(logits_hw[hard_mask], targets_hw[hard_mask])
else:
action_ce = F.cross_entropy(policy_logits.float(), action_targets)
predicted_next_logits = torch.logit(predicted_next)
if hard_mask.any():
gt_hard = gt_mask_f.squeeze(1)[hard_mask]
pred_hard = predicted_next_logits.squeeze(1)[hard_mask]
bce = F.binary_cross_entropy_with_logits(pred_hard, gt_hard)
else:
bce = F.binary_cross_entropy_with_logits(predicted_next_logits, gt_mask_f)
ce_term = action_ce_mix * action_ce + (1.0 - action_ce_mix) * bce
aux_loss = aux_loss + ce_weight * ce_term
ce_loss_value = float(ce_term.detach().item())
if dice_weight > 0:
inter = (predicted_next * gt_mask_f).sum()
dice_loss = 1.0 - (2.0 * inter + 1e-6) / (predicted_next.sum() + gt_mask_f.sum() + 1e-6)
aux_loss = aux_loss + dice_weight * dice_loss
dice_loss_value = float(dice_loss.detach().item())
return aux_loss, ce_loss_value, dice_loss_value
aux_loss = torch.zeros((), device=policy_logits.device, dtype=torch.float32)
ce_loss_value = 0.0
dice_loss_value = 0.0
if ce_weight > 0:
if num_actions >= 3:
if seg_mask is None:
seg_mask = torch.ones_like(gt_mask)
seg_bin = threshold_binary_long(seg_mask).squeeze(1)
gt_bin = gt_mask[:, 0].long()
aux_target = torch.where(
gt_bin == 0,
torch.zeros_like(gt_bin),
torch.where(seg_bin == 1, torch.ones_like(gt_bin), torch.full_like(gt_bin, 2)),
)
else:
aux_target = gt_mask[:, 0].long() * (num_actions - 1)
ce_loss = F.cross_entropy(logits_f, aux_target)
aux_loss = aux_loss + ce_weight * ce_loss
ce_loss_value = float(ce_loss.detach().item())
if dice_weight > 0:
probs_fg = F.softmax(logits_f, dim=1)[:, num_actions - 1 : num_actions]
inter = (probs_fg * gt_mask_f).sum()
dice_loss = 1.0 - (2.0 * inter + 1e-6) / (probs_fg.sum() + gt_mask_f.sum() + 1e-6)
aux_loss = aux_loss + dice_weight * dice_loss
dice_loss_value = float(dice_loss.detach().item())
return aux_loss, ce_loss_value, dice_loss_value
def make_optimizer(
model: nn.Module,
strategy: int,
head_lr: float,
encoder_lr: float,
weight_decay: float,
rl_lr: float | None = None,
):
raw = _unwrap_compiled(model)
encoder_params = []
decoder_params = []
rl_params = []
for name, param in raw.named_parameters():
if not param.requires_grad:
continue
if (
name.startswith("extractor.encoder.")
or name.startswith("encoder.")
or name.startswith("smp_model.encoder.")
or name.startswith("smp_encoder.")
):
encoder_params.append(param)
elif "decoder" in name or "segmentation_head" in name:
decoder_params.append(param)
else:
rl_params.append(param)
decoder_lr = float(_job_param("decoder_lr", head_lr))
rl_group_lr = float(_job_param("rl_lr", rl_lr if rl_lr is not None else head_lr))
param_groups: list[dict[str, Any]] = []
if encoder_params:
param_groups.append({"params": encoder_params, "lr": encoder_lr})
if decoder_params:
param_groups.append({"params": decoder_params, "lr": decoder_lr})
if rl_params:
param_groups.append({"params": rl_params, "lr": rl_group_lr})
try:
optimizer = AdamW(param_groups, weight_decay=weight_decay, fused=DEVICE.type == "cuda")
except Exception:
optimizer = AdamW(param_groups, weight_decay=weight_decay)
return optimizer
def infer_segmentation_mask(
model: nn.Module,
image: torch.Tensor,
tmax: int,
*,
strategy: int,
use_amp: bool,
amp_dtype: torch.dtype,
use_channels_last: bool,
) -> torch.Tensor:
model.eval()
if use_channels_last and image.ndim == 4 and image.device.type == "cuda":
image = image.contiguous(memory_format=torch.channels_last)
if strategy == 2:
with autocast_ctx(enabled=use_amp, device=image.device, amp_dtype=amp_dtype):
logits = model(image)
return threshold_binary_mask(torch.sigmoid(logits)).float()
refinement_runtime = _uses_refinement_runtime(model, strategy=strategy)
if strategy in (3, 4) and refinement_runtime:
with autocast_ctx(enabled=use_amp, device=image.device, amp_dtype=amp_dtype):
refinement_context = model.prepare_refinement_context(image)
seg = refinement_context["decoder_prob"].float()
for _step_idx in range(tmax):
with autocast_ctx(enabled=use_amp, device=image.device, amp_dtype=amp_dtype):
state_t, _ = model.forward_refinement_state(
refinement_context["base_features"],
seg,
refinement_context["decoder_prob"],
encoder_features=refinement_context.get("encoder_features"),
mc_uncertainty=refinement_context.get("mc_uncertainty"),
)
policy_logits, _value_t = model.forward_from_state(state_t)
actions, _, _ = sample_actions(policy_logits, stochastic=False)
seg = _strategy3_apply_rollout_step(seg, actions)
return threshold_binary_mask(seg.float()).float()
if strategy in (3, 4):
with autocast_ctx(enabled=use_amp, device=image.device, amp_dtype=amp_dtype):
seg = threshold_binary_mask(torch.sigmoid(model.forward_decoder(image))).float()
else:
seg = torch.ones(image.shape[0], 1, image.shape[2], image.shape[3], device=image.device, dtype=image.dtype)
for _ in range(tmax):
with autocast_ctx(enabled=use_amp, device=image.device, amp_dtype=amp_dtype):
x_t = image * seg
policy_logits = model.forward_policy_only(x_t)
actions, _, _ = sample_actions(policy_logits, stochastic=False)
seg = apply_actions(seg, actions, num_actions=policy_logits.shape[1]).to(dtype=seg.dtype)
return seg.float()
def train_step(
model: nn.Module,
batch: dict[str, Any],
optimizer: torch.optim.Optimizer,
*,
gamma: float,
tmax: int,
critic_loss_weight: float,
log_alpha: torch.Tensor,
alpha_optimizer: torch.optim.Optimizer,
target_entropy: float,
ce_weight: float,
dice_weight: float,
grad_clip_norm: float,
scaler: Any | None,
use_amp: bool,
amp_dtype: torch.dtype,
stepwise_backward: bool,
use_channels_last: bool,
initial_mask: torch.Tensor | None = None,
decoder_loss_extra: torch.Tensor | None = None,
) -> dict[str, Any]:
model.train()
_strategy3_keep_frozen_modules_in_eval(model)
image = batch["image"]
gt_mask = batch["mask"]
if use_channels_last and image.ndim == 4 and image.device.type == "cuda":
image = image.contiguous(memory_format=torch.channels_last)
if use_amp and image.device.type == "cuda":
image = image.to(dtype=amp_dtype)
gt_mask = gt_mask.to(dtype=amp_dtype)
else:
image = image.float()
gt_mask = gt_mask.float()
if initial_mask is not None:
seg = initial_mask.to(device=image.device, dtype=image.dtype)
else:
seg = torch.ones(image.shape[0], 1, image.shape[2], image.shape[3], device=image.device, dtype=image.dtype)
alpha = log_alpha.exp()
total_actor = 0.0
total_critic = 0.0
total_loss = 0.0
total_reward = 0.0
total_entropy = 0.0
total_ce_loss = 0.0
total_dice_loss = 0.0
accum_tensor = None
alpha_loss_accum = torch.tensor(0.0, device=image.device, dtype=torch.float32)
aux_fused = False
optimizer.zero_grad(set_to_none=True)
for _ in range(tmax):
with autocast_ctx(enabled=use_amp, device=image.device, amp_dtype=amp_dtype):
x_t = image * seg
state_t, _ = model.forward_state(x_t)
policy_logits, value_t = model.forward_from_state(state_t)
actions, log_prob, entropy = sample_actions(policy_logits, stochastic=True)
log_prob = log_prob.clamp(min=-10.0)
seg_next = apply_actions(seg, actions, num_actions=policy_logits.shape[1])
reward = (seg - gt_mask).pow(2) - (seg_next - gt_mask).pow(2)
with torch.no_grad():
with autocast_ctx(enabled=use_amp, device=image.device, amp_dtype=amp_dtype):
x_next = image * seg_next
state_next, _ = model.forward_state(x_next)
value_next = model.value_from_state(state_next).detach()
neighborhood_next = model.neighborhood_value(value_next)
target = reward + gamma * neighborhood_next
advantage = target - value_t
critic_loss = F.smooth_l1_loss(value_t, target)
actor_loss = -(log_prob * advantage.detach()).mean()
actor_loss = actor_loss - alpha.detach() * entropy
step_loss = (actor_loss + critic_loss_weight * critic_loss) / float(tmax)
alpha_loss_accum = alpha_loss_accum + (log_alpha * (entropy.detach() - target_entropy)) / float(tmax)
if not aux_fused and initial_mask is None and (ce_weight > 0 or dice_weight > 0):
aux_loss, ce_loss_value, dice_loss_value = compute_strategy1_aux_segmentation_loss(
policy_logits,
gt_mask,
ce_weight=ce_weight,
dice_weight=dice_weight,
seg_mask=seg,
)
if ce_weight > 0:
total_ce_loss = ce_loss_value
if dice_weight > 0:
total_dice_loss = dice_loss_value
step_loss = step_loss + aux_loss
aux_fused = True
total_actor += float(actor_loss.detach().item())
total_critic += float(critic_loss.detach().item())
total_loss += float(step_loss.detach().item())
total_reward += float(reward.detach().mean().item())
total_entropy += float(entropy.detach().item())
if stepwise_backward:
if scaler is not None:
scaler.scale(step_loss).backward()
else:
step_loss.backward()
else:
accum_tensor = step_loss if accum_tensor is None else accum_tensor + step_loss
seg = seg_next.detach()
if not stepwise_backward and accum_tensor is not None:
if scaler is not None:
scaler.scale(accum_tensor).backward()
else:
accum_tensor.backward()
if not aux_fused and (ce_weight > 0 or dice_weight > 0):
with autocast_ctx(enabled=use_amp, device=image.device, amp_dtype=amp_dtype):
policy_aux, _, _ = model(image)
logits_f = policy_aux.float()
aux_loss = torch.zeros(1, device=image.device, dtype=torch.float32)
if ce_weight > 0:
num_actions = int(logits_f.shape[1])
if num_actions >= 3:
init_seg = initial_mask if initial_mask is not None else torch.ones_like(gt_mask)
seg_bin = threshold_binary_long(init_seg).squeeze(1)
gt_bin = gt_mask[:, 0].long()
aux_target = torch.where(
gt_bin == 0,
torch.zeros_like(gt_bin),
torch.where(seg_bin == 1, torch.ones_like(gt_bin), torch.full_like(gt_bin, 2)),
)
else:
aux_target = gt_mask[:, 0].long() * (num_actions - 1)
ce_loss = F.cross_entropy(logits_f, aux_target)
aux_loss = aux_loss + ce_weight * ce_loss
total_ce_loss = float(ce_loss.detach().item())
if dice_weight > 0:
probs_fg = F.softmax(logits_f, dim=1)[:, num_actions - 1 : num_actions]
gt_f = gt_mask.float()
inter = (probs_fg * gt_f).sum()
dice_loss = 1.0 - (2.0 * inter + 1e-6) / (probs_fg.sum() + gt_f.sum() + 1e-6)
aux_loss = aux_loss + dice_weight * dice_loss
total_dice_loss = float(dice_loss.detach().item())
if decoder_loss_extra is not None:
aux_loss = aux_loss + decoder_loss_extra
if scaler is not None:
scaler.scale(aux_loss).backward()
else:
aux_loss.backward()
total_loss += float(aux_loss.detach().item())
elif decoder_loss_extra is not None:
if scaler is not None:
scaler.scale(decoder_loss_extra).backward()
else:
decoder_loss_extra.backward()
total_loss += float(decoder_loss_extra.detach().item())
if scaler is not None:
scaler.unscale_(optimizer)
total_grad_norm = float(torch.nn.utils.clip_grad_norm_(model.parameters(), grad_clip_norm).item()) if grad_clip_norm > 0 else 0.0
if scaler is not None:
scaler.step(optimizer)
scaler.update()
else:
optimizer.step()
alpha_optimizer.zero_grad(set_to_none=True)
alpha_loss_accum.backward()
alpha_optimizer.step()
with torch.no_grad():
log_alpha.clamp_(min=_alpha_log_floor(), max=5.0)
return {
"loss": total_loss,
"actor_loss": total_actor / tmax,
"critic_loss": total_critic / tmax,
"mean_reward": total_reward / tmax,
"entropy": total_entropy / tmax,
"ce_loss": total_ce_loss,
"dice_loss": total_dice_loss,
"grad_norm": total_grad_norm,
"grad_clip_used": grad_clip_norm,
"final_mask": seg.detach(),
}
def train_step_strategy3(
model: nn.Module,
batch: dict[str, Any],
optimizer: torch.optim.Optimizer,
*,
gamma: float,
tmax: int,
critic_loss_weight: float,
log_alpha: torch.Tensor,
alpha_optimizer: torch.optim.Optimizer,
target_entropy: float,
ce_weight: float,
dice_weight: float,
grad_clip_norm: float,
scaler: Any | None,
use_amp: bool,
amp_dtype: torch.dtype,
stepwise_backward: bool,
use_channels_last: bool,
current_epoch: int,
max_epochs: int,
) -> dict[str, Any]:
if not _uses_refinement_runtime(model, strategy=3):
image = batch["image"]
gt_mask = batch["mask"]
if use_channels_last and image.ndim == 4 and image.device.type == "cuda":
image = image.contiguous(memory_format=torch.channels_last)
if use_amp and image.device.type == "cuda":
image = image.to(dtype=amp_dtype)
gt_mask = gt_mask.to(dtype=amp_dtype)
else:
image = image.float()
gt_mask = gt_mask.float()
with autocast_ctx(enabled=use_amp, device=image.device, amp_dtype=amp_dtype):
decoder_logits = model.forward_decoder(image)
init_mask = threshold_binary_mask(torch.sigmoid(decoder_logits)).float()
decoder_loss = torch.zeros(1, device=image.device, dtype=torch.float32)
with autocast_ctx(enabled=use_amp, device=image.device, amp_dtype=amp_dtype):
dl_f = decoder_logits.float()
gt_f = gt_mask.float()
if ce_weight > 0:
decoder_loss = decoder_loss + ce_weight * F.binary_cross_entropy_with_logits(dl_f, gt_f)
if dice_weight > 0:
dm_prob = torch.sigmoid(dl_f)
inter = (dm_prob * gt_f).sum()
decoder_loss = decoder_loss + dice_weight * (
1.0 - (2.0 * inter + 1e-6) / (dm_prob.sum() + gt_f.sum() + 1e-6)
)
return train_step(
model,
batch,
optimizer,
gamma=gamma,
tmax=tmax,
critic_loss_weight=critic_loss_weight,
log_alpha=log_alpha,
alpha_optimizer=alpha_optimizer,
target_entropy=target_entropy,
ce_weight=ce_weight,
dice_weight=dice_weight,
grad_clip_norm=grad_clip_norm,
scaler=scaler,
use_amp=use_amp,
amp_dtype=amp_dtype,
stepwise_backward=stepwise_backward,
use_channels_last=use_channels_last,
initial_mask=init_mask,
decoder_loss_extra=decoder_loss,
)
model.train()
_strategy3_keep_frozen_modules_in_eval(model)
image = batch["image"]
gt_mask = batch["mask"]
if use_channels_last and image.ndim == 4 and image.device.type == "cuda":
image = image.contiguous(memory_format=torch.channels_last)
if use_amp and image.device.type == "cuda":
image = image.to(dtype=amp_dtype)
gt_mask = gt_mask.to(dtype=amp_dtype)
else:
image = image.float()
gt_mask = gt_mask.float()
del stepwise_backward
with autocast_ctx(enabled=use_amp, device=image.device, amp_dtype=amp_dtype):
refinement_context = model.prepare_refinement_context(image)
decoder_logits = refinement_context["decoder_logits"]
decoder_prob = refinement_context["decoder_prob"]
base_features = refinement_context["base_features"]
encoder_features = refinement_context.get("encoder_features")
seg = decoder_prob.detach().to(device=image.device, dtype=image.dtype)
loss_weights = _strategy3_loss_weights(model, ce_weight=ce_weight, dice_weight=dice_weight)
policy_action_count = _model_policy_action_count(model) or int(_job_param("num_actions", NUM_ACTIONS))
decoder_loss = torch.zeros((), device=image.device, dtype=torch.float32)
decoder_ce_loss_value = 0.0
decoder_dice_loss_value = 0.0
with autocast_ctx(enabled=use_amp, device=image.device, amp_dtype=amp_dtype):
dl_f = decoder_logits.float()
gt_f = gt_mask.float()
if loss_weights["decoder_ce"] > 0:
decoder_ce = F.binary_cross_entropy_with_logits(dl_f, gt_f)
decoder_loss = decoder_loss + loss_weights["decoder_ce"] * decoder_ce
decoder_ce_loss_value = float(decoder_ce.detach().item())
if loss_weights["decoder_dice"] > 0:
dm_prob = decoder_prob.float()
inter = (dm_prob * gt_f).sum()
decoder_dice = 1.0 - (2.0 * inter + 1e-6) / (dm_prob.sum() + gt_f.sum() + 1e-6)
decoder_loss = decoder_loss + loss_weights["decoder_dice"] * decoder_dice
decoder_dice_loss_value = float(decoder_dice.detach().item())
optimizer.zero_grad(set_to_none=True)
alpha = log_alpha.exp()
gae_lambda = float(_job_param("gae_lambda", 0.95))
a3c_entropy_coeff = float(_job_param("a3c_entropy_coeff", 0.01))
a3c_grad_clip = float(_job_param("strategy3_rl_grad_clip_norm", 1.0))
detached_base_features = base_features.detach()
detached_decoder_prob = decoder_prob.detach()
detached_encoder_features = [f.detach() for f in encoder_features] if encoder_features is not None else None
_mc_unc = refinement_context.get("mc_uncertainty")
detached_mc_uncertainty = _mc_unc.detach() if _mc_unc is not None else None
step_action_hists: list[dict[str, float]] = []
step_mask_deltas: list[float] = []
step_reward_means: list[float] = []
step_reward_pos_pcts: list[float] = []
rollout_states: list[torch.Tensor] = []
rollout_actions: list[torch.Tensor] = []
rollout_log_probs: list[torch.Tensor] = []
rollout_values: list[torch.Tensor] = []
rollout_rewards: list[torch.Tensor] = []
rollout_entropies: list[torch.Tensor] = []
for step_idx in range(tmax):
seg_before = seg.detach()
with torch.no_grad():
with autocast_ctx(enabled=use_amp, device=image.device, amp_dtype=amp_dtype):
state_t, _ = model.forward_refinement_state(
detached_base_features, seg_before, detached_decoder_prob,
encoder_features=detached_encoder_features,
mc_uncertainty=detached_mc_uncertainty,
)
policy_logits, value_t = model.forward_from_state(state_t)
actions, log_prob, entropy = sample_actions(policy_logits, stochastic=True)
seg_next = _strategy3_apply_rollout_step(seg_before, actions)
reward = compute_refinement_reward(seg_before, seg_next, gt_mask.float())
state_next, _ = model.forward_refinement_state(
detached_base_features, seg_next, detached_decoder_prob,
encoder_features=detached_encoder_features,
mc_uncertainty=detached_mc_uncertainty,
)
value_next = model.value_from_state(state_next).detach()
step_action_hists.append(_action_histogram(actions, policy_action_count))
step_mask_deltas.append(float((seg_next - seg_before).abs().mean().item()))
step_reward_means.append(float(reward.mean().item()))
step_reward_pos_pcts.append(float((reward > 0).float().mean().item() * 100.0))
rollout_states.append(seg_before)
rollout_actions.append(actions.detach())
rollout_log_probs.append(log_prob.detach())
rollout_values.append(value_t.detach())
rollout_rewards.append(reward.detach())
rollout_entropies.append(entropy.detach())
seg = seg_next.detach()
effective_steps = tmax
last_value = value_next
returns: list[torch.Tensor] = [torch.zeros_like(rollout_values[0])] * effective_steps
advantages_list: list[torch.Tensor] = [torch.zeros_like(rollout_values[0])] * effective_steps
gae = torch.zeros_like(rollout_values[0])
for t in reversed(range(effective_steps)):
next_val = last_value if t == effective_steps - 1 else rollout_values[t + 1]
td_error = rollout_rewards[t] + gamma * next_val - rollout_values[t]
gae = td_error + gamma * gae_lambda * gae
advantages_list[t] = gae
returns[t] = gae + rollout_values[t]
total_actor = 0.0
total_critic = 0.0
total_reward = 0.0
total_entropy = 0.0
total_ce_loss = decoder_ce_loss_value
total_dice_loss = decoder_dice_loss_value
actor_loss_tensor = torch.zeros((), device=image.device, dtype=torch.float32)
critic_loss_tensor = torch.zeros((), device=image.device, dtype=torch.float32)
gt_boundary = _soft_boundary(gt_mask.float())
boundary_entropy_weight = 1.0 + 2.0 * gt_boundary
aux_ce_w = loss_weights["aux_ce"]
aux_dice_w = loss_weights["aux_dice"]
aux_loss_tensor = torch.zeros((), device=image.device, dtype=torch.float32)
total_aux_ce_loss = 0.0
total_aux_dice_loss = 0.0
for t in range(effective_steps):
total_reward += float(rollout_rewards[t].mean().item())
total_entropy += float(rollout_entropies[t].item())
with autocast_ctx(enabled=use_amp, device=image.device, amp_dtype=amp_dtype):
state_t, _ = model.forward_refinement_state(
detached_base_features, rollout_states[t], detached_decoder_prob,
encoder_features=detached_encoder_features,
mc_uncertainty=detached_mc_uncertainty,
)
policy_logits, value_t = model.forward_from_state(state_t)
log_probs_all, entropy_t = _policy_log_probs_and_entropy(policy_logits)
log_prob_t = _log_prob_for_actions(log_probs_all, rollout_actions[t]).clamp(min=-10.0)
detached_adv = advantages_list[t].detach()
norm_adv = (detached_adv - detached_adv.mean()) / (detached_adv.std(unbiased=False) + 1e-6)
step_actor = -(log_prob_t * norm_adv).mean()
weighted_entropy = (entropy_t.unsqueeze(0) * boundary_entropy_weight).mean() if entropy_t.dim() == 0 else (entropy_t * boundary_entropy_weight).mean()
entropy_bonus = a3c_entropy_coeff + float(alpha.detach().item())
step_actor = step_actor - entropy_bonus * weighted_entropy
returns_t = returns[t].detach()
step_critic = F.mse_loss(value_t, returns_t)
if aux_ce_w > 0 or aux_dice_w > 0:
step_aux, step_aux_ce, step_aux_dice = compute_strategy1_aux_segmentation_loss(
policy_logits, gt_mask,
ce_weight=aux_ce_w, dice_weight=aux_dice_w,
seg_mask=rollout_states[t],
)
aux_loss_tensor = aux_loss_tensor + step_aux / float(effective_steps)
total_aux_ce_loss += step_aux_ce / float(effective_steps)
total_aux_dice_loss += step_aux_dice / float(effective_steps)
actor_loss_tensor = actor_loss_tensor + step_actor / float(effective_steps)
critic_loss_tensor = critic_loss_tensor + step_critic / float(effective_steps)
total_actor += float(step_actor.detach().item())
total_critic += float(step_critic.detach().item())
rl_loss = actor_loss_tensor + critic_loss_weight * critic_loss_tensor
total_ce_loss += total_aux_ce_loss
total_dice_loss += total_aux_dice_loss
total_loss_tensor = decoder_loss + rl_loss + aux_loss_tensor
if scaler is not None:
scaler.scale(total_loss_tensor).backward()
scaler.unscale_(optimizer)
else:
total_loss_tensor.backward()
effective_grad_clip = a3c_grad_clip if a3c_grad_clip > 0 else grad_clip_norm
total_grad_norm = (
float(torch.nn.utils.clip_grad_norm_(model.parameters(), effective_grad_clip).item())
if effective_grad_clip > 0
else 0.0
)
if scaler is not None:
scaler.step(optimizer)
scaler.update()
else:
optimizer.step()
alpha_loss = torch.zeros((), device=image.device, dtype=torch.float32)
for t in range(effective_steps):
alpha_loss = alpha_loss + (log_alpha * (rollout_entropies[t].detach() - target_entropy))
alpha_optimizer.zero_grad(set_to_none=True)
(alpha_loss / float(effective_steps)).backward()
alpha_optimizer.step()
with torch.no_grad():
log_alpha.clamp_(min=_alpha_log_floor(), max=5.0)
adv_means = [float(a.mean().item()) for a in advantages_list]
adv_stds = [float(a.std().item()) for a in advantages_list]
value_pred_errors = [
float((rollout_rewards[t] + gamma * (last_value if t == effective_steps - 1 else rollout_values[t + 1]) - rollout_values[t]).abs().mean().item())
for t in range(effective_steps)
]
avg_action_dist: dict[str, float] = {}
if step_action_hists:
all_keys = set()
for h in step_action_hists:
all_keys.update(h.keys())
for k in sorted(all_keys):
avg_action_dist[k] = float(np.mean([h.get(k, 0.0) for h in step_action_hists]))
return {
"loss": float(total_loss_tensor.detach().item()),
"actor_loss": total_actor / float(effective_steps),
"critic_loss": total_critic / float(effective_steps),
"mean_reward": total_reward / float(effective_steps),
"entropy": total_entropy / float(effective_steps),
"ce_loss": total_ce_loss,
"dice_loss": total_dice_loss,
"grad_norm": total_grad_norm,
"grad_clip_used": effective_grad_clip,
"final_mask": threshold_binary_mask(seg.detach().float()).float(),
"effective_steps": effective_steps,
"action_distribution": avg_action_dist,
"mask_delta_mean": float(np.mean(step_mask_deltas)) if step_mask_deltas else 0.0,
"reward_per_step": step_reward_means,
"reward_pos_pct_per_step": step_reward_pos_pcts,
"advantage_mean": float(np.mean(adv_means)),
"advantage_std": float(np.mean(adv_stds)),
"value_pred_error_mean": float(np.mean(value_pred_errors)),
"alpha": float(alpha.detach().item()),
}
def train_step_supervised(
model: nn.Module,
batch: dict[str, Any],
optimizer: torch.optim.Optimizer,
*,
scaler: Any | None,
use_amp: bool,
amp_dtype: torch.dtype,
use_channels_last: bool,
grad_clip_norm: float,
ce_weight: float = 0.5,
dice_weight: float = 0.5,
) -> dict[str, Any]:
model.train()
_strategy3_keep_frozen_modules_in_eval(model)
image = batch["image"]
gt_mask = batch["mask"]
if use_channels_last and image.ndim == 4 and image.device.type == "cuda":
image = image.contiguous(memory_format=torch.channels_last)
if use_amp and image.device.type == "cuda":
image = image.to(dtype=amp_dtype)
gt_mask = gt_mask.to(dtype=amp_dtype)
else:
image = image.float()
gt_mask = gt_mask.float()
optimizer.zero_grad(set_to_none=True)
with autocast_ctx(enabled=use_amp, device=image.device, amp_dtype=amp_dtype):
logits = model(image)
logits_f = logits.float()
gt_f = gt_mask.float()
loss = torch.zeros(1, device=image.device, dtype=torch.float32)
ce_loss_val = 0.0
dice_loss_val = 0.0
if ce_weight > 0:
bce = F.binary_cross_entropy_with_logits(logits_f, gt_f, reduction="mean")
loss = loss + ce_weight * bce
ce_loss_val = float(bce.detach().item())
if dice_weight > 0:
pred_f = torch.sigmoid(logits_f)
inter = (pred_f * gt_f).sum()
dice_l = 1.0 - (2.0 * inter + 1e-6) / (pred_f.sum() + gt_f.sum() + 1e-6)
loss = loss + dice_weight * dice_l
dice_loss_val = float(dice_l.detach().item())
if scaler is not None:
scaler.scale(loss).backward()
scaler.unscale_(optimizer)
else:
loss.backward()
total_grad_norm = float(torch.nn.utils.clip_grad_norm_(model.parameters(), grad_clip_norm).item()) if grad_clip_norm > 0 else 0.0
if scaler is not None:
scaler.step(optimizer)
scaler.update()
else:
optimizer.step()
final_mask = threshold_binary_mask(torch.sigmoid(logits_f)).float().detach()
return {
"loss": float(loss.detach().item()),
"actor_loss": 0.0,
"critic_loss": 0.0,
"mean_reward": 0.0,
"entropy": 0.0,
"ce_loss": ce_loss_val,
"dice_loss": dice_loss_val,
"grad_norm": total_grad_norm,
"grad_clip_used": grad_clip_norm,
"final_mask": final_mask,
}
@torch.inference_mode()
def validate(
model: nn.Module,
loader: DataLoader,
*,
strategy: int,
tmax: int,
use_amp: bool,
amp_dtype: torch.dtype,
use_channels_last: bool,
gamma: float,
critic_loss_weight: float,
ce_weight: float,
dice_weight: float,
training_progress: float = 1.0,
) -> dict[str, float]:
model.eval()
losses: list[float] = []
dice_scores: list[float] = []
iou_scores: list[float] = []
entropies: list[float] = []
rewards: list[float] = []
actor_losses: list[float] = []
critic_losses: list[float] = []
ce_losses: list[float] = []
dice_losses: list[float] = []
decoder_dice_scores: list[float] = []
decoder_iou_scores: list[float] = []
val_binary_flips_total: list[float] = []
val_binary_flips_correct: list[float] = []
val_binary_flips_wrong: list[float] = []
prefetcher = CUDAPrefetcher(loader, DEVICE)
try:
for batch in tqdm(prefetcher, total=len(loader), desc="Validating", leave=False):
image = batch["image"]
gt_mask = batch["mask"].float()
if use_channels_last and image.ndim == 4 and image.device.type == "cuda":
image = image.contiguous(memory_format=torch.channels_last)
if use_amp and DEVICE.type == "cuda":
image = image.to(dtype=amp_dtype)
gt_mask = gt_mask.to(dtype=amp_dtype)
if strategy == 2:
with autocast_ctx(enabled=use_amp, device=image.device, amp_dtype=amp_dtype):
logits = model(image)
pred_prob = torch.sigmoid(logits).float()
pred = threshold_binary_mask(pred_prob).float()
bce = F.binary_cross_entropy_with_logits(logits.float(), gt_mask.float(), reduction="mean") if ce_weight > 0 else torch.tensor(0.0, device=image.device)
inter_prob = (pred_prob * gt_mask.float()).sum()
dice_loss = 1.0 - (2.0 * inter_prob + 1e-6) / (pred_prob.sum() + gt_mask.sum() + 1e-6) if dice_weight > 0 else torch.tensor(0.0, device=image.device)
losses.append(float((ce_weight * bce + dice_weight * dice_loss).item()))
ce_losses.append(float(bce.item()) if ce_weight > 0 else 0.0)
dice_losses.append(float(dice_loss.item()) if dice_weight > 0 else 0.0)
else:
refinement_runtime = _uses_refinement_runtime(model, strategy=strategy)
if strategy in (3, 4) and refinement_runtime:
with autocast_ctx(enabled=use_amp, device=image.device, amp_dtype=amp_dtype):
refinement_context = model.prepare_refinement_context(image)
decoder_logits = refinement_context["decoder_logits"]
decoder_prob = refinement_context["decoder_prob"].float()
seg = decoder_prob.float()
loss_weights = _strategy3_loss_weights(model, ce_weight=ce_weight, dice_weight=dice_weight)
decoder_loss = 0.0
batch_ce = 0.0
batch_dice = 0.0
with autocast_ctx(enabled=use_amp, device=image.device, amp_dtype=amp_dtype):
dl_f = decoder_logits.float()
gt_f = gt_mask.float()
if loss_weights["decoder_ce"] > 0:
batch_ce = float(F.binary_cross_entropy_with_logits(dl_f, gt_f).item())
decoder_loss += loss_weights["decoder_ce"] * batch_ce
if loss_weights["decoder_dice"] > 0:
dm_prob = decoder_prob.float()
inter = (dm_prob * gt_f).sum()
batch_dice = float(
(
1.0 - (2.0 * inter + 1e-6) / (dm_prob.sum() + gt_f.sum() + 1e-6)
).item()
)
decoder_loss += loss_weights["decoder_dice"] * batch_dice
decoder_pred = threshold_binary_mask(decoder_prob.float()).float()
decoder_inter = (decoder_pred * gt_mask.float()).sum(dim=(1, 2, 3))
decoder_pred_sum = decoder_pred.sum(dim=(1, 2, 3))
decoder_gt_sum = gt_mask.float().sum(dim=(1, 2, 3))
decoder_dice = (2.0 * decoder_inter + _EPS) / (decoder_pred_sum + decoder_gt_sum + _EPS)
decoder_iou = (decoder_inter + _EPS) / (decoder_pred_sum + decoder_gt_sum - decoder_inter + _EPS)
decoder_dice_scores.extend(decoder_dice.cpu().tolist())
decoder_iou_scores.extend(decoder_iou.cpu().tolist())
else:
fg_count = gt_mask.sum().clamp(min=1.0)
bg_count = (gt_mask == 0).sum().clamp(min=1.0)
pos_weight = bg_count / fg_count
_weight_map = torch.where(gt_mask == 1, pos_weight, torch.ones_like(gt_mask))
if strategy in (3, 4):
with autocast_ctx(enabled=use_amp, device=image.device, amp_dtype=amp_dtype):
decoder_logits = model.forward_decoder(image)
seg = threshold_binary_mask(torch.sigmoid(decoder_logits)).float()
decoder_loss = 0.0
batch_ce = 0.0
batch_dice = 0.0
with autocast_ctx(enabled=use_amp, device=image.device, amp_dtype=amp_dtype):
dl_f = decoder_logits.float()
gt_f = gt_mask.float()
if ce_weight > 0:
batch_ce = float(F.binary_cross_entropy_with_logits(dl_f, gt_f).item())
decoder_loss += ce_weight * batch_ce
if dice_weight > 0:
dm_prob = torch.sigmoid(dl_f)
inter = (dm_prob * gt_f).sum()
batch_dice = float(
(
1.0 - (2.0 * inter + 1e-6) / (dm_prob.sum() + gt_f.sum() + 1e-6)
).item()
)
decoder_loss += dice_weight * batch_dice
else:
seg = torch.ones(
image.shape[0],
1,
image.shape[2],
image.shape[3],
device=image.device,
dtype=image.dtype,
)
decoder_loss = 0.0
batch_ce = 0.0
batch_dice = 0.0
batch_actor = 0.0
batch_critic = 0.0
batch_reward = 0.0
batch_entropy = 0.0
batch_loss = decoder_loss
decoder_ce_base = batch_ce
decoder_dice_base = batch_dice
aux_ce_total = 0.0
aux_dice_total = 0.0
effective_steps = tmax
if strategy in (3, 4) and refinement_runtime:
detached_base_features = refinement_context["base_features"].detach()
detached_decoder_prob = decoder_prob.detach()
_enc_feats = refinement_context.get("encoder_features")
detached_enc_feats = [f.detach() for f in _enc_feats] if _enc_feats is not None else None
_mc_unc_val = refinement_context.get("mc_uncertainty")
detached_mc_unc = _mc_unc_val.detach() if _mc_unc_val is not None else None
effective_steps = tmax
for _step_idx in range(tmax):
with autocast_ctx(enabled=use_amp, device=image.device, amp_dtype=amp_dtype):
state_t, _ = model.forward_refinement_state(
detached_base_features, seg, detached_decoder_prob,
encoder_features=detached_enc_feats,
mc_uncertainty=detached_mc_unc,
)
policy_logits, value_t = model.forward_from_state(state_t)
actions, log_prob, entropy = sample_actions(policy_logits, stochastic=False)
seg_next = _strategy3_apply_rollout_step(seg, actions)
reward = compute_refinement_reward(seg, seg_next, gt_mask.float())
state_next, _ = model.forward_refinement_state(
detached_base_features, seg_next, detached_decoder_prob,
encoder_features=detached_enc_feats,
mc_uncertainty=detached_mc_unc,
)
value_next = model.value_from_state(state_next).detach()
target = reward + gamma * value_next
advantage = target - value_t
actor_loss = -(log_prob * advantage.detach()).mean()
critic_loss = F.mse_loss(value_t, target)
batch_actor += float(actor_loss.item())
batch_critic += float(critic_loss.item())
batch_reward += float(reward.mean().item())
batch_entropy += float(entropy.item())
batch_loss += float((actor_loss + critic_loss_weight * critic_loss).item())
seg = seg_next
batch_ce = decoder_ce_base
batch_dice = decoder_dice_base
batch_loss = decoder_loss + batch_loss / float(max(effective_steps, 1))
pred = threshold_binary_mask(seg.float()).float()
# Track binary mask flips between decoder and RL-refined prediction
flipped = (decoder_pred != pred)
gt_binary = (gt_mask.float() > 0.5)
correct_flips = flipped & ((pred > 0.5) == gt_binary)
wrong_flips = flipped & ((pred > 0.5) != gt_binary)
total_px = max(pred.numel(), 1)
val_binary_flips_total.append(float(flipped.float().sum().item() / total_px * 100.0))
val_binary_flips_correct.append(float(correct_flips.float().sum().item() / total_px * 100.0))
val_binary_flips_wrong.append(float(wrong_flips.float().sum().item() / total_px * 100.0))
else:
for _ in range(tmax):
with autocast_ctx(enabled=use_amp, device=image.device, amp_dtype=amp_dtype):
x_t = image * seg
state_t, _ = model.forward_state(x_t)
policy_logits, value_t = model.forward_from_state(state_t)
actions, log_prob, entropy = sample_actions(policy_logits, stochastic=False)
log_prob = log_prob.clamp(min=-10.0)
seg_next = apply_actions(seg, actions, num_actions=policy_logits.shape[1])
reward = ((seg - gt_mask).pow(2) - (seg_next - gt_mask).pow(2))
x_next = image * seg_next
state_next, _ = model.forward_state(x_next)
value_next = model.value_from_state(state_next).detach()
target = reward + gamma * model.neighborhood_value(value_next)
advantage = target - value_t
actor_loss = -(log_prob * advantage.detach()).mean()
critic_loss = F.smooth_l1_loss(value_t, target)
batch_actor += float(actor_loss.item())
batch_critic += float(critic_loss.item())
batch_reward += float(reward.mean().item())
batch_entropy += float(entropy.item())
batch_loss += float(((actor_loss + critic_loss_weight * critic_loss) / float(tmax)).item())
seg = seg_next
with autocast_ctx(enabled=use_amp, device=image.device, amp_dtype=amp_dtype):
policy_aux, _, _ = model(image)
aux_loss, aux_ce, aux_dice = compute_strategy1_aux_segmentation_loss(
policy_aux,
gt_mask,
ce_weight=ce_weight,
dice_weight=dice_weight,
seg_mask=seg,
)
batch_loss += float(aux_loss.item())
batch_ce = aux_ce
batch_dice = aux_dice
pred = infer_segmentation_mask(
model,
image,
tmax,
strategy=strategy,
use_amp=use_amp,
amp_dtype=amp_dtype,
use_channels_last=use_channels_last,
).float()
ce_losses.append(batch_ce)
dice_losses.append(batch_dice)
actor_losses.append(batch_actor / float(max(effective_steps, 1)))
critic_losses.append(batch_critic / float(max(effective_steps, 1)))
rewards.append(batch_reward / float(max(effective_steps, 1)))
entropies.append(batch_entropy / float(max(effective_steps, 1)))
losses.append(batch_loss)
inter = (pred * gt_mask.float()).sum(dim=(1, 2, 3))
pred_sum = pred.sum(dim=(1, 2, 3))
gt_sum = gt_mask.float().sum(dim=(1, 2, 3))
dice = (2.0 * inter + _EPS) / (pred_sum + gt_sum + _EPS)
iou = (inter + _EPS) / (pred_sum + gt_sum - inter + _EPS)
dice_scores.extend(dice.cpu().tolist())
iou_scores.extend(iou.cpu().tolist())
finally:
prefetcher.close()
del prefetcher
val_decoder_dice = float(np.mean(decoder_dice_scores)) if decoder_dice_scores else None
val_decoder_iou = float(np.mean(decoder_iou_scores)) if decoder_iou_scores else None
val_dice = float(np.mean(dice_scores)) if dice_scores else 0.0
val_iou = float(np.mean(iou_scores)) if iou_scores else 0.0
return {
"val_loss": float(np.mean(losses)) if losses else 0.0,
"val_dice": val_dice,
"val_iou": val_iou,
"val_decoder_dice": val_decoder_dice,
"val_decoder_iou": val_decoder_iou,
"val_dice_gain": None if val_decoder_dice is None else val_dice - val_decoder_dice,
"val_iou_gain": None if val_decoder_iou is None else val_iou - val_decoder_iou,
"val_actor_loss": float(np.mean(actor_losses)) if actor_losses else 0.0,
"val_critic_loss": float(np.mean(critic_losses)) if critic_losses else 0.0,
"val_ce_loss": float(np.mean(ce_losses)) if ce_losses else 0.0,
"val_dice_loss": float(np.mean(dice_losses)) if dice_losses else 0.0,
"val_reward": float(np.mean(rewards)) if rewards else 0.0,
"val_entropy": float(np.mean(entropies)) if entropies else 0.0,
"val_binary_flips_total_pct": float(np.mean(val_binary_flips_total)) if val_binary_flips_total else None,
"val_binary_flips_correct_pct": float(np.mean(val_binary_flips_correct)) if val_binary_flips_correct else None,
"val_binary_flips_wrong_pct": float(np.mean(val_binary_flips_wrong)) if val_binary_flips_wrong else None,
}
def _save_training_plots(history: list[dict[str, Any]], plots_dir: Path) -> None:
if len(history) < 1:
return
ensure_dir(plots_dir)
epochs = [row["epoch"] for row in history]
plot_specs = [
("loss.png", "Loss", [("train_loss", "Train"), ("val_loss", "Val")]),
("dice.png", "Dice", [("train_dice", "Train"), ("val_dice", "Val")]),
("iou.png", "IoU", [("train_iou", "Train"), ("val_iou", "Val")]),
("reward.png", "Reward", [("train_mean_reward", "Train"), ("val_reward", "Val")]),
("entropy.png", "Entropy", [("train_entropy", "Train"), ("val_entropy", "Val")]),
("ce_loss.png", "CE Loss", [("train_ce_loss", "Train")]),
("dice_loss.png", "Dice Loss", [("train_dice_loss", "Train")]),
("alpha.png", "Alpha", [("alpha", "Alpha")]),
("lr.png", "Learning Rate", [("lr", "Head LR"), ("encoder_lr", "Encoder LR")]),
]
for file_name, title, curves in plot_specs:
fig, ax = plt.subplots(figsize=(8, 4))
has_data = False
for key, label in curves:
values = [(row["epoch"], row[key]) for row in history if key in row]
if not values:
continue
xs, ys = zip(*values)
ax.plot(xs, ys, label=label, linewidth=1.2)
has_data = True
if has_data:
ax.set_title(title)
ax.set_xlabel("Epoch")
ax.set_ylabel(title)
ax.grid(True, alpha=0.3)
ax.legend()
fig.tight_layout()
fig.savefig(plots_dir / file_name, dpi=110)
plt.close(fig)
RESUME_IDENTITY_KEYS = (
"strategy",
"dataset_percent",
"dataset_name",
"dataset_split_policy",
"split_type",
"train_subset_key",
"train_subset_variant",
"best_checkpoint_metric_name",
"backbone_family",
"smp_encoder_name",
"smp_encoder_weights",
"smp_encoder_depth",
"smp_encoder_proj_dim",
"smp_decoder_type",
"vgg_feature_scales",
"vgg_feature_dilation",
"head_lr",
"encoder_lr",
"weight_decay",
"dropout_p",
"tmax",
"entropy_lr",
)
def _resume_value_matches(current: Any, saved: Any) -> bool:
if isinstance(current, (int, float)) and isinstance(saved, (int, float)) and not isinstance(current, bool):
return math.isclose(float(current), float(saved), rel_tol=1e-9, abs_tol=1e-12)
return current == saved
def validate_resume_checkpoint_identity(
current_run_config: dict[str, Any],
saved_run_config: dict[str, Any],
*,
checkpoint_path: Path,
) -> None:
mismatches: list[str] = []
for key in RESUME_IDENTITY_KEYS:
if key not in current_run_config or key not in saved_run_config:
mismatches.append(f"{key}: current={current_run_config.get(key)!r}, checkpoint={saved_run_config.get(key)!r}")
continue
if not _resume_value_matches(current_run_config[key], saved_run_config[key]):
mismatches.append(f"{key}: current={current_run_config[key]!r}, checkpoint={saved_run_config[key]!r}")
current_s2 = current_run_config.get("strategy2_checkpoint_path")
saved_s2 = saved_run_config.get("strategy2_checkpoint_path")
if current_s2 or saved_s2:
if str(current_s2 or "") != str(saved_s2 or ""):
# Warn but do not abort: when resuming, the model weights are fully restored
# from the resume checkpoint (not re-loaded from the strategy2 checkpoint),
# so a path change (e.g. file moved/renamed) does not affect correctness.
print(
f"[WARN] strategy2_checkpoint_path changed since checkpoint was saved "
f"(current={current_s2!r}, checkpoint={saved_s2!r}). "
f"Resuming anyway — model state comes from the resume checkpoint."
)
if mismatches:
raise ValueError(
f"Resume checkpoint identity mismatch for {checkpoint_path}:\n" + "\n".join(f" - {line}" for line in mismatches)
)
def load_history_for_resume(history_path: Path, checkpoint_payload: dict[str, Any]) -> list[dict[str, Any]]:
checkpoint_epoch = int(checkpoint_payload.get("epoch", 0))
epoch_metrics = checkpoint_payload.get("epoch_metrics")
history: list[dict[str, Any]] = []
checkpoint_history = checkpoint_payload.get("history")
if isinstance(checkpoint_history, list):
history = [dict(row) for row in checkpoint_history if isinstance(row, dict)]
history = [row for row in history if int(row.get("epoch", 0)) <= checkpoint_epoch]
if history_path.exists():
payload = load_json(history_path)
if not isinstance(payload, list):
raise RuntimeError(f"Expected list history at {history_path}, found {type(payload).__name__}.")
file_history = [dict(row) for row in payload if isinstance(row, dict)]
file_history = [row for row in file_history if int(row.get("epoch", 0)) <= checkpoint_epoch]
if len(file_history) >= len(history):
history = file_history
if not history and isinstance(epoch_metrics, dict):
history = [dict(epoch_metrics)]
elif history and isinstance(epoch_metrics, dict):
if int(history[-1].get("epoch", 0)) < checkpoint_epoch:
history.append(dict(epoch_metrics))
return history
def train_model(
*,
run_type: str,
model_config: RuntimeModelConfig,
run_config: dict[str, Any],
model: nn.Module,
description: str,
strategy: int,
run_dir: Path,
bundle: DataBundle,
max_epochs: int,
head_lr: float,
encoder_lr: float,
weight_decay: float,
tmax: int,
entropy_lr: float,
entropy_alpha_init: float,
entropy_target_ratio: float,
critic_loss_weight: float,
ce_weight: float,
dice_weight: float,
dropout_p: float,
resume_checkpoint_path: Path | None = None,
trial: optuna.trial.Trial | None = None,
) -> tuple[dict[str, Any], list[dict[str, Any]]]:
amp_dtype = resolve_amp_dtype(AMP_DTYPE)
use_amp = amp_autocast_enabled(DEVICE)
use_channels_last = _use_channels_last_for_run(model_config)
if resume_checkpoint_path is not None and strategy in (3, 4):
_configure_model_from_checkpoint_path(model, resume_checkpoint_path)
_configure_mc_dropout_from_params(model)
print_model_parameter_summary(
model=model,
description=description,
strategy=strategy,
model_config=model_config,
dropout_p=dropout_p,
amp_dtype=amp_dtype,
compiled=hasattr(model, "_orig_mod"),
)
strategy3_freeze_status = _strategy3_bootstrap_freeze_status(model) if strategy == 3 else None
strategy3_frozen_decoder = strategy == 3 and _strategy3_decoder_is_frozen(model)
decoder_head_lr = float(_job_param("decoder_lr", 0.0 if strategy3_frozen_decoder else head_lr * 0.1))
encoder_group_lr = 0.0 if strategy3_frozen_decoder else encoder_lr
rl_group_lr = float(_job_param("rl_lr", head_lr))
optimizer = make_optimizer(
model,
strategy,
head_lr=decoder_head_lr,
encoder_lr=encoder_group_lr,
weight_decay=weight_decay,
rl_lr=rl_group_lr,
)
scheduler = CosineAnnealingLR(
optimizer,
T_max=200, # full training epochs
eta_min=1e-6, # floor
)
scaler = make_grad_scaler(enabled=use_amp, amp_dtype=amp_dtype, device=DEVICE)
target_entropy = entropy_target_ratio * math.log(max(_model_policy_action_count(model) or NUM_ACTIONS, 2))
log_alpha = torch.tensor(math.log(max(entropy_alpha_init, 1e-8)), dtype=torch.float32, device=DEVICE, requires_grad=True)
alpha_optimizer = Adam([log_alpha], lr=entropy_lr)
save_artifacts = run_type == "final"
save_history_incrementally = bool(run_config.get("save_history_incrementally", SAVE_HISTORY_INCREMENTALLY))
write_epoch_diagnostic = bool(run_config.get("write_epoch_diagnostic", WRITE_EPOCH_DIAGNOSTIC))
ckpt_dir = ensure_dir(run_dir / "checkpoints") if save_artifacts else None
plots_dir = ensure_dir(run_dir / "plots") if save_artifacts else None
history_path = checkpoint_history_path(run_dir, run_type)
diagnostic_path = diagnostic_path_for_run(run_dir) if run_type == "final" and write_epoch_diagnostic else None
history: list[dict[str, Any]] = []
selection_metric_name = _strategy_selection_metric_name(strategy)
early_stopping_monitor_name = _early_stopping_monitor_name(strategy)
early_stopping_mode = _early_stopping_mode(strategy, early_stopping_monitor_name)
early_stopping_min_delta = _early_stopping_min_delta()
early_stopping_start_epoch = _early_stopping_start_epoch()
early_stopping_patience = _early_stopping_patience()
best_model_metric = -float("inf")
patience_counter = 0
best_early_stopping_metric: float | None = None
elapsed_before_resume = 0.0
start_epoch = 1
resume_source: dict[str, Any] | None = None
diagnostic_payload: dict[str, Any] | None = None
train_probe_batches: list[dict[str, Any]] = []
val_probe_batches: list[dict[str, Any]] = []
run_label = run_identity_label(
strategy=strategy,
percent=bundle.percent,
trial_number=trial.number if trial is not None else None,
split_payload=bundle.split_payload,
)
if diagnostic_path is not None:
train_probe_batches = _fixed_probe_batches_from_dataset(
bundle.train_ds,
num_batches=EPOCH_DIAGNOSTIC_TRAIN_BATCHES,
device=DEVICE,
)
val_probe_batches = _fixed_probe_batches_from_dataset(
bundle.val_ds,
num_batches=EPOCH_DIAGNOSTIC_VAL_BATCHES,
device=DEVICE,
)
diagnostic_payload = empty_epoch_diagnostic_payload(
run_type=run_type,
run_config=run_config,
bundle=bundle,
train_probe_batches=train_probe_batches,
val_probe_batches=val_probe_batches,
)
if resume_checkpoint_path is not None:
checkpoint_payload = load_checkpoint(
resume_checkpoint_path,
model=model,
optimizer=optimizer,
scheduler=scheduler,
scaler=scaler,
device=DEVICE,
log_alpha=log_alpha if strategy != 2 else None,
alpha_optimizer=alpha_optimizer if strategy != 2 else None,
expected_run_type=run_type,
require_run_metadata=True,
)
validate_resume_checkpoint_identity(
run_config,
checkpoint_run_config_payload(checkpoint_payload),
checkpoint_path=resume_checkpoint_path,
)
start_epoch = int(checkpoint_payload["epoch"]) + 1
selection_metric_name = str(checkpoint_payload.get("best_metric_name", selection_metric_name))
best_model_metric = float(checkpoint_payload["best_metric_value"])
patience_counter = int(checkpoint_payload.get("patience_counter", 0))
elapsed_before_resume = float(checkpoint_payload.get("elapsed_seconds", 0.0))
history = load_history_for_resume(history_path, checkpoint_payload)
resume_source = {
"checkpoint_path": str(Path(resume_checkpoint_path).resolve()),
"checkpoint_epoch": int(checkpoint_payload["epoch"]),
"checkpoint_run_type": checkpoint_payload.get("run_type", run_type),
}
epoch_metrics = checkpoint_payload.get("epoch_metrics")
if isinstance(epoch_metrics, dict) and epoch_metrics.get("early_stopping_best_value") is not None:
best_early_stopping_metric = float(epoch_metrics["early_stopping_best_value"])
if diagnostic_path is not None and diagnostic_payload is not None:
diagnostic_payload = load_epoch_diagnostic_for_resume(
diagnostic_path,
checkpoint_payload,
diagnostic_payload,
)
print(
f"[Resume] {run_label} | {run_type} continuing from {resume_checkpoint_path} "
f"at epoch {start_epoch}/{max_epochs}."
)
prev_params = _snapshot_params(model) if diagnostic_path is not None else None
start_time = time.time()
validate_interval = max(int(VALIDATE_EVERY_N_EPOCHS), 1)
for epoch in range(start_epoch, max_epochs + 1):
epoch_losses: list[float] = []
epoch_actor: list[float] = []
epoch_critic: list[float] = []
epoch_reward: list[float] = []
epoch_entropy: list[float] = []
epoch_ce: list[float] = []
epoch_dice_loss: list[float] = []
epoch_grad: list[float] = []
epoch_dices: list[float] = []
epoch_ious: list[float] = []
epoch_effective_steps: list[float] = []
epoch_mask_deltas: list[float] = []
epoch_advantage_means: list[float] = []
epoch_advantage_stds: list[float] = []
epoch_value_pred_errors: list[float] = []
epoch_alphas: list[float] = []
epoch_action_dists: list[dict[str, float]] = []
prefetcher = CUDAPrefetcher(bundle.train_loader, DEVICE)
progress = tqdm(prefetcher, total=len(bundle.train_loader), desc=f"Epoch {epoch}/{max_epochs}", leave=False)
for batch in progress:
if strategy == 2:
metrics = train_step_supervised(
model,
batch,
optimizer,
scaler=scaler,
use_amp=use_amp,
amp_dtype=amp_dtype,
use_channels_last=use_channels_last,
grad_clip_norm=DEFAULT_GRAD_CLIP_NORM,
ce_weight=ce_weight,
dice_weight=dice_weight,
)
elif strategy in (3, 4):
metrics = train_step_strategy3(
model,
batch,
optimizer,
gamma=DEFAULT_GAMMA,
tmax=tmax,
critic_loss_weight=critic_loss_weight,
log_alpha=log_alpha,
alpha_optimizer=alpha_optimizer,
target_entropy=target_entropy,
ce_weight=ce_weight,
dice_weight=dice_weight,
grad_clip_norm=DEFAULT_GRAD_CLIP_NORM,
scaler=scaler,
use_amp=use_amp,
amp_dtype=amp_dtype,
stepwise_backward=STEPWISE_BACKWARD,
use_channels_last=use_channels_last,
current_epoch=epoch,
max_epochs=max_epochs,
)
else:
metrics = train_step(
model,
batch,
optimizer,
gamma=DEFAULT_GAMMA,
tmax=tmax,
critic_loss_weight=critic_loss_weight,
log_alpha=log_alpha,
alpha_optimizer=alpha_optimizer,
target_entropy=target_entropy,
ce_weight=ce_weight,
dice_weight=dice_weight,
grad_clip_norm=DEFAULT_GRAD_CLIP_NORM,
scaler=scaler,
use_amp=use_amp,
amp_dtype=amp_dtype,
stepwise_backward=STEPWISE_BACKWARD,
use_channels_last=use_channels_last,
current_epoch=epoch,
max_epochs=OVERFIT_N_EPOCHS,
)
epoch_losses.append(metrics["loss"])
epoch_actor.append(metrics["actor_loss"])
epoch_critic.append(metrics["critic_loss"])
epoch_reward.append(metrics["mean_reward"])
epoch_entropy.append(metrics["entropy"])
epoch_ce.append(metrics["ce_loss"])
epoch_dice_loss.append(metrics["dice_loss"])
epoch_grad.append(metrics["grad_norm"])
if "effective_steps" in metrics:
epoch_effective_steps.append(float(metrics["effective_steps"]))
if "mask_delta_mean" in metrics:
epoch_mask_deltas.append(metrics["mask_delta_mean"])
if "advantage_mean" in metrics:
epoch_advantage_means.append(metrics["advantage_mean"])
if "advantage_std" in metrics:
epoch_advantage_stds.append(metrics["advantage_std"])
if "value_pred_error_mean" in metrics:
epoch_value_pred_errors.append(metrics["value_pred_error_mean"])
if "alpha" in metrics:
epoch_alphas.append(metrics["alpha"])
if "action_distribution" in metrics and metrics["action_distribution"]:
epoch_action_dists.append(metrics["action_distribution"])
pred_mask = metrics["final_mask"]
gt_mask = batch["mask"].float()
inter = (pred_mask * gt_mask).sum(dim=(1, 2, 3))
pred_sum = pred_mask.sum(dim=(1, 2, 3))
gt_sum = gt_mask.sum(dim=(1, 2, 3))
dice = (2.0 * inter + _EPS) / (pred_sum + gt_sum + _EPS)
iou = (inter + _EPS) / (pred_sum + gt_sum - inter + _EPS)
epoch_dices.extend(dice.detach().cpu().tolist())
epoch_ious.extend(iou.detach().cpu().tolist())
head_lr_now = float(optimizer.param_groups[-1]["lr"])
enc_lr_now = float(optimizer.param_groups[0]["lr"]) if len(optimizer.param_groups) > 1 else head_lr_now
progress.set_postfix(loss=f"{metrics['loss']:.4f}", iou=f"{np.mean(epoch_ious):.4f}", lr=f"{head_lr_now:.2e}")
should_validate = epoch % validate_interval == 0 or epoch == max_epochs
val_metrics: dict[str, float | None] = {
"val_loss": None,
"val_dice": None,
"val_iou": None,
"val_reward": None,
"val_entropy": None,
}
if should_validate:
tqdm.write(
f"[{run_label}] Epoch {epoch}/{max_epochs}: running validation on {len(bundle.val_loader)} batches..."
)
validated_metrics = validate(
model,
bundle.val_loader,
strategy=strategy,
tmax=tmax,
use_amp=use_amp,
amp_dtype=amp_dtype,
use_channels_last=use_channels_last,
gamma=DEFAULT_GAMMA,
critic_loss_weight=critic_loss_weight,
ce_weight=ce_weight,
dice_weight=dice_weight,
training_progress=_strategy3_training_progress(epoch, max_epochs),
)
val_metrics.update(validated_metrics)
scheduler.step() # always step up the scheduler
grad_stats: dict[str, Any] = {}
param_stats: dict[str, Any] = {}
if diagnostic_path is not None:
grad_stats = _grad_diagnostics(model)
param_stats = _param_diagnostics(model, prev_params)
prev_params = _snapshot_params(model)
avg_epoch_action_dist: dict[str, float] = {}
if epoch_action_dists:
all_act_keys = set()
for d in epoch_action_dists:
all_act_keys.update(d.keys())
for k in sorted(all_act_keys):
avg_epoch_action_dist[k] = float(np.mean([d.get(k, 0.0) for d in epoch_action_dists]))
row = {
"epoch": epoch,
"train_loss": float(np.mean(epoch_losses)) if epoch_losses else 0.0,
"train_actor_loss": float(np.mean(epoch_actor)) if epoch_actor else 0.0,
"train_critic_loss": float(np.mean(epoch_critic)) if epoch_critic else 0.0,
"train_mean_reward": float(np.mean(epoch_reward)) if epoch_reward else 0.0,
"train_entropy": float(np.mean(epoch_entropy)) if epoch_entropy else 0.0,
"train_ce_loss": float(np.mean(epoch_ce)) if epoch_ce else 0.0,
"train_dice_loss": float(np.mean(epoch_dice_loss)) if epoch_dice_loss else 0.0,
"train_dice": float(np.mean(epoch_dices)) if epoch_dices else 0.0,
"train_iou": float(np.mean(epoch_ious)) if epoch_ious else 0.0,
"grad_norm": float(np.mean(epoch_grad)) if epoch_grad else 0.0,
"lr": float(optimizer.param_groups[-1]["lr"]),
"encoder_lr": float(optimizer.param_groups[0]["lr"]) if len(optimizer.param_groups) > 1 else float(optimizer.param_groups[-1]["lr"]),
"alpha": float(log_alpha.exp().detach().item()) if strategy != 2 else 0.0,
"train_effective_steps": float(np.mean(epoch_effective_steps)) if epoch_effective_steps else 0.0,
"train_mask_delta_mean": float(np.mean(epoch_mask_deltas)) if epoch_mask_deltas else 0.0,
"train_advantage_mean": float(np.mean(epoch_advantage_means)) if epoch_advantage_means else 0.0,
"train_advantage_std": float(np.mean(epoch_advantage_stds)) if epoch_advantage_stds else 0.0,
"train_value_pred_error": float(np.mean(epoch_value_pred_errors)) if epoch_value_pred_errors else 0.0,
"train_alpha": float(np.mean(epoch_alphas)) if epoch_alphas else 0.0,
"train_action_distribution": avg_epoch_action_dist if avg_epoch_action_dist else None,
"validated_this_epoch": should_validate,
**val_metrics,
}
if strategy3_freeze_status is not None:
row["strategy3_bootstrap_loaded"] = bool(strategy3_freeze_status["bootstrap_loaded"])
row["strategy3_freeze_requested"] = bool(strategy3_freeze_status["freeze_requested"])
row["strategy3_freeze_active"] = bool(strategy3_freeze_status["freeze_active"])
row["strategy3_encoder_state"] = str(strategy3_freeze_status["encoder_state"])
row["strategy3_decoder_state"] = str(strategy3_freeze_status["decoder_state"])
row["strategy3_segmentation_head_state"] = str(strategy3_freeze_status["segmentation_head_state"])
history.append(row)
improved = False
early_stopping_improved_now = False
if should_validate:
val_iou = float(val_metrics["val_iou"])
selected_metric_value = _strategy_selection_metric_value(strategy, val_metrics)
row["selection_metric_name"] = selection_metric_name
row["selection_metric_value"] = selected_metric_value
improved = selected_metric_value > best_model_metric
if improved:
best_model_metric = selected_metric_value
early_stopping_monitor_value = _early_stopping_monitor_value(
row,
strategy=strategy,
monitor_name=early_stopping_monitor_name,
)
early_stopping_active = epoch >= early_stopping_start_epoch
if early_stopping_active and early_stopping_monitor_value is not None:
early_stopping_improved_now = _early_stopping_improved(
early_stopping_monitor_value,
best_early_stopping_metric,
mode=early_stopping_mode,
min_delta=early_stopping_min_delta,
)
if early_stopping_improved_now:
best_early_stopping_metric = early_stopping_monitor_value
patience_counter = 0
else:
patience_counter += 1
row["early_stopping_monitor_name"] = early_stopping_monitor_name
row["early_stopping_monitor_mode"] = early_stopping_mode
row["early_stopping_monitor_value"] = early_stopping_monitor_value
row["early_stopping_best_value"] = best_early_stopping_metric
row["early_stopping_min_delta"] = early_stopping_min_delta
row["early_stopping_start_epoch"] = early_stopping_start_epoch
row["early_stopping_patience"] = early_stopping_patience
row["early_stopping_active"] = early_stopping_active
row["early_stopping_improved"] = early_stopping_improved_now
row["early_stopping_wait"] = int(patience_counter)
if improved and save_artifacts and ckpt_dir is not None:
save_checkpoint(
ckpt_dir / "best.pt",
run_type=run_type,
model=model,
optimizer=optimizer,
scheduler=scheduler,
scaler=scaler,
epoch=epoch,
best_metric_value=best_model_metric,
best_metric_name=selection_metric_name,
run_config=run_config,
epoch_metrics=row,
patience_counter=patience_counter,
elapsed_seconds=elapsed_before_resume + (time.time() - start_time),
history=history,
log_alpha=log_alpha if strategy != 2 else None,
alpha_optimizer=alpha_optimizer if strategy != 2 else None,
resume_source=resume_source,
)
else:
row["early_stopping_monitor_name"] = early_stopping_monitor_name
row["early_stopping_monitor_mode"] = early_stopping_mode
row["early_stopping_monitor_value"] = None
row["early_stopping_best_value"] = best_early_stopping_metric
row["early_stopping_min_delta"] = early_stopping_min_delta
row["early_stopping_start_epoch"] = early_stopping_start_epoch
row["early_stopping_patience"] = early_stopping_patience
row["early_stopping_active"] = False
row["early_stopping_improved"] = False
row["early_stopping_wait"] = int(patience_counter)
if save_artifacts and save_history_incrementally:
if plots_dir is not None and run_type != "trial":
_save_training_plots(history, plots_dir)
save_json(history_path, history)
if diagnostic_path is not None and diagnostic_payload is not None:
epoch_alerts = _numerical_health_check(row, prefix=f"epoch[{epoch}]:")
if int(grad_stats.get("n_nan", 0)) > 0:
epoch_alerts.append(f"epoch[{epoch}]: grad diagnostics detected NaN gradients")
if int(grad_stats.get("n_inf", 0)) > 0:
epoch_alerts.append(f"epoch[{epoch}]: grad diagnostics detected Inf gradients")
train_probe = _evaluate_probe_batches(
model,
train_probe_batches,
strategy=strategy,
tmax=tmax,
use_amp=use_amp,
amp_dtype=amp_dtype,
use_channels_last=use_channels_last,
)
val_probe = _evaluate_probe_batches(
model,
val_probe_batches,
strategy=strategy,
tmax=tmax,
use_amp=use_amp,
amp_dtype=amp_dtype,
use_channels_last=use_channels_last,
)
epoch_alerts.extend(train_probe.get("alerts", []))
epoch_alerts.extend(val_probe.get("alerts", []))
diagnostic_payload["epochs"].append(
{
"epoch": epoch,
"elapsed_seconds": elapsed_before_resume + (time.time() - start_time),
"is_new_best": bool(improved),
"best_metric_name": selection_metric_name,
"best_metric_value_so_far": float(best_model_metric),
"patience_counter": int(patience_counter),
"early_stopping_monitor_name": early_stopping_monitor_name,
"early_stopping_monitor_mode": early_stopping_mode,
"early_stopping_min_delta": float(early_stopping_min_delta),
"early_stopping_start_epoch": int(early_stopping_start_epoch),
"early_stopping_patience": int(early_stopping_patience),
"early_stopping_best_value_so_far": best_early_stopping_metric,
"history_row": dict(row),
"train_batch_summary": {
"loss": _summary_stats(epoch_losses),
"actor_loss": _summary_stats(epoch_actor),
"critic_loss": _summary_stats(epoch_critic),
"reward": _summary_stats(epoch_reward),
"entropy": _summary_stats(epoch_entropy),
"ce_loss": _summary_stats(epoch_ce),
"dice_loss": _summary_stats(epoch_dice_loss),
"grad_norm": _summary_stats(epoch_grad),
"dice": _summary_stats(epoch_dices),
"iou": _summary_stats(epoch_ious),
"effective_steps": _summary_stats(epoch_effective_steps),
"mask_delta": _summary_stats(epoch_mask_deltas),
"advantage_mean": _summary_stats(epoch_advantage_means),
"advantage_std": _summary_stats(epoch_advantage_stds),
"value_pred_error": _summary_stats(epoch_value_pred_errors),
"alpha": _summary_stats(epoch_alphas),
"action_distribution": avg_epoch_action_dist if avg_epoch_action_dist else None,
},
"optimizer": {
"param_groups": _optimizer_diagnostics(optimizer),
"scheduler_last_lr": [float(value) for value in scheduler.get_last_lr()],
"target_entropy": float(target_entropy) if strategy != 2 else 0.0,
},
"grad_diagnostics": grad_stats,
"param_diagnostics": param_stats,
"probes": {
"train_fixed": train_probe,
"val_fixed": val_probe,
},
"probe_epoch_summary": {
"train_fixed": _format_probe_deterioration("train", train_probe, tmax),
"val_fixed": _format_probe_deterioration("val", val_probe, tmax),
},
"alerts": epoch_alerts,
}
)
save_json(diagnostic_path, diagnostic_payload)
if save_artifacts and ckpt_dir is not None and SAVE_LATEST_EVERY_EPOCH and run_type != "trial":
save_checkpoint(
ckpt_dir / "latest.pt",
run_type=run_type,
model=model,
optimizer=optimizer,
scheduler=scheduler,
scaler=scaler,
epoch=epoch,
best_metric_value=best_model_metric,
best_metric_name=selection_metric_name,
run_config=run_config,
epoch_metrics=row,
patience_counter=patience_counter,
elapsed_seconds=elapsed_before_resume + (time.time() - start_time),
history=history,
log_alpha=log_alpha if strategy != 2 else None,
alpha_optimizer=alpha_optimizer if strategy != 2 else None,
resume_source=resume_source,
)
if save_artifacts and ckpt_dir is not None and CHECKPOINT_EVERY_N_EPOCHS > 0 and epoch % CHECKPOINT_EVERY_N_EPOCHS == 0 and run_type != "trial":
save_checkpoint(
ckpt_dir / f"epoch_{epoch:04d}.pt",
run_type=run_type,
model=model,
optimizer=optimizer,
scheduler=scheduler,
scaler=scaler,
epoch=epoch,
best_metric_value=best_model_metric,
best_metric_name=selection_metric_name,
run_config=run_config,
epoch_metrics=row,
patience_counter=patience_counter,
elapsed_seconds=elapsed_before_resume + (time.time() - start_time),
history=history,
log_alpha=log_alpha if strategy != 2 else None,
alpha_optimizer=alpha_optimizer if strategy != 2 else None,
resume_source=resume_source,
)
if trial is not None and should_validate:
reported_metric = row.get("selection_metric_value")
if reported_metric is None:
reported_metric = _strategy_selection_metric_value(strategy, val_metrics)
if reported_metric is None:
reported_metric = float(val_metrics["val_iou"])
reported_metric = float(reported_metric)
trial.report(reported_metric, step=epoch)
if USE_TRIAL_PRUNING and epoch >= TRIAL_PRUNER_WARMUP_STEPS and trial.should_prune():
raise optuna.TrialPruned(
f"Trial pruned at epoch {epoch} with "
f"{selection_metric_name}={reported_metric:.4f}"
)
if VERBOSE_EPOCH_LOG:
tqdm.write(f"[{run_label}] Epoch {epoch}/{max_epochs}")
tqdm.write(json.dumps(row, indent=2))
else:
tqdm.write(
f"[{run_label}] Epoch {epoch}/{max_epochs}: "
f"{format_concise_epoch_log(row, best_metric_name=selection_metric_name, best_metric_value=best_model_metric)}"
)
if should_validate and early_stopping_patience > 0 and patience_counter >= early_stopping_patience:
print(
f"Early stopping triggered at epoch {epoch}: "
f"monitor={early_stopping_monitor_name} mode={early_stopping_mode} "
f"best={best_early_stopping_metric} current={row.get('early_stopping_monitor_value')} "
f"min_delta={early_stopping_min_delta:.6g} wait={patience_counter}/{early_stopping_patience}."
)
break
elapsed = elapsed_before_resume + (time.time() - start_time)
if save_artifacts:
save_json(history_path, history)
if plots_dir is not None and run_type != "trial":
_save_training_plots(history, plots_dir)
summary = {
"best_model_metric_name": selection_metric_name,
"best_model_metric": float(best_model_metric),
"early_stopping_monitor_name": early_stopping_monitor_name,
"early_stopping_monitor_mode": early_stopping_mode,
"early_stopping_min_delta": float(early_stopping_min_delta),
"early_stopping_start_epoch": int(early_stopping_start_epoch),
"early_stopping_patience": int(early_stopping_patience),
"early_stopping_best_value": best_early_stopping_metric,
"best_val_iou": max((float(r["val_iou"]) for r in history if r.get("val_iou") is not None), default=0.0),
"best_val_dice": max((float(r["val_dice"]) for r in history if r.get("val_dice") is not None), default=0.0),
"best_val_iou_gain": max((float(r["val_iou_gain"]) for r in history if r.get("val_iou_gain") is not None), default=0.0),
"final_epoch": int(history[-1]["epoch"]) if history else int(start_epoch - 1),
"elapsed_seconds": elapsed,
"seconds_per_epoch": elapsed / max(len(history), 1),
"device_used": str(DEVICE),
"strategy": strategy,
"run_type": run_type,
"resumed": resume_source is not None,
}
if strategy3_freeze_status is not None:
summary.update(
{
"strategy3_bootstrap_loaded": bool(strategy3_freeze_status["bootstrap_loaded"]),
"strategy3_freeze_requested": bool(strategy3_freeze_status["freeze_requested"]),
"strategy3_freeze_active": bool(strategy3_freeze_status["freeze_active"]),
"strategy3_encoder_state": str(strategy3_freeze_status["encoder_state"]),
"strategy3_decoder_state": str(strategy3_freeze_status["decoder_state"]),
"strategy3_segmentation_head_state": str(strategy3_freeze_status["segmentation_head_state"]),
}
)
if resume_source is not None:
summary["resume_source"] = resume_source
if save_artifacts:
save_json(run_dir / "summary.json", summary)
return summary, history
"""=============================================================================
EVALUATION + SMOKE TEST
=============================================================================
"""
def _save_rgb_panel(image_chw: np.ndarray, pred_hw: np.ndarray, gt_hw: np.ndarray, output_path: Path, title: str) -> None:
img = image_chw.transpose(1, 2, 0)
img = (img - img.min()) / (img.max() - img.min() + 1e-8)
fig, axes = plt.subplots(1, 3, figsize=(12, 4))
axes[0].imshow(img)
axes[0].set_title("Input")
axes[1].imshow(pred_hw, cmap="gray", vmin=0, vmax=1)
axes[1].set_title("Prediction")
axes[2].imshow(gt_hw, cmap="gray", vmin=0, vmax=1)
axes[2].set_title("Ground Truth")
for ax in axes:
ax.axis("off")
fig.suptitle(title)
fig.tight_layout()
fig.savefig(output_path, dpi=120)
plt.close(fig)
def evaluate_model(
*,
model: nn.Module,
model_config: RuntimeModelConfig,
bundle: DataBundle,
run_dir: Path,
strategy: int,
tmax: int,
best_metric_name: str,
) -> tuple[dict[str, dict[str, float]], list[dict[str, Any]]]:
amp_dtype = resolve_amp_dtype(AMP_DTYPE)
use_amp = amp_autocast_enabled(DEVICE)
use_channels_last = _use_channels_last_for_run(model_config)
pred_dir = ensure_dir(run_dir / "predictions")
pred_255_dir = ensure_dir(run_dir / "predictions_255")
model.eval()
per_metric = {k: [] for k in ("dice", "ppv", "sen", "iou", "biou", "hd95")}
per_sample: list[dict[str, Any]] = []
with torch.inference_mode():
prefetcher = CUDAPrefetcher(bundle.test_loader, DEVICE)
for batch in tqdm(prefetcher, total=len(bundle.test_loader), desc="Evaluating", leave=False):
image = batch["image"]
gt = batch["mask"]
if use_amp and DEVICE.type == "cuda":
image = image.to(dtype=amp_dtype)
pred = infer_segmentation_mask(
model,
image,
tmax,
strategy=strategy,
use_amp=use_amp,
amp_dtype=amp_dtype,
use_channels_last=use_channels_last,
).float()
pred_np = pred.cpu().numpy().astype(np.uint8)
gt_np = gt.cpu().numpy().astype(np.uint8)
sample_ids = batch["sample_id"]
for idx in range(pred_np.shape[0]):
metrics = compute_all_metrics(pred_np[idx], gt_np[idx])
for key, value in metrics.items():
per_metric[key].append(value)
per_sample.append({"sample_id": sample_ids[idx], **metrics})
mask_2d = pred_np[idx].squeeze()
PILImage.fromarray(mask_2d).save(pred_dir / f"{sample_ids[idx]}.png")
PILImage.fromarray((mask_2d * 255).astype(np.uint8)).save(pred_255_dir / f"{sample_ids[idx]}.png")
aggregate: dict[str, dict[str, float]] = {}
for key, values in per_metric.items():
values_np = np.array(values, dtype=np.float32)
aggregate[key] = {"mean": float(values_np.mean()), "std": float(values_np.std())}
save_json(
run_dir / "evaluation.json",
{
"strategy": strategy,
"best_metric_name": str(best_metric_name),
"metrics": aggregate,
"per_sample": per_sample,
},
)
df_all = pd.DataFrame(per_sample)
avg_row = {}
for column in df_all.columns:
avg_row[column] = df_all[column].mean() if pd.api.types.is_numeric_dtype(df_all[column]) else "AVERAGE"
df_samples = pd.concat([df_all, pd.DataFrame([avg_row])], ignore_index=True)
df_summary = pd.DataFrame(aggregate).T
df_summary.index.name = "metric"
df_low_iou = df_all[df_all["iou"] < 0.01]
history_path = run_dir / "history.json"
df_history = pd.DataFrame(load_json(history_path)) if history_path.exists() else None
xlsx_path = run_dir / "evaluation_results.xlsx"
with pd.ExcelWriter(xlsx_path, engine="openpyxl") as writer:
df_samples.to_excel(writer, sheet_name="Per Sample", index=False)
df_summary.to_excel(writer, sheet_name="Summary")
if not df_low_iou.empty:
df_low_iou.to_excel(writer, sheet_name="Low IoU Samples", index=False)
if df_history is not None:
df_history.to_excel(writer, sheet_name="Training History", index=False)
csv_rows = [{"sample_id": row["sample_id"]} for row in df_low_iou.to_dict(orient="records")]
save_json(run_dir / "evaluation_summary.json", {"mean_iou": aggregate["iou"]["mean"], "mean_dice": aggregate["dice"]["mean"]})
pd.DataFrame(csv_rows).to_csv(run_dir / "low_iou_samples.csv", index=False)
return aggregate, per_sample
def percent_root(percent: float) -> Path:
return ensure_dir(RUNS_ROOT / MODEL_NAME / f"pct_{percent_label(percent)}")
def strategy_dir_name(strategy: int, model_config: RuntimeModelConfig | None = None) -> str:
model_config = (model_config or current_model_config()).validate()
if model_config.backbone_family == "custom_vgg":
return f"strategy_{strategy}_custom_vgg"
return f"strategy_{strategy}"
def strategy_root_for_percent(
strategy: int,
percent: float,
model_config: RuntimeModelConfig | None = None,
) -> Path:
return ensure_dir(percent_root(percent) / strategy_dir_name(strategy, model_config))
def final_root_for_strategy(
strategy: int,
percent: float,
model_config: RuntimeModelConfig | None = None,
) -> Path:
return ensure_dir(strategy_root_for_percent(strategy, percent, model_config) / "final")
def ensure_specific_checkpoint_scope(selector_name: str, selector_mode: str) -> None:
if selector_mode != "specific":
return
# Allow STRATEGY2 checkpoints with dict mapping for dynamic per-percent selection
if "strategy2" in selector_name.lower() and isinstance(STRATEGY2_SPECIFIC_CHECKPOINT, dict):
return
if len(STRATEGIES) != 1 or len(DATASET_PERCENTS) != 1:
raise ValueError(
f"{selector_name}=specific is only supported when exactly one strategy and one dataset percent are selected. "
f"Got STRATEGIES={STRATEGIES} and DATASET_PERCENTS={DATASET_PERCENTS}."
)
def resolve_checkpoint_path(
*,
run_dir: Path,
selector_mode: str,
specific_checkpoint: str | Path | dict,
purpose: str,
) -> Path:
run_dir = Path(run_dir)
if selector_mode == "latest":
checkpoint_path = run_dir / "checkpoints" / "latest.pt"
elif selector_mode == "best":
checkpoint_path = run_dir / "checkpoints" / "best.pt"
elif selector_mode == "specific":
ensure_specific_checkpoint_scope(purpose, selector_mode)
if not specific_checkpoint:
raise ValueError(f"{purpose}=specific requires a non-empty specific checkpoint path.")
checkpoint_path = Path(specific_checkpoint).expanduser().resolve()
else:
raise ValueError(f"Unsupported checkpoint selector mode '{selector_mode}' for {purpose}.")
if not checkpoint_path.exists():
raise FileNotFoundError(f"Checkpoint for {purpose} not found: {checkpoint_path}")
return checkpoint_path
def resolve_train_resume_checkpoint_path(run_dir: Path) -> Path | None:
if TRAIN_RESUME_MODE == "off":
return None
return resolve_checkpoint_path(
run_dir=run_dir,
selector_mode=TRAIN_RESUME_MODE,
specific_checkpoint=TRAIN_RESUME_SPECIFIC_CHECKPOINT,
purpose="train_resume_checkpoint",
)
def resolve_strategy2_checkpoint_path(
strategy: int,
percent: float,
model_config: RuntimeModelConfig | None = None,
) -> Path:
if strategy not in (3, 4, 5):
raise ValueError(f"Strategy 2 dependency checkpoint requested for unsupported strategy {strategy}.")
# --- ADD THIS BLOCK ---
specific_checkpoint = STRATEGY2_SPECIFIC_CHECKPOINT
if isinstance(specific_checkpoint, dict):
specific_checkpoint = specific_checkpoint.get(percent, "")
# ----------------------
checkpoint_path = resolve_checkpoint_path(
run_dir=final_root_for_strategy(2, percent, model_config),
selector_mode=STRATEGY2_CHECKPOINT_MODE,
specific_checkpoint=specific_checkpoint,
purpose="strategy2_checkpoint",
)
# Print which checkpoint is being used
checkpoint_label = run_identity_label(strategy=strategy, percent=percent)
ctx = globals().get("CURRENT_FOLD_CONTEXT")
if ctx is not None and abs(float(percent) - float(ctx.percent_fraction)) <= 1e-12:
checkpoint_label = run_identity_label(
strategy=strategy,
percent=percent,
split_payload={
"split_repeat_index": ctx.split_repeat_index,
"subset_repeat_index": ctx.subset_repeat_index,
"dataset_percent": ctx.percent_fraction,
},
)
print(f"[Strategy 2 Checkpoint] {checkpoint_label} | Loading: {checkpoint_path}")
return checkpoint_path
def load_required_hparams(payload: dict[str, Any], *, source: str, strategy: int, percent: float) -> dict[str, Any]:
missing_keys = [name for name in REQUIRED_HPARAM_KEYS if name not in payload]
if missing_keys:
raise KeyError(
f"Incomplete hyperparameters for strategy={strategy}, percent={percent_text(percent)} from {source}. "
f"Missing keys: {missing_keys}. Required keys: {REQUIRED_HPARAM_KEYS}."
)
return dict(payload)
def load_saved_best_params_if_optuna_off(
strategy: int,
percent: float,
*,
model_config: RuntimeModelConfig,
) -> dict[str, Any]:
_, study_root, _ = study_paths_for(strategy, percent, model_config)
best_params_path = study_root / "best_params.json"
if not best_params_path.exists():
raise FileNotFoundError(
f"RUN_OPTUNA=False and USE_EXISTING_BEST_PARAMS_WHEN_OPTUNA_OFF=True, but no saved best params were found "
f"for strategy={strategy}, percent={percent_text(percent)} at {best_params_path}."
)
params = load_json(best_params_path)
params = load_required_hparams(
params,
source=str(best_params_path),
strategy=strategy,
percent=percent,
)
print(
f"[Optuna Off] Using saved best parameters for strategy={strategy}, "
f"percent={percent_text(percent)} from {best_params_path}."
)
for name in REQUIRED_HPARAM_KEYS:
print(f" {name:20s}: {_format_hparam_value(name, params[name])}")
return params
def load_manual_hparams_if_optuna_off(strategy: int, percent: float) -> dict[str, Any]:
key = manual_hparams_key(strategy, percent)
if key not in MANUAL_HPARAMS_IF_OPTUNA_OFF:
raise KeyError(
f"RUN_OPTUNA=False and USE_EXISTING_BEST_PARAMS_WHEN_OPTUNA_OFF=False, but no manual hyperparameter "
f"JSON filename was found for strategy={strategy}, percent={percent_text(percent)} under key '{key}'. "
f"Required keys: {REQUIRED_HPARAM_KEYS}."
)
manual_filename = MANUAL_HPARAMS_IF_OPTUNA_OFF[key]
manual_path = (HARD_CODED_PARAM_DIR / manual_filename).resolve()
if not manual_path.exists():
raise FileNotFoundError(
f"RUN_OPTUNA=False and USE_EXISTING_BEST_PARAMS_WHEN_OPTUNA_OFF=False, but the manual hyperparameter "
f"JSON file for strategy={strategy}, percent={percent_text(percent)} was not found at {manual_path}. "
f"Configured key='{key}', filename='{manual_filename}'."
)
params = load_json(manual_path)
params = load_required_hparams(
params,
source=str(manual_path),
strategy=strategy,
percent=percent,
)
print(
f"[Optuna Off] Using manual hyperparameters for strategy={strategy}, "
f"percent={percent_text(percent)} from {manual_path}."
)
for name in REQUIRED_HPARAM_KEYS:
print(f" {name:20s}: {_format_hparam_value(name, params[name])}")
return params
def resolve_job_params(
strategy: int,
percent: float,
bundle: DataBundle,
*,
model_config: RuntimeModelConfig,
strategy2_checkpoint_path: str | Path | None = None,
) -> dict[str, Any]:
if RUN_OPTUNA:
banner(
f"OPTUNA STUDY | {run_identity_label(strategy=strategy, percent=percent, split_payload=bundle.split_payload)}"
)
return run_study(
strategy,
bundle,
model_config=model_config,
strategy2_checkpoint_path=strategy2_checkpoint_path,
)
if USE_EXISTING_BEST_PARAMS_WHEN_OPTUNA_OFF:
return load_saved_best_params_if_optuna_off(strategy, percent, model_config=model_config)
return load_manual_hparams_if_optuna_off(strategy, percent)
def read_run_config_for_eval(run_dir: Path, checkpoint_path: Path) -> dict[str, Any]:
run_config_path = Path(run_dir) / "run_config.json"
if run_config_path.exists():
return load_json(run_config_path)
ckpt = torch.load(checkpoint_path, map_location="cpu", weights_only=False)
return checkpoint_run_config_payload(ckpt)
def run_evaluation_for_run(
*,
strategy: int,
percent: float,
bundle: DataBundle,
run_dir: Path,
strategy2_checkpoint_path: str | Path | None = None,
) -> tuple[dict[str, dict[str, float]], list[dict[str, Any]]]:
checkpoint_path = resolve_checkpoint_path(
run_dir=run_dir,
selector_mode=EVAL_CHECKPOINT_MODE,
specific_checkpoint=EVAL_SPECIFIC_CHECKPOINT,
purpose="evaluation_checkpoint",
)
effective_run_dir = Path(run_dir)
if not (effective_run_dir / "run_config.json").exists() and checkpoint_path.parent.name == "checkpoints":
effective_run_dir = checkpoint_path.parent.parent
print(
f"[Evaluation] {run_identity_label(strategy=strategy, percent=percent, split_payload=bundle.split_payload)} "
f"| checkpoint={checkpoint_path}"
)
runtime_config = read_run_config_for_eval(effective_run_dir, checkpoint_path)
set_current_job_params(runtime_config)
model_config = RuntimeModelConfig.from_payload(runtime_config).validate()
if strategy in (4, 5):
if runtime_config.get("strategy2_checkpoint_path"):
strategy2_checkpoint_path = runtime_config["strategy2_checkpoint_path"]
else:
strategy2_checkpoint_path = resolve_strategy2_checkpoint_path(strategy, percent, model_config)
elif strategy == 3 and runtime_config.get("strategy2_checkpoint_path"):
strategy2_checkpoint_path = runtime_config["strategy2_checkpoint_path"]
dropout_p = float(runtime_config.get("dropout_p", DEFAULT_DROPOUT_P))
tmax = int(runtime_config.get("tmax", DEFAULT_TMAX))
eval_model, _description, _compiled = build_model(
strategy,
dropout_p,
model_config=model_config,
strategy2_checkpoint_path=strategy2_checkpoint_path,
)
checkpoint_payload = load_checkpoint(
checkpoint_path,
model=eval_model,
device=DEVICE,
)
best_metric_name = str(
checkpoint_payload.get("best_metric_name")
or runtime_config.get("best_checkpoint_metric_name")
or _strategy_selection_metric_name(strategy)
)
aggregate, per_sample = evaluate_model(
model=eval_model,
model_config=model_config,
bundle=bundle,
run_dir=effective_run_dir,
strategy=strategy,
tmax=tmax,
best_metric_name=best_metric_name,
)
evaluation_json_path = effective_run_dir / "evaluation.json"
evaluation_payload = load_json(evaluation_json_path)
evaluation_payload["checkpoint_mode"] = EVAL_CHECKPOINT_MODE
evaluation_payload["checkpoint_path"] = str(checkpoint_path)
evaluation_payload["best_metric_name"] = best_metric_name
if checkpoint_payload.get("best_metric_value") is not None:
evaluation_payload["best_metric_value"] = float(checkpoint_payload["best_metric_value"])
save_json(evaluation_json_path, evaluation_payload)
del eval_model
run_cuda_cleanup(
context=f"evaluation {run_identity_label(strategy=strategy, percent=percent, split_payload=bundle.split_payload)}"
)
return aggregate, per_sample
def run_smoke_test(
*,
strategy: int,
model_config: RuntimeModelConfig,
bundle: DataBundle,
smoke_root: Path,
strategy2_checkpoint_path: str | Path | None = None,
) -> None:
banner(
f"PRE-TRAINING SMOKE TEST | {run_identity_label(strategy=strategy, percent=bundle.percent, split_payload=bundle.split_payload)}"
)
smoke_root = ensure_dir(smoke_root)
if RUN_OPTUNA:
set_current_job_params()
elif USE_EXISTING_BEST_PARAMS_WHEN_OPTUNA_OFF:
set_current_job_params(
load_saved_best_params_if_optuna_off(strategy, bundle.percent, model_config=model_config)
)
else:
set_current_job_params(load_manual_hparams_if_optuna_off(strategy, bundle.percent))
sample = bundle.test_ds[SMOKE_TEST_SAMPLE_INDEX]
image = sample["image"].unsqueeze(0).to(DEVICE)
raw_image = sample["image"].numpy()
raw_gt = sample["mask"].squeeze(0).numpy()
amp_dtype = resolve_amp_dtype(AMP_DTYPE)
use_amp = amp_autocast_enabled(DEVICE)
if use_amp and DEVICE.type == "cuda":
image = image.to(dtype=amp_dtype)
model, description, compiled = build_model(
strategy,
DEFAULT_DROPOUT_P,
model_config=model_config,
strategy2_checkpoint_path=strategy2_checkpoint_path,
)
_configure_mc_dropout_from_params(model)
print_model_parameter_summary(
model=model,
description=f"{description} | Smoke Test",
strategy=strategy,
model_config=model_config,
dropout_p=DEFAULT_DROPOUT_P,
amp_dtype=amp_dtype,
compiled=compiled,
)
pred = infer_segmentation_mask(
model,
image,
DEFAULT_TMAX,
strategy=strategy,
use_amp=use_amp,
amp_dtype=amp_dtype,
use_channels_last=_use_channels_last_for_run(model_config),
).float()
pred_np = pred[0, 0].detach().cpu().numpy()
panel_path = smoke_root / "smoke_panel.png"
raw_mask_path = smoke_root / "smoke_prediction.png"
_save_rgb_panel(
raw_image,
pred_np,
raw_gt,
panel_path,
f"Smoke Test | {run_identity_label(strategy=strategy, percent=bundle.percent, split_payload=bundle.split_payload)}",
)
PILImage.fromarray((pred_np * 255).astype(np.uint8)).save(raw_mask_path)
del model
run_cuda_cleanup(
context=f"smoke {run_identity_label(strategy=strategy, percent=bundle.percent, split_payload=bundle.split_payload)}"
)
print(
f"[Smoke Test] {run_identity_label(strategy=strategy, percent=bundle.percent, split_payload=bundle.split_payload)} passed. "
f"Saved panel to {panel_path.name} and mask to {raw_mask_path.name}."
)
"""=============================================================================
OVERFIT TEST
=============================================================================
"""
OVERFIT_HISTORY_KEYS = (
"dice",
"iou",
"loss",
"reward",
"actor_loss",
"critic_loss",
"ce_loss",
"dice_loss",
"entropy",
"grad_norm",
"action_dist",
"reward_pos_pct",
"pred_fg_pct",
"gt_fg_pct",
)
def empty_overfit_history() -> dict[str, list[Any]]:
return {key: [] for key in OVERFIT_HISTORY_KEYS}
def load_overfit_history_for_resume(history_path: Path, checkpoint_payload: dict[str, Any]) -> dict[str, list[Any]]:
history = empty_overfit_history()
checkpoint_epoch = int(checkpoint_payload.get("epoch", 0))
if history_path.exists():
payload = load_json(history_path)
if not isinstance(payload, dict):
raise RuntimeError(f"Expected dict history at {history_path}, found {type(payload).__name__}.")
for key in OVERFIT_HISTORY_KEYS:
values = payload.get(key, [])
if isinstance(values, list):
history[key] = list(values[:checkpoint_epoch])
return history
epoch_metrics = checkpoint_payload.get("epoch_metrics", {})
if isinstance(epoch_metrics, dict):
for key in OVERFIT_HISTORY_KEYS:
if key in epoch_metrics:
history[key].append(epoch_metrics[key])
return history
def _grad_diagnostics(model: nn.Module) -> dict[str, Any]:
raw = _unwrap_compiled(model)
groups: dict[str, list[float]] = {}
total_sq = 0.0
n_nan = 0
n_inf = 0
n_zero = 0
n_total_params = 0
for name, param in raw.named_parameters():
if not param.requires_grad:
continue
n_total_params += 1
if param.grad is None:
n_zero += 1
continue
grad_norm = float(param.grad.data.norm(2).item())
if math.isnan(grad_norm):
n_nan += 1
continue
if math.isinf(grad_norm):
n_inf += 1
continue
total_sq += grad_norm ** 2
group_name = name.split(".", 1)[0]
groups.setdefault(group_name, []).append(grad_norm)
group_stats: dict[str, dict[str, float | int]] = {}
for group_name, norms in groups.items():
group_stats[group_name] = {
"min": min(norms),
"max": max(norms),
"mean": sum(norms) / len(norms),
"count": len(norms),
}
return {
"global_norm": total_sq ** 0.5,
"groups": group_stats,
"n_nan": n_nan,
"n_inf": n_inf,
"n_zero_grad": n_zero,
"n_total": n_total_params,
}
def _param_diagnostics(model: nn.Module, prev_params: dict[str, torch.Tensor] | None = None) -> dict[str, dict[str, float]]:
raw = _unwrap_compiled(model)
info: dict[str, dict[str, list[float]]] = {}
for name, param in raw.named_parameters():
if not param.requires_grad:
continue
param_norm = float(param.data.norm(2).item())
group_name = name.split(".", 1)[0]
entry = info.setdefault(group_name, {"norms": [], "update_ratios": []})
entry["norms"].append(param_norm)
if prev_params is not None and name in prev_params:
delta = float((param.data - prev_params[name]).norm(2).item())
entry["update_ratios"].append(delta / max(param_norm, 1e-12))
summary: dict[str, dict[str, float]] = {}
for group_name, values in info.items():
norms = values["norms"]
ratios = values["update_ratios"]
summary[group_name] = {
"p_min": min(norms),
"p_max": max(norms),
"p_mean": sum(norms) / len(norms),
}
if ratios:
summary[group_name]["ur_min"] = min(ratios)
summary[group_name]["ur_max"] = max(ratios)
summary[group_name]["ur_mean"] = sum(ratios) / len(ratios)
return summary
def _snapshot_params(model: nn.Module) -> dict[str, torch.Tensor]:
raw = _unwrap_compiled(model)
return {
name: param.data.detach().clone()
for name, param in raw.named_parameters()
if param.requires_grad
}
def _action_distribution(
model: nn.Module,
image: torch.Tensor,
seg: torch.Tensor,
tmax: int,
use_amp: bool,
amp_dtype: torch.dtype,
*,
strategy: int | None = None,
) -> tuple[list[dict[int, float]], torch.Tensor]:
distributions: list[dict[int, float]] = []
refinement_context: dict[str, torch.Tensor] | None = None
if strategy in (3, 4) and _uses_refinement_runtime(model, strategy=strategy):
with autocast_ctx(enabled=use_amp, device=image.device, amp_dtype=amp_dtype):
refinement_context = model.prepare_refinement_context(image)
seg = seg.float()
for _step in range(tmax):
if refinement_context is not None:
with autocast_ctx(enabled=use_amp, device=image.device, amp_dtype=amp_dtype):
state, _ = model.forward_refinement_state(
refinement_context["base_features"],
seg,
refinement_context["decoder_prob"],
encoder_features=refinement_context.get("encoder_features"),
mc_uncertainty=refinement_context.get("mc_uncertainty"),
)
policy_logits, _ = model.forward_from_state(state)
actions, _, _ = sample_actions(policy_logits, stochastic=False)
seg = _strategy3_apply_rollout_step(seg, actions).to(dtype=seg.dtype)
else:
with autocast_ctx(enabled=use_amp, device=image.device, amp_dtype=amp_dtype):
masked = image * seg
policy_logits = model.forward_policy_only(masked)
actions, _, _ = sample_actions(policy_logits, stochastic=False)
seg = apply_actions(seg, actions, num_actions=policy_logits.shape[1]).to(dtype=seg.dtype)
total_pixels = max(actions.numel(), 1)
step_dist: dict[int, float] = {}
action_count = int(policy_logits.shape[1])
for action_idx in range(action_count):
step_dist[action_idx] = float((actions == action_idx).sum().item()) / total_pixels * 100.0
distributions.append(step_dist)
if refinement_context is not None:
return distributions, threshold_binary_mask(seg.float()).float()
return distributions, seg
def _numerical_health_check(outputs_dict: dict[str, Any], prefix: str = "") -> list[str]:
alerts: list[str] = []
for name, value in outputs_dict.items():
if value is None:
continue
if isinstance(value, (int, float)):
if math.isnan(value):
alerts.append(f"{prefix}{name} = NaN")
elif math.isinf(value):
alerts.append(f"{prefix}{name} = Inf")
continue
if torch.is_tensor(value):
if torch.isnan(value).any():
alerts.append(f"{prefix}{name} contains NaN")
if torch.isinf(value).any():
alerts.append(f"{prefix}{name} contains Inf")
return alerts
def _batch_binary_metrics(pred: torch.Tensor, gt: torch.Tensor) -> tuple[list[float], list[float]]:
pred_np = pred.detach().cpu().numpy().astype(np.uint8)
gt_np = gt.detach().cpu().numpy().astype(np.uint8)
dices: list[float] = []
ious: list[float] = []
for idx in range(pred_np.shape[0]):
metrics = compute_all_metrics(pred_np[idx], gt_np[idx])
dices.append(float(metrics["dice"]))
ious.append(float(metrics["iou"]))
return dices, ious
def diagnostic_path_for_run(run_dir: Path) -> Path:
return Path(run_dir) / "diagnostic.json"
def _summary_stats(values: list[float]) -> dict[str, float | int | None]:
if not values:
return {"count": 0, "mean": None, "std": None, "min": None, "max": None}
arr = np.asarray(values, dtype=np.float64)
return {
"count": int(arr.size),
"mean": float(arr.mean()),
"std": float(arr.std()),
"min": float(arr.min()),
"max": float(arr.max()),
}
def _tensor_stats(tensor: torch.Tensor | None) -> dict[str, Any] | None:
if tensor is None:
return None
data = tensor.detach().float()
flat = data.reshape(-1)
if flat.numel() == 0:
return {"shape": list(data.shape), "dtype": str(tensor.dtype), "numel": 0}
return {
"shape": list(data.shape),
"dtype": str(tensor.dtype),
"numel": int(flat.numel()),
"mean": float(flat.mean().item()),
"std": float(flat.std(unbiased=False).item()),
"min": float(flat.min().item()),
"max": float(flat.max().item()),
}
def _action_histogram(actions: torch.Tensor, action_count: int) -> dict[str, float]:
total_pixels = max(actions.numel(), 1)
return {
str(action_idx): float((actions == action_idx).sum().item()) / total_pixels * 100.0
for action_idx in range(action_count)
}
def _jsonable_action_distribution(distributions: list[dict[int, float]] | list[dict[str, float]]) -> list[dict[str, float]]:
jsonable: list[dict[str, float]] = []
for step_dist in distributions:
jsonable.append({str(key): float(value) for key, value in step_dist.items()})
return jsonable
def _average_action_distributions(
distributions_per_batch: list[list[dict[int, float]]],
steps: int,
) -> list[dict[str, float]]:
averaged: list[dict[str, float]] = []
if not distributions_per_batch:
return averaged
for step_idx in range(steps):
action_keys = sorted(
{
int(action_idx)
for batch_dist in distributions_per_batch
if step_idx < len(batch_dist)
for action_idx in batch_dist[step_idx].keys()
}
)
if not action_keys:
continue
step_summary: dict[str, float] = {}
for action_idx in action_keys:
values = [
float(batch_dist[step_idx][action_idx])
for batch_dist in distributions_per_batch
if step_idx < len(batch_dist) and action_idx in batch_dist[step_idx]
]
step_summary[str(action_idx)] = float(np.mean(values)) if values else 0.0
averaged.append(step_summary)
return averaged
def _trajectory_degradation_summary(step_trace: list[dict[str, Any]]) -> dict[str, Any]:
if not step_trace:
return {}
ious = [float(step.get("iou_mean", 0.0)) for step in step_trace]
dices = [float(step.get("dice_mean", 0.0)) for step in step_trace]
ts = [int(step.get("t", idx)) for idx, step in enumerate(step_trace)]
init_iou = ious[0]
init_dice = dices[0]
best_iou = max(ious)
best_dice = max(dices)
best_iou_t = ts[ious.index(best_iou)]
best_dice_t = ts[dices.index(best_dice)]
first_worse_than_initial_iou_t = next((ts[idx] for idx, value in enumerate(ious[1:], start=1) if value < init_iou - 1e-6), None)
first_worse_than_prev_iou_t = next((ts[idx] for idx in range(1, len(ious)) if ious[idx] < ious[idx - 1] - 1e-6), None)
largest_iou_drop = max(best_iou - value for value in ious)
largest_iou_drop_t = ts[max(range(len(ious)), key=lambda idx: best_iou - ious[idx])]
return {
"steps_recorded": len(step_trace) - 1,
"best_iou_t": best_iou_t,
"best_iou": best_iou,
"best_dice_t": best_dice_t,
"best_dice": best_dice,
"final_t": ts[-1],
"final_iou": ious[-1],
"final_dice": dices[-1],
"delta_final_vs_init_iou": ious[-1] - init_iou,
"delta_final_vs_init_dice": dices[-1] - init_dice,
"delta_final_vs_best_iou": ious[-1] - best_iou,
"delta_final_vs_best_dice": dices[-1] - best_dice,
"first_worse_than_initial_iou_t": first_worse_than_initial_iou_t,
"first_worse_than_prev_iou_t": first_worse_than_prev_iou_t,
"largest_iou_drop_from_best": largest_iou_drop,
"largest_iou_drop_t": largest_iou_drop_t,
}
def _average_rollout_traces(traces_per_batch: list[list[dict[str, Any]]]) -> list[dict[str, Any]]:
averaged: list[dict[str, Any]] = []
if not traces_per_batch:
return averaged
max_steps = max(len(trace) for trace in traces_per_batch)
for step_idx in range(max_steps):
present = [trace[step_idx] for trace in traces_per_batch if step_idx < len(trace)]
if not present:
continue
reward_pos_values = [float(step["reward_pos_pct"]) for step in present if step.get("reward_pos_pct") is not None]
value_scores = [float(step["value_score"]) for step in present if step.get("value_score") is not None]
averaged.append(
{
"t": int(np.mean([float(step.get("t", step_idx)) for step in present])),
"dice_mean": float(np.mean([float(step.get("dice_mean", 0.0)) for step in present])),
"iou_mean": float(np.mean([float(step.get("iou_mean", 0.0)) for step in present])),
"pred_fg_pct": float(np.mean([float(step.get("pred_fg_pct", 0.0)) for step in present])),
"reward_pos_pct": float(np.mean(reward_pos_values)) if reward_pos_values else None,
"value_score": float(np.mean(value_scores)) if value_scores else None,
}
)
return averaged
def _rollout_probe_trace(
model: nn.Module,
image: torch.Tensor,
gt_mask: torch.Tensor,
*,
strategy: int,
tmax: int,
use_amp: bool,
amp_dtype: torch.dtype,
use_channels_last: bool,
) -> dict[str, Any]:
rollout_trace: list[dict[str, Any]] = []
batch_action_dist: list[dict[int, float]] = []
reward_pos_pct = 0.0
init_fg_pct = 0.0
first_action_dist: dict[str, float] | None = None
first_policy_stats: dict[str, Any] | None = None
first_value_stats: dict[str, Any] | None = None
decoder_prob_stats: dict[str, Any] | None = None
first_entropy: float | None = None
selected_t = 0
def record_step(
*,
t: int,
seg_tensor: torch.Tensor,
seg_prev: torch.Tensor | None = None,
actions_taken: torch.Tensor | None = None,
value_score: float | None = None,
action_distribution: dict[str, float] | None = None,
reward_pos: float | None = None,
reward_map_tensor: torch.Tensor | None = None,
step_entropy: float | None = None,
policy_stats: dict[str, Any] | None = None,
num_act: int | None = None,
) -> None:
pred_t = threshold_binary_mask(seg_tensor.float()).float()
dice_vals, iou_vals = _batch_binary_metrics(pred_t, gt_mask.float())
step_data: dict[str, Any] = {
"t": int(t),
"dice_mean": float(np.mean(dice_vals)) if dice_vals else 0.0,
"iou_mean": float(np.mean(iou_vals)) if iou_vals else 0.0,
"pred_fg_pct": float(pred_t.sum().item()) / max(pred_t.numel(), 1) * 100.0,
"reward_pos_pct": None if reward_pos is None else float(reward_pos),
"value_score": None if value_score is None else float(value_score),
"action_distribution": action_distribution,
"seg_soft_stats": _tensor_stats(seg_tensor),
"entropy": step_entropy,
"policy_logit_stats": policy_stats,
}
if seg_prev is not None:
delta = seg_tensor.float() - seg_prev.float()
abs_delta = delta.abs()
# Binary mask flip tracking: how many pixels actually change in the thresholded output
binary_prev = threshold_binary_mask(seg_prev.float()).float()
binary_curr = threshold_binary_mask(seg_tensor.float()).float()
binary_flipped = (binary_prev != binary_curr)
flipped_to_fg = binary_flipped & (binary_curr > 0.5)
flipped_to_bg = binary_flipped & (binary_curr < 0.5)
gt_binary_local = (gt_mask.float() > 0.5)
correct_flips = binary_flipped & ((binary_curr > 0.5) == gt_binary_local)
wrong_flips = binary_flipped & ((binary_curr > 0.5) != gt_binary_local)
total_px = max(binary_prev.numel(), 1)
step_data["mask_delta"] = {
"mean_abs_change": float(abs_delta.mean().item()),
"max_change": float(abs_delta.max().item()),
"pct_pixels_changed": float((abs_delta > 1e-6).float().mean().item() * 100.0),
"fg_gained_pct": float((delta > 1e-6).float().mean().item() * 100.0),
"fg_lost_pct": float((delta < -1e-6).float().mean().item() * 100.0),
}
step_data["binary_mask_flips"] = {
"total_flipped_pct": float(binary_flipped.float().sum().item() / total_px * 100.0),
"flipped_to_fg_pct": float(flipped_to_fg.float().sum().item() / total_px * 100.0),
"flipped_to_bg_pct": float(flipped_to_bg.float().sum().item() / total_px * 100.0),
"correct_flips_pct": float(correct_flips.float().sum().item() / total_px * 100.0),
"wrong_flips_pct": float(wrong_flips.float().sum().item() / total_px * 100.0),
"flip_accuracy": float(correct_flips.float().sum().item() / max(binary_flipped.float().sum().item(), 1.0) * 100.0),
}
if reward_map_tensor is not None:
step_data["reward_stats"] = {
"mean": float(reward_map_tensor.mean().item()),
"std": float(reward_map_tensor.std().item()),
"min": float(reward_map_tensor.min().item()),
"max": float(reward_map_tensor.max().item()),
"pct_positive": float((reward_map_tensor > 0).float().mean().item() * 100.0),
"pct_negative": float((reward_map_tensor < 0).float().mean().item() * 100.0),
"pct_zero": float((reward_map_tensor.abs() < 1e-8).float().mean().item() * 100.0),
}
if actions_taken is not None and num_act is not None:
gt_f = gt_mask.float()
ref_pred = threshold_binary_mask(seg_prev.float()).float() if seg_prev is not None else pred_t
gt_fg = (gt_f > 0.5).squeeze(1)
gt_bg = ~gt_fg
pred_fg = (ref_pred > 0.5).squeeze(1)
tp_mask = pred_fg & gt_fg
tn_mask = (~pred_fg) & gt_bg
fp_mask = pred_fg & gt_bg
fn_mask = (~pred_fg) & gt_fg
acts = actions_taken
if acts.ndim == 4:
acts = acts.squeeze(1)
action_breakdown: dict[str, dict[str, float]] = {}
for label, pixel_mask in [("tp", tp_mask), ("tn", tn_mask), ("fp", fp_mask), ("fn", fn_mask)]:
total = pixel_mask.sum().item()
if total > 0:
dist: dict[str, float] = {}
for a in range(num_act):
count = ((acts == a) & pixel_mask).sum().item()
dist[str(a)] = round(count / total * 100.0, 2)
action_breakdown[label] = dist
else:
action_breakdown[label] = {str(a): 0.0 for a in range(num_act)}
step_data["action_on_class"] = action_breakdown
if reward_map_tensor is not None:
reward_squeezed = reward_map_tensor.squeeze(1) if reward_map_tensor.ndim == 4 else reward_map_tensor
per_action_reward: dict[str, float] = {}
for a in range(num_act):
a_mask = (acts == a)
if a_mask.any():
per_action_reward[str(a)] = float(reward_squeezed[a_mask].mean().item())
else:
per_action_reward[str(a)] = 0.0
step_data["per_action_reward"] = per_action_reward
rollout_trace.append(step_data)
if strategy == 2:
with autocast_ctx(enabled=use_amp, device=image.device, amp_dtype=amp_dtype):
logits = model(image)
pred = threshold_binary_mask(torch.sigmoid(logits)).float()
record_step(t=0, seg_tensor=torch.sigmoid(logits))
return {
"final_pred": pred,
"action_distribution": batch_action_dist,
"reward_pos_pct": reward_pos_pct,
"init_fg_pct": init_fg_pct,
"first_action_distribution": first_action_dist,
"first_policy_stats": first_policy_stats,
"first_value_stats": first_value_stats,
"decoder_prob_stats": decoder_prob_stats,
"first_entropy": first_entropy,
"rollout_trace": rollout_trace,
"rollout_summary": _trajectory_degradation_summary(rollout_trace),
"selected_t": selected_t,
}
refinement_runtime = _uses_refinement_runtime(model, strategy=strategy)
if strategy in (3, 4) and refinement_runtime:
with autocast_ctx(enabled=use_amp, device=image.device, amp_dtype=amp_dtype):
refinement_context = model.prepare_refinement_context(image)
seg = refinement_context["decoder_prob"].float()
decoder_prob_stats = _tensor_stats(refinement_context["decoder_prob"])
init_fg_pct = float(seg.sum().item()) / max(seg.numel(), 1) * 100.0
selected_t = 0
for step_idx in range(tmax):
with autocast_ctx(enabled=use_amp, device=image.device, amp_dtype=amp_dtype):
state_t, _ = model.forward_refinement_state(
refinement_context["base_features"],
seg,
refinement_context["decoder_prob"],
encoder_features=refinement_context.get("encoder_features"),
mc_uncertainty=refinement_context.get("mc_uncertainty"),
)
policy_logits, value_t = model.forward_from_state(state_t)
current_score = float(value_t.detach().mean().item())
actions, _, entropy = sample_actions(policy_logits, stochastic=False)
action_dist = _action_histogram(actions, int(policy_logits.shape[1]))
batch_action_dist.append({int(key): float(value) for key, value in action_dist.items()})
if step_idx == 0:
first_action_dist = action_dist
first_policy_stats = _tensor_stats(policy_logits)
first_value_stats = _tensor_stats(value_t)
first_entropy = float(entropy.detach().item())
record_step(t=0, seg_tensor=seg, value_score=current_score, step_entropy=first_entropy, policy_stats=first_policy_stats)
seg_next = _strategy3_apply_rollout_step(seg, actions)
reward_map = compute_refinement_reward(seg, seg_next, gt_mask.float())
step_reward_pos = float((reward_map > 0).float().mean().item() * 100.0)
step_entropy_val = float(entropy.detach().item())
if step_idx == 0:
reward_pos_pct = step_reward_pos
record_step(
t=step_idx + 1,
seg_tensor=seg_next,
seg_prev=seg,
actions_taken=actions,
action_distribution=action_dist,
reward_pos=step_reward_pos,
reward_map_tensor=reward_map,
step_entropy=step_entropy_val,
policy_stats=_tensor_stats(policy_logits),
num_act=int(policy_logits.shape[1]),
)
seg = seg_next
selected_t = step_idx + 1
pred = threshold_binary_mask(seg.float()).float()
decoder_pred = threshold_binary_mask(refinement_context["decoder_prob"].float()).float()
decoder_dice_vals, decoder_iou_vals = _batch_binary_metrics(decoder_pred, gt_mask.float())
decoder_baseline = {
"dice": float(np.mean(decoder_dice_vals)) if decoder_dice_vals else 0.0,
"iou": float(np.mean(decoder_iou_vals)) if decoder_iou_vals else 0.0,
"fg_pct": float(decoder_pred.sum().item()) / max(decoder_pred.numel(), 1) * 100.0,
}
final_dice_vals, final_iou_vals = _batch_binary_metrics(pred, gt_mask.float())
rl_vs_decoder = {
"decoder_dice": decoder_baseline["dice"],
"decoder_iou": decoder_baseline["iou"],
"final_dice": float(np.mean(final_dice_vals)) if final_dice_vals else 0.0,
"final_iou": float(np.mean(final_iou_vals)) if final_iou_vals else 0.0,
"dice_gain": (float(np.mean(final_dice_vals)) if final_dice_vals else 0.0) - decoder_baseline["dice"],
"iou_gain": (float(np.mean(final_iou_vals)) if final_iou_vals else 0.0) - decoder_baseline["iou"],
}
summary = _trajectory_degradation_summary(rollout_trace)
summary["selected_t"] = selected_t
return {
"final_pred": pred,
"action_distribution": batch_action_dist,
"reward_pos_pct": reward_pos_pct,
"init_fg_pct": init_fg_pct,
"first_action_distribution": first_action_dist,
"first_policy_stats": first_policy_stats,
"first_value_stats": first_value_stats,
"decoder_prob_stats": decoder_prob_stats,
"first_entropy": first_entropy,
"rollout_trace": rollout_trace,
"rollout_summary": summary,
"selected_t": selected_t,
"decoder_baseline": decoder_baseline,
"rl_vs_decoder": rl_vs_decoder,
}
if strategy in (3, 4):
with autocast_ctx(enabled=use_amp, device=image.device, amp_dtype=amp_dtype):
seg = threshold_binary_mask(torch.sigmoid(model.forward_decoder(image))).float()
else:
seg = torch.ones(image.shape[0], 1, image.shape[2], image.shape[3], device=image.device, dtype=image.dtype)
init_fg_pct = float(seg.sum().item()) / max(seg.numel(), 1) * 100.0
record_step(t=0, seg_tensor=seg)
for step_idx in range(tmax):
with autocast_ctx(enabled=use_amp, device=image.device, amp_dtype=amp_dtype):
masked = image * seg
policy_logits = model.forward_policy_only(masked)
actions, _, entropy = sample_actions(policy_logits, stochastic=False)
action_dist = _action_histogram(actions, int(policy_logits.shape[1]))
batch_action_dist.append({int(key): float(value) for key, value in action_dist.items()})
if step_idx == 0:
first_action_dist = action_dist
first_policy_stats = _tensor_stats(policy_logits)
first_entropy = float(entropy.detach().item())
seg_next = apply_actions(seg, actions, num_actions=policy_logits.shape[1]).to(dtype=seg.dtype)
reward_map = (seg - gt_mask).pow(2) - (seg_next - gt_mask).pow(2)
step_reward_pos = float((reward_map > 0).float().mean().item() * 100.0)
if step_idx == 0:
reward_pos_pct = step_reward_pos
record_step(
t=step_idx + 1,
seg_tensor=seg_next,
action_distribution=action_dist,
reward_pos=step_reward_pos,
)
seg = seg_next
pred = seg.float()
summary = _trajectory_degradation_summary(rollout_trace)
summary["selected_t"] = len(rollout_trace) - 1
return {
"final_pred": pred,
"action_distribution": batch_action_dist,
"reward_pos_pct": reward_pos_pct,
"init_fg_pct": init_fg_pct,
"first_action_distribution": first_action_dist,
"first_policy_stats": first_policy_stats,
"first_value_stats": first_value_stats,
"decoder_prob_stats": decoder_prob_stats,
"first_entropy": first_entropy,
"rollout_trace": rollout_trace,
"rollout_summary": summary,
"selected_t": len(rollout_trace) - 1,
}
def _format_probe_deterioration(label: str, probe_payload: dict[str, Any], tmax: int) -> str:
degradation = probe_payload.get("aggregate", {}).get("degradation", {})
if not degradation:
return f"{label}: no degradation trace"
first_worse = degradation.get("first_worse_than_initial_iou_t")
first_step_drop = degradation.get("first_worse_than_prev_iou_t")
best_t = degradation.get("best_iou_t")
final_t = degradation.get("final_t")
delta_best = degradation.get("delta_final_vs_best_iou")
worst_t = degradation.get("largest_iou_drop_t")
worst_drop = degradation.get("largest_iou_drop_from_best")
return (
f"{label}: first_worse={first_worse}/{tmax} "
f"first_drop={first_step_drop}/{tmax} "
f"best={best_t}/{tmax} final={final_t}/{tmax} "
f"final-best_iou={float(delta_best):+.4f} "
f"worst={worst_t}/{tmax} drop={float(worst_drop):+.4f}"
)
def _optimizer_diagnostics(optimizer: torch.optim.Optimizer) -> list[dict[str, Any]]:
groups: list[dict[str, Any]] = []
for group_idx, group in enumerate(optimizer.param_groups):
num_tensors = len(group.get("params", []))
num_elements = int(sum(param.numel() for param in group.get("params", [])))
groups.append(
{
"index": group_idx,
"lr": float(group.get("lr", 0.0)),
"weight_decay": float(group.get("weight_decay", 0.0)),
"num_tensors": num_tensors,
"num_elements": num_elements,
}
)
return groups
def _fixed_probe_batches_from_dataset(
dataset: BUSIDataset,
*,
num_batches: int,
device: torch.device,
) -> list[dict[str, Any]]:
fixed_batches: list[dict[str, Any]] = []
max_samples = min(len(dataset), max(int(num_batches), 0) * BATCH_SIZE)
for start in range(0, max_samples, BATCH_SIZE):
end = min(start + BATCH_SIZE, max_samples)
images = torch.stack([dataset._images[idx].clone() for idx in range(start, end)], dim=0)
masks = torch.stack([dataset._masks[idx].clone() for idx in range(start, end)], dim=0)
sample_ids = [Path(dataset.sample_records[idx]["filename"]).stem for idx in range(start, end)]
fixed_batches.append(
to_device(
{
"image": images,
"mask": masks,
"sample_id": sample_ids,
"dataset": current_dataset_name(),
},
device,
)
)
return fixed_batches
def _probe_batch_id_lists(fixed_batches: list[dict[str, Any]]) -> list[list[str]]:
return [list(batch.get("sample_id", [])) for batch in fixed_batches]
def _reference_eval_payloads(project_dir: Path, percent: float) -> dict[str, Any]:
refs: dict[str, Any] = {}
pct = percent_label(percent)
strat2_dir = project_dir / "strat2_history"
strat3_dir = project_dir / "strat3_history_best"
strat2_candidates = [
strat2_dir / f"evaluation_strat2_pc{pct}.json",
strat2_dir / f"evaluation_strat2_pct{pct}.json",
]
strat3_candidate = strat3_dir / f"evaluation_{pct} (1)"
for candidate in strat2_candidates:
if candidate.exists():
refs["strategy2_reference"] = load_json(candidate)
break
if strat3_candidate.exists():
refs["strategy3_best_reference"] = load_json(strat3_candidate)
return refs
def empty_epoch_diagnostic_payload(
*,
run_type: str,
run_config: dict[str, Any],
bundle: DataBundle,
train_probe_batches: list[dict[str, Any]],
val_probe_batches: list[dict[str, Any]],
) -> dict[str, Any]:
payload = {
"diagnostic_version": 1,
"run_type": run_type,
"strategy": int(run_config["strategy"]),
"dataset_percent": float(bundle.percent),
"run_config": run_config,
"probe_setup": {
"train_probe_batches": _probe_batch_id_lists(train_probe_batches),
"val_probe_batches": _probe_batch_id_lists(val_probe_batches),
"train_probe_batch_count": len(train_probe_batches),
"val_probe_batch_count": len(val_probe_batches),
"tmax": int(run_config.get("tmax", DEFAULT_TMAX)),
},
"epochs": [],
}
payload.update(_reference_eval_payloads(PROJECT_DIR, bundle.percent))
return payload
def load_epoch_diagnostic_for_resume(
path: Path,
checkpoint_payload: dict[str, Any] | None,
default_payload: dict[str, Any],
) -> dict[str, Any]:
payload = dict(default_payload)
checkpoint_epoch = int(checkpoint_payload.get("epoch", 0)) if checkpoint_payload is not None else 0
if path.exists():
loaded = load_json(path)
if isinstance(loaded, dict):
payload.update({k: v for k, v in loaded.items() if k != "epochs"})
epochs = loaded.get("epochs", [])
if isinstance(epochs, list):
payload["epochs"] = [dict(row) for row in epochs if isinstance(row, dict) and int(row.get("epoch", 0)) <= checkpoint_epoch]
if "epochs" not in payload:
payload["epochs"] = []
return payload
def _evaluate_probe_batches(
model: nn.Module,
fixed_batches: list[dict[str, Any]],
*,
strategy: int,
tmax: int,
use_amp: bool,
amp_dtype: torch.dtype,
use_channels_last: bool,
) -> dict[str, Any]:
if not fixed_batches:
return {"n_batches": 0, "batch_details": [], "aggregate": {}, "alerts": []}
was_training = model.training
batch_details: list[dict[str, Any]] = []
alerts: list[str] = []
action_distributions: list[list[dict[int, float]]] = []
rollout_traces: list[list[dict[str, Any]]] = []
metric_lists: dict[str, list[float]] = {key: [] for key in ("dice", "ppv", "sen", "iou", "biou", "hd95")}
reward_pos_values: list[float] = []
pred_fg_values: list[float] = []
gt_fg_values: list[float] = []
init_fg_values: list[float] = []
decoder_dices: list[float] = []
decoder_ious: list[float] = []
iou_gains: list[float] = []
dice_gains: list[float] = []
model.eval()
try:
with torch.inference_mode():
for batch_index, batch in enumerate(fixed_batches):
image = batch["image"]
gt_mask = batch["mask"].float()
sample_ids = [str(item) for item in batch.get("sample_id", [])]
if use_channels_last and image.ndim == 4 and image.device.type == "cuda":
image = image.contiguous(memory_format=torch.channels_last)
if use_amp and image.device.type == "cuda":
image = image.to(dtype=amp_dtype)
rollout_probe = _rollout_probe_trace(
model,
image,
gt_mask,
strategy=strategy,
tmax=tmax,
use_amp=use_amp,
amp_dtype=amp_dtype,
use_channels_last=use_channels_last,
)
pred = rollout_probe["final_pred"].float()
batch_action_dist = rollout_probe["action_distribution"]
reward_pos_pct = float(rollout_probe["reward_pos_pct"])
init_fg_pct = float(rollout_probe["init_fg_pct"])
first_action_dist = rollout_probe["first_action_distribution"]
first_policy_stats = rollout_probe["first_policy_stats"]
first_value_stats = rollout_probe["first_value_stats"]
decoder_prob_stats = rollout_probe["decoder_prob_stats"]
first_entropy = rollout_probe["first_entropy"]
rollout_trace = rollout_probe["rollout_trace"]
rollout_summary = rollout_probe["rollout_summary"]
if batch_action_dist:
action_distributions.append(batch_action_dist)
if rollout_trace:
rollout_traces.append(rollout_trace)
pred_fg_pct = float(pred.sum().item()) / max(pred.numel(), 1) * 100.0
gt_fg_pct = float(gt_mask.sum().item()) / max(gt_mask.numel(), 1) * 100.0
reward_pos_values.append(reward_pos_pct)
pred_fg_values.append(pred_fg_pct)
gt_fg_values.append(gt_fg_pct)
init_fg_values.append(init_fg_pct)
rl_vs_dec = rollout_probe.get("rl_vs_decoder")
if rl_vs_dec:
decoder_dices.append(rl_vs_dec["decoder_dice"])
decoder_ious.append(rl_vs_dec["decoder_iou"])
iou_gains.append(rl_vs_dec["iou_gain"])
dice_gains.append(rl_vs_dec["dice_gain"])
batch_alerts = _numerical_health_check(
{
"pred": pred,
"gt_mask": gt_mask,
"pred_fg_pct": pred_fg_pct,
"gt_fg_pct": gt_fg_pct,
"reward_pos_pct": reward_pos_pct,
"first_entropy": first_entropy if first_entropy is not None else 0.0,
},
prefix=f"probe[{batch_index}]:",
)
alerts.extend(batch_alerts)
pred_np = pred.detach().cpu().numpy().astype(np.uint8)
gt_np = gt_mask.detach().cpu().numpy().astype(np.uint8)
per_sample: list[dict[str, Any]] = []
for sample_index in range(pred_np.shape[0]):
metrics = compute_all_metrics(pred_np[sample_index], gt_np[sample_index])
per_sample.append(
{
"sample_id": sample_ids[sample_index] if sample_index < len(sample_ids) else f"sample_{sample_index}",
**{key: float(value) for key, value in metrics.items()},
}
)
for key, value in metrics.items():
metric_lists[key].append(float(value))
batch_details.append(
{
"batch_index": batch_index,
"sample_ids": sample_ids,
"pred_fg_pct": pred_fg_pct,
"gt_fg_pct": gt_fg_pct,
"init_fg_pct": init_fg_pct,
"reward_pos_pct": reward_pos_pct,
"action_distribution": _jsonable_action_distribution(batch_action_dist),
"first_action_distribution": first_action_dist,
"first_entropy": first_entropy,
"decoder_prob_stats": decoder_prob_stats,
"first_policy_stats": first_policy_stats,
"first_value_stats": first_value_stats,
"pred_stats": _tensor_stats(pred),
"rollout_trace": rollout_trace,
"rollout_summary": rollout_summary,
"decoder_baseline": rollout_probe.get("decoder_baseline"),
"rl_vs_decoder": rollout_probe.get("rl_vs_decoder"),
"alerts": batch_alerts,
"per_sample": per_sample,
}
)
finally:
model.train(was_training)
aggregate_trace = _average_rollout_traces(rollout_traces)
rl_vs_decoder_aggregate: dict[str, Any] = {}
if decoder_dices:
rl_vs_decoder_aggregate = {
"decoder_dice": _summary_stats(decoder_dices),
"decoder_iou": _summary_stats(decoder_ious),
"iou_gain": _summary_stats(iou_gains),
"dice_gain": _summary_stats(dice_gains),
}
return {
"n_batches": len(fixed_batches),
"batch_details": batch_details,
"aggregate": {
"metrics": {key: _summary_stats(values) for key, values in metric_lists.items()},
"reward_pos_pct": _summary_stats(reward_pos_values),
"pred_fg_pct": _summary_stats(pred_fg_values),
"gt_fg_pct": _summary_stats(gt_fg_values),
"init_fg_pct": _summary_stats(init_fg_values),
"action_distribution": _average_action_distributions(action_distributions, tmax),
"rollout_trace": aggregate_trace,
"degradation": _trajectory_degradation_summary(aggregate_trace),
"rl_vs_decoder": rl_vs_decoder_aggregate,
},
"alerts": alerts,
}
def run_overfit_test(
*,
strategy: int,
model_config: RuntimeModelConfig,
bundle: DataBundle,
overfit_root: Path,
strategy2_checkpoint_path: str | Path | None = None,
) -> dict[str, Any]:
amp_dtype = resolve_amp_dtype(AMP_DTYPE)
use_amp = amp_autocast_enabled(DEVICE)
use_channels_last = _use_channels_last_for_run(model_config)
overfit_root = ensure_dir(overfit_root)
ckpt_dir = ensure_dir(overfit_root / "checkpoints")
history_path = checkpoint_history_path(overfit_root, "overfit")
run_config = {
"project_dir": str(PROJECT_DIR),
"data_root": str(DATA_ROOT),
"run_type": "overfit",
"strategy": strategy,
"dataset_percent": bundle.percent,
"dataset_name": bundle.split_payload["dataset_name"],
"dataset_split_policy": bundle.split_payload["dataset_split_policy"],
"dataset_splits_path": bundle.split_payload["dataset_splits_path"],
"split_type": bundle.split_payload["split_type"],
"train_subset_key": bundle.split_payload["train_subset_key"],
"max_epochs": OVERFIT_N_EPOCHS,
"head_lr": OVERFIT_HEAD_LR,
"encoder_lr": OVERFIT_ENCODER_LR,
"weight_decay": DEFAULT_WEIGHT_DECAY,
"dropout_p": DEFAULT_DROPOUT_P,
"tmax": DEFAULT_TMAX,
"entropy_lr": DEFAULT_ENTROPY_LR,
"gamma": DEFAULT_GAMMA,
"grad_clip_norm": DEFAULT_GRAD_CLIP_NORM,
"train_resume_mode": TRAIN_RESUME_MODE,
"train_resume_specific_checkpoint": TRAIN_RESUME_SPECIFIC_CHECKPOINT,
}
if strategy == 3:
run_config.setdefault(
"strategy3_freeze_bootstrapped_segmentation",
DEFAULT_STRATEGY3_FREEZE_BOOTSTRAPPED_SEGMENTATION,
)
bootstrap_freeze = (
strategy2_checkpoint_path is not None
and bool(run_config["strategy3_freeze_bootstrapped_segmentation"])
)
run_config.setdefault("num_actions", 5)
run_config.setdefault("strategy3_action_mode", "delta")
run_config.setdefault("decoder_lr", 0.0 if bootstrap_freeze else OVERFIT_HEAD_LR * 0.1)
run_config.setdefault("rl_lr", OVERFIT_HEAD_LR)
run_config.setdefault("strategy3_decoder_ce_weight", 0.0 if bootstrap_freeze else DEFAULT_CE_WEIGHT)
run_config.setdefault("strategy3_decoder_dice_weight", 0.0 if bootstrap_freeze else DEFAULT_DICE_WEIGHT)
run_config.setdefault("gae_lambda", 0.95)
run_config.setdefault("a3c_entropy_coeff", 0.01)
run_config.setdefault("asymmetric_reward_alpha", 1.0)
run_config.setdefault("boundary_reward_weight", 0.0)
run_config.setdefault("binary_reward_weight", 0.7)
run_config.setdefault("reward_boundary_focus", 0.8)
run_config.setdefault("reward_inaction_cost", 0.05)
run_config.setdefault("gt_error_dropout", 0.40)
run_config.setdefault("mc_dropout_p", 0.3)
run_config.setdefault("mc_n_passes", 5)
run_config.setdefault("strategy3_rl_grad_clip_norm", 1.0)
run_config.setdefault("early_stopping_monitor", DEFAULT_EARLY_STOPPING_MONITOR)
run_config.setdefault("early_stopping_mode", DEFAULT_EARLY_STOPPING_MODE)
run_config.setdefault("early_stopping_min_delta", DEFAULT_EARLY_STOPPING_MIN_DELTA)
run_config.setdefault("early_stopping_start_epoch", DEFAULT_EARLY_STOPPING_START_EPOCH)
run_config.setdefault("early_stopping_patience", EARLY_STOPPING_PATIENCE)
run_config.update(model_config.to_payload())
if strategy2_checkpoint_path is not None:
run_config["strategy2_checkpoint_path"] = str(Path(strategy2_checkpoint_path))
save_json(overfit_root / "run_config.json", run_config)
set_current_job_params(run_config)
banner(
f"OVERFIT TEST | {run_identity_label(strategy=strategy, percent=bundle.percent, split_payload=bundle.split_payload)}"
)
print(
f"[Overfit] Fixed batches={OVERFIT_N_BATCHES}, epochs={OVERFIT_N_EPOCHS}, "
f"head_lr={OVERFIT_HEAD_LR:.2e}, encoder_lr={OVERFIT_ENCODER_LR:.2e}"
)
fixed_batches: list[dict[str, Any]] = []
for batch_index, batch in enumerate(bundle.train_loader):
fixed_batches.append(to_device(batch, DEVICE))
if batch_index + 1 >= OVERFIT_N_BATCHES:
break
if not fixed_batches:
raise RuntimeError("Overfit test could not collect any training batches.")
if len(fixed_batches) < OVERFIT_N_BATCHES:
print(f"[Overfit] Warning: only {len(fixed_batches)} train batch(es) available.")
model, description, compiled = build_model(
strategy,
DEFAULT_DROPOUT_P,
model_config=model_config,
strategy2_checkpoint_path=strategy2_checkpoint_path,
)
resume_checkpoint_path = resolve_train_resume_checkpoint_path(overfit_root)
if resume_checkpoint_path is not None and strategy in (3, 4):
_configure_model_from_checkpoint_path(model, resume_checkpoint_path)
_configure_mc_dropout_from_params(model)
print_model_parameter_summary(
model=model,
description=f"{description} | Overfit Test",
strategy=strategy,
model_config=model_config,
dropout_p=DEFAULT_DROPOUT_P,
amp_dtype=amp_dtype,
compiled=compiled,
)
optimizer = make_optimizer(
model,
strategy,
head_lr=OVERFIT_HEAD_LR,
encoder_lr=OVERFIT_ENCODER_LR,
weight_decay=DEFAULT_WEIGHT_DECAY,
)
scaler = make_grad_scaler(enabled=use_amp, amp_dtype=amp_dtype, device=DEVICE)
log_alpha: torch.Tensor | None = None
alpha_optimizer: Adam | None = None
target_entropy = DEFAULT_ENTROPY_TARGET_RATIO * math.log(max(_model_policy_action_count(model) or NUM_ACTIONS, 2))
if strategy != 2:
log_alpha = torch.tensor(
math.log(max(DEFAULT_ENTROPY_ALPHA_INIT, 1e-8)),
dtype=torch.float32,
device=DEVICE,
requires_grad=True,
)
alpha_optimizer = Adam([log_alpha], lr=DEFAULT_ENTROPY_LR)
history = empty_overfit_history()
prev_loss: float | None = None
best_dice = -1.0
elapsed_before_resume = 0.0
start_epoch = 1
resume_source: dict[str, Any] | None = None
if resume_checkpoint_path is not None:
checkpoint_payload = load_checkpoint(
resume_checkpoint_path,
model=model,
optimizer=optimizer,
scheduler=None,
scaler=scaler,
device=DEVICE,
log_alpha=log_alpha,
alpha_optimizer=alpha_optimizer,
expected_run_type="overfit",
require_run_metadata=True,
)
validate_resume_checkpoint_identity(
run_config,
checkpoint_run_config_payload(checkpoint_payload),
checkpoint_path=resume_checkpoint_path,
)
start_epoch = int(checkpoint_payload["epoch"]) + 1
best_dice = float(checkpoint_payload["best_metric_value"])
elapsed_before_resume = float(checkpoint_payload.get("elapsed_seconds", 0.0))
history = load_overfit_history_for_resume(history_path, checkpoint_payload)
resume_source = {
"checkpoint_path": str(Path(resume_checkpoint_path).resolve()),
"checkpoint_epoch": int(checkpoint_payload["epoch"]),
"checkpoint_run_type": checkpoint_payload.get("run_type", "overfit"),
}
print(
f"[Resume] overfit run continuing from {resume_checkpoint_path} "
f"at epoch {start_epoch}/{OVERFIT_N_EPOCHS}."
)
if history["loss"]:
prev_loss = float(history["loss"][-1])
prev_params = _snapshot_params(model)
start_time = time.time()
for epoch in range(start_epoch, OVERFIT_N_EPOCHS + 1):
full_dump = epoch <= 5 or epoch % max(OVERFIT_PRINT_EVERY, 1) == 0 or epoch == OVERFIT_N_EPOCHS
epoch_losses: list[float] = []
epoch_dices: list[float] = []
epoch_ious: list[float] = []
epoch_rewards: list[float] = []
epoch_actor: list[float] = []
epoch_critic: list[float] = []
epoch_ce: list[float] = []
epoch_dice_losses: list[float] = []
epoch_entropy: list[float] = []
epoch_grad_norms: list[float] = []
epoch_action_dist: list[list[dict[int, float]]] = []
epoch_reward_pos_pct: list[float] = []
epoch_pred_fg_pct: list[float] = []
epoch_gt_fg_pct: list[float] = []
epoch_alerts: list[str] = []
for batch in fixed_batches:
if strategy == 2:
metrics = train_step_supervised(
model,
batch,
optimizer,
scaler=scaler,
use_amp=use_amp,
amp_dtype=amp_dtype,
use_channels_last=use_channels_last,
grad_clip_norm=DEFAULT_GRAD_CLIP_NORM,
ce_weight=DEFAULT_CE_WEIGHT,
dice_weight=DEFAULT_DICE_WEIGHT,
)
elif strategy in (3, 4):
assert log_alpha is not None and alpha_optimizer is not None
metrics = train_step_strategy3(
model,
batch,
optimizer,
gamma=DEFAULT_GAMMA,
tmax=DEFAULT_TMAX,
critic_loss_weight=DEFAULT_CRITIC_LOSS_WEIGHT,
log_alpha=log_alpha,
alpha_optimizer=alpha_optimizer,
target_entropy=target_entropy,
ce_weight=DEFAULT_CE_WEIGHT,
dice_weight=DEFAULT_DICE_WEIGHT,
grad_clip_norm=DEFAULT_GRAD_CLIP_NORM,
scaler=scaler,
use_amp=use_amp,
amp_dtype=amp_dtype,
stepwise_backward=STEPWISE_BACKWARD,
use_channels_last=use_channels_last,
current_epoch=epoch,
max_epochs=OVERFIT_N_EPOCHS,
)
else:
assert log_alpha is not None and alpha_optimizer is not None
metrics = train_step(
model,
batch,
optimizer,
gamma=DEFAULT_GAMMA,
tmax=DEFAULT_TMAX,
critic_loss_weight=DEFAULT_CRITIC_LOSS_WEIGHT,
log_alpha=log_alpha,
alpha_optimizer=alpha_optimizer,
target_entropy=target_entropy,
ce_weight=DEFAULT_CE_WEIGHT,
dice_weight=DEFAULT_DICE_WEIGHT,
grad_clip_norm=DEFAULT_GRAD_CLIP_NORM,
scaler=scaler,
use_amp=use_amp,
amp_dtype=amp_dtype,
stepwise_backward=STEPWISE_BACKWARD,
use_channels_last=use_channels_last,
)
epoch_losses.append(float(metrics["loss"]))
epoch_rewards.append(float(metrics["mean_reward"]))
epoch_actor.append(float(metrics["actor_loss"]))
epoch_critic.append(float(metrics["critic_loss"]))
epoch_ce.append(float(metrics["ce_loss"]))
epoch_dice_losses.append(float(metrics["dice_loss"]))
epoch_entropy.append(float(metrics["entropy"]))
epoch_grad_norms.append(float(metrics["grad_norm"]))
epoch_alerts.extend(
_numerical_health_check(
{
"loss": metrics["loss"],
"actor_loss": metrics["actor_loss"],
"critic_loss": metrics["critic_loss"],
"reward": metrics["mean_reward"],
"entropy": metrics["entropy"],
"grad_norm": metrics["grad_norm"],
"ce_loss": metrics["ce_loss"],
"dice_loss": metrics["dice_loss"],
},
prefix="train:",
)
)
model.eval()
with torch.inference_mode():
image = batch["image"]
gt_mask = batch["mask"].float()
if use_channels_last and image.ndim == 4 and image.device.type == "cuda":
image = image.contiguous(memory_format=torch.channels_last)
if use_amp and DEVICE.type == "cuda":
image = image.to(dtype=amp_dtype)
if strategy == 2:
with autocast_ctx(enabled=use_amp, device=image.device, amp_dtype=amp_dtype):
logits = model(image)
pred = threshold_binary_mask(torch.sigmoid(logits)).float()
else:
refinement_runtime = _uses_refinement_runtime(model, strategy=strategy)
if strategy in (3, 4) and refinement_runtime:
with autocast_ctx(enabled=use_amp, device=image.device, amp_dtype=amp_dtype):
init_mask = model.prepare_refinement_context(image)["decoder_prob"].float()
else:
init_mask = torch.ones(
image.shape[0],
1,
image.shape[2],
image.shape[3],
device=image.device,
dtype=image.dtype,
)
if strategy in (3, 4):
with autocast_ctx(enabled=use_amp, device=image.device, amp_dtype=amp_dtype):
init_mask = threshold_binary_mask(torch.sigmoid(model.forward_decoder(image))).float()
action_dist, pred = _action_distribution(
model,
image,
init_mask,
DEFAULT_TMAX,
use_amp,
amp_dtype,
strategy=strategy,
)
epoch_action_dist.append(action_dist)
if strategy in (3, 4) and refinement_runtime:
with autocast_ctx(enabled=use_amp, device=image.device, amp_dtype=amp_dtype):
refinement_context = model.prepare_refinement_context(image)
soft_init_mask = refinement_context["decoder_prob"].float()
state_t, _ = model.forward_refinement_state(
refinement_context["base_features"],
soft_init_mask,
refinement_context["decoder_prob"],
encoder_features=refinement_context.get("encoder_features"),
mc_uncertainty=refinement_context.get("mc_uncertainty"),
)
policy_logits, _ = model.forward_from_state(state_t)
first_actions, _, _ = sample_actions(policy_logits, stochastic=False)
first_seg = _strategy3_apply_rollout_step(soft_init_mask, first_actions)
reward_map = compute_refinement_reward(
soft_init_mask, first_seg, gt_mask.float(),
)
else:
with autocast_ctx(enabled=use_amp, device=image.device, amp_dtype=amp_dtype):
masked = image * init_mask
policy_logits = model.forward_policy_only(masked)
first_actions, _, _ = sample_actions(policy_logits, stochastic=False)
first_seg = apply_actions(init_mask, first_actions, num_actions=policy_logits.shape[1])
reward_map = (init_mask - gt_mask).pow(2) - (first_seg - gt_mask).pow(2)
epoch_reward_pos_pct.append(float((reward_map > 0).float().mean().item() * 100.0))
pred_fg_pct = float(pred.sum().item()) / max(pred.numel(), 1) * 100.0
gt_fg_pct = float(gt_mask.sum().item()) / max(gt_mask.numel(), 1) * 100.0
epoch_pred_fg_pct.append(pred_fg_pct)
epoch_gt_fg_pct.append(gt_fg_pct)
dice_values, iou_values = _batch_binary_metrics(pred.float(), gt_mask.float())
epoch_dices.extend(dice_values)
epoch_ious.extend(iou_values)
epoch_alerts.extend(
_numerical_health_check(
{"pred": pred, "gt_mask": gt_mask},
prefix="eval:",
)
)
model.train()
grad_stats = _grad_diagnostics(model)
param_stats = _param_diagnostics(model, prev_params)
prev_params = _snapshot_params(model)
avg_loss = float(np.mean(epoch_losses)) if epoch_losses else 0.0
avg_dice = float(np.mean(epoch_dices)) if epoch_dices else 0.0
avg_iou = float(np.mean(epoch_ious)) if epoch_ious else 0.0
avg_reward = float(np.mean(epoch_rewards)) if epoch_rewards else 0.0
avg_actor = float(np.mean(epoch_actor)) if epoch_actor else 0.0
avg_critic = float(np.mean(epoch_critic)) if epoch_critic else 0.0
avg_ce = float(np.mean(epoch_ce)) if epoch_ce else 0.0
avg_dice_loss = float(np.mean(epoch_dice_losses)) if epoch_dice_losses else 0.0
avg_entropy = float(np.mean(epoch_entropy)) if epoch_entropy else 0.0
avg_grad_norm = float(np.mean(epoch_grad_norms)) if epoch_grad_norms else 0.0
avg_reward_pos = float(np.mean(epoch_reward_pos_pct)) if epoch_reward_pos_pct else 0.0
avg_pred_fg = float(np.mean(epoch_pred_fg_pct)) if epoch_pred_fg_pct else 0.0
avg_gt_fg = float(np.mean(epoch_gt_fg_pct)) if epoch_gt_fg_pct else 0.0
avg_action_dist: list[dict[int, float]] = []
if epoch_action_dist:
for step_idx in range(DEFAULT_TMAX):
step_dist: dict[int, float] = {}
action_indices = sorted({action_idx for run_dist in epoch_action_dist if step_idx < len(run_dist) for action_idx in run_dist[step_idx]})
for action_idx in action_indices:
values = [
run_dist[step_idx][action_idx]
for run_dist in epoch_action_dist
if step_idx < len(run_dist)
]
step_dist[action_idx] = float(np.mean(values)) if values else 0.0
avg_action_dist.append(step_dist)
history["dice"].append(avg_dice)
history["iou"].append(avg_iou)
history["loss"].append(avg_loss)
history["reward"].append(avg_reward)
history["actor_loss"].append(avg_actor)
history["critic_loss"].append(avg_critic)
history["ce_loss"].append(avg_ce)
history["dice_loss"].append(avg_dice_loss)
history["entropy"].append(avg_entropy)
history["grad_norm"].append(avg_grad_norm)
history["action_dist"].append(avg_action_dist)
history["reward_pos_pct"].append(avg_reward_pos)
history["pred_fg_pct"].append(avg_pred_fg)
history["gt_fg_pct"].append(avg_gt_fg)
save_json(history_path, history)
loss_delta = avg_loss - prev_loss if prev_loss is not None else 0.0
prev_loss = avg_loss
if epoch_alerts:
print(f"[Overfit][Epoch {epoch}] Numerical alerts: {' | '.join(epoch_alerts)}")
if full_dump:
current_alpha = float(log_alpha.exp().detach().item()) if log_alpha is not None else 0.0
print(
f"[Overfit][Epoch {epoch:03d}] loss={avg_loss:.6f} (delta={loss_delta:+.6f}) "
f"dice={avg_dice:.4f} iou={avg_iou:.4f} reward={avg_reward:+.6f} "
f"entropy={avg_entropy:.6f} alpha={current_alpha:.4f}"
)
print(
f"[Overfit][Epoch {epoch:03d}] ce={avg_ce:.6f} dice_l={avg_dice_loss:.6f} "
f"grad_norm={avg_grad_norm:.6f} global_grad={grad_stats['global_norm']:.6f}"
)
if avg_action_dist:
first = avg_action_dist[0]
last = avg_action_dist[-1]
print(
f"[Overfit][Epoch {epoch:03d}] action step0={first} step_last={last} "
f"reward_pos={avg_reward_pos:.2f}%"
)
print(
f"[Overfit][Epoch {epoch:03d}] pred_fg={avg_pred_fg:.2f}% gt_fg={avg_gt_fg:.2f}% "
f"param_groups={list(param_stats.keys())}"
)
else:
print(
f"[Overfit][Epoch {epoch:03d}] loss={avg_loss:.6f} dice={avg_dice:.4f} "
f"iou={avg_iou:.4f} reward={avg_reward:+.6f}"
)
row = {
"epoch": epoch,
"dice": avg_dice,
"iou": avg_iou,
"loss": avg_loss,
"reward": avg_reward,
"actor_loss": avg_actor,
"critic_loss": avg_critic,
"ce_loss": avg_ce,
"dice_loss": avg_dice_loss,
"entropy": avg_entropy,
"grad_norm": avg_grad_norm,
"action_dist": avg_action_dist,
"reward_pos_pct": avg_reward_pos,
"pred_fg_pct": avg_pred_fg,
"gt_fg_pct": avg_gt_fg,
}
if avg_dice > best_dice:
best_dice = avg_dice
save_checkpoint(
ckpt_dir / "best.pt",
run_type="overfit",
model=model,
optimizer=optimizer,
scheduler=None,
scaler=scaler,
epoch=epoch,
best_metric_value=best_dice,
best_metric_name="overfit_dice",
run_config=run_config,
epoch_metrics=row,
patience_counter=0,
elapsed_seconds=elapsed_before_resume + (time.time() - start_time),
log_alpha=log_alpha,
alpha_optimizer=alpha_optimizer,
resume_source=resume_source,
)
if SAVE_LATEST_EVERY_EPOCH:
save_checkpoint(
ckpt_dir / "latest.pt",
run_type="overfit",
model=model,
optimizer=optimizer,
scheduler=None,
scaler=scaler,
epoch=epoch,
best_metric_value=best_dice,
best_metric_name="overfit_dice",
run_config=run_config,
epoch_metrics=row,
patience_counter=0,
elapsed_seconds=elapsed_before_resume + (time.time() - start_time),
log_alpha=log_alpha,
alpha_optimizer=alpha_optimizer,
resume_source=resume_source,
)
if CHECKPOINT_EVERY_N_EPOCHS > 0 and epoch % CHECKPOINT_EVERY_N_EPOCHS == 0:
save_checkpoint(
ckpt_dir / f"epoch_{epoch:04d}.pt",
run_type="overfit",
model=model,
optimizer=optimizer,
scheduler=None,
scaler=scaler,
epoch=epoch,
best_metric_value=best_dice,
best_metric_name="overfit_dice",
run_config=run_config,
epoch_metrics=row,
patience_counter=0,
elapsed_seconds=elapsed_before_resume + (time.time() - start_time),
log_alpha=log_alpha,
alpha_optimizer=alpha_optimizer,
resume_source=resume_source,
)
peak_dice = max(history["dice"]) if history["dice"] else 0.0
final_dice = history["dice"][-1] if history["dice"] else 0.0
summary = {
"run_type": "overfit",
"strategy": strategy,
"peak_dice": peak_dice,
"final_dice": final_dice,
"description": description,
"resumed": resume_source is not None,
"elapsed_seconds": elapsed_before_resume + (time.time() - start_time),
"final_epoch": max(len(history["dice"]), start_epoch - 1),
}
if resume_source is not None:
summary["resume_source"] = resume_source
save_json(overfit_root / "summary.json", summary)
print(
f"[Overfit] {run_identity_label(strategy=strategy, percent=bundle.percent, split_payload=bundle.split_payload)} | "
f"peak_dice={peak_dice:.4f}, final_dice={final_dice:.4f}"
)
del model
run_cuda_cleanup(
context=f"overfit {run_identity_label(strategy=strategy, percent=bundle.percent, split_payload=bundle.split_payload)}"
)
return {**summary, "history": history}
def run_configured_overfit_tests(
bundles: dict[float, DataBundle],
*,
model_config: RuntimeModelConfig,
) -> None:
banner("OVERFIT TEST MODE")
for percent in DATASET_PERCENTS:
bundle = bundles[percent]
for strategy in STRATEGIES:
strategy2_checkpoint_path = None
if strategy in (4, 5) or (strategy == 3 and STRATEGY3_BOOTSTRAP_FROM_STRATEGY2):
strategy2_checkpoint_path = resolve_strategy2_checkpoint_path(strategy, percent, model_config)
run_overfit_test(
strategy=strategy,
model_config=model_config,
bundle=bundle,
overfit_root=strategy_root_for_percent(strategy, percent, model_config) / "overfit_test",
strategy2_checkpoint_path=strategy2_checkpoint_path,
)
"""=============================================================================
OPTUNA + ORCHESTRATION
=============================================================================
"""
def strategy_epochs(strategy: int) -> int:
if strategy == 1:
return STRATEGY_1_MAX_EPOCHS
if strategy == 2:
return STRATEGY_2_MAX_EPOCHS
if strategy == 3:
return STRATEGY_3_MAX_EPOCHS
if strategy == 4:
return STRATEGY_4_MAX_EPOCHS
if strategy == 5:
return STRATEGY_5_MAX_EPOCHS
raise ValueError(f"Unsupported strategy for epoch selection: {strategy}")
def suggest_hyperparameters(trial: optuna.trial.Trial, strategy: int) -> dict[str, Any]:
if strategy == 3:
# For Strategy 3, the S2 encoder+decoder are fully frozen.
# head_lr / encoder_lr / decoder_lr are all forced to 0.0 at runtime,
# so only rl_lr is the effective learning rate.
# decoder_ce/dice weights are also irrelevant (frozen decoder).
# GT error channels have been removed from training, so gt_error_dropout is gone.
rl_lr = trial.suggest_float("rl_lr", HEAD_LR_RANGE[0], HEAD_LR_RANGE[1], log=True)
refine_delta_small = trial.suggest_float("refine_delta_small", 0.05, 0.25)
refine_delta_large = trial.suggest_float(
"refine_delta_large",
max(0.15, refine_delta_small + 0.05),
0.50,
)
return {
# Fixed / irrelevant when decoder is frozen
"head_lr": rl_lr,
"encoder_lr": ENCODER_LR_RANGE[0],
"decoder_lr": 0.0,
"strategy3_decoder_ce_weight": 0.0,
"strategy3_decoder_dice_weight": 0.0,
"strategy3_freeze_bootstrapped_segmentation": True,
"num_actions": 5,
"strategy3_action_mode": "delta",
# Searched — learning rates & regularisation
"rl_lr": rl_lr,
"weight_decay": trial.suggest_float("weight_decay", WEIGHT_DECAY_RANGE[0], WEIGHT_DECAY_RANGE[1], log=True),
"dropout_p": trial.suggest_float("dropout_p", DROPOUT_P_RANGE[0], DROPOUT_P_RANGE[1]),
# Searched — rollout
"tmax": trial.suggest_int("tmax", TMAX_RANGE[0], TMAX_RANGE[1]),
# Searched — architecture
"smp_encoder_proj_dim": trial.suggest_categorical("smp_encoder_proj_dim", [64, 128, 192, 256]),
# Searched — entropy / exploration
"entropy_lr": trial.suggest_float("entropy_lr", ENTROPY_LR_RANGE[0], ENTROPY_LR_RANGE[1], log=True),
"entropy_target_ratio": trial.suggest_float("entropy_target_ratio", 0.05, 0.45),
"entropy_alpha_init": trial.suggest_float("entropy_alpha_init", 1e-3, 2e-1, log=True),
"min_alpha": trial.suggest_float("min_alpha", 1e-4, 1e-1, log=True),
"a3c_entropy_coeff": trial.suggest_float("a3c_entropy_coeff", 0.001, 0.10, log=True),
# Searched — advantage estimation & critic
"gae_lambda": trial.suggest_float("gae_lambda", 0.80, 0.99),
"critic_loss_weight": trial.suggest_float("critic_loss_weight", 0.10, 1.50),
# Searched — reward shaping
"asymmetric_reward_alpha": trial.suggest_float("asymmetric_reward_alpha", 0.5, 2.0),
"boundary_reward_weight": trial.suggest_float("boundary_reward_weight", 0.0, 1.0),
"binary_reward_weight": trial.suggest_float("binary_reward_weight", 0.3, 0.9),
"reward_boundary_focus": trial.suggest_float("reward_boundary_focus", 0.3, 0.95),
"reward_inaction_cost": trial.suggest_float("reward_inaction_cost", 0.01, 0.15),
# Searched — gradient clipping
"strategy3_rl_grad_clip_norm": trial.suggest_float("strategy3_rl_grad_clip_norm", 0.5, 4.0),
# Searched — action deltas (enforce large > small)
"refine_delta_small": refine_delta_small,
"refine_delta_large": refine_delta_large,
# Searched — decision threshold
"threshold": trial.suggest_float("threshold", 0.35, 0.65),
# Searched — MC dropout uncertainty
"mc_dropout_p": trial.suggest_float("mc_dropout_p", 0.05, 0.50),
"mc_n_passes": trial.suggest_int("mc_n_passes", 3, 10),
# Searched — auxiliary supervised loss weights
"strategy3_aux_ce_weight": trial.suggest_float("strategy3_aux_ce_weight", 0.0, 1.0),
"strategy3_aux_dice_weight": trial.suggest_float("strategy3_aux_dice_weight", 0.0, 1.0),
"aux_action_ce_mix": trial.suggest_float("aux_action_ce_mix", 0.3, 1.0),
}
head_lr = trial.suggest_float("head_lr", HEAD_LR_RANGE[0], HEAD_LR_RANGE[1], log=True)
encoder_lr = trial.suggest_float("encoder_lr", ENCODER_LR_RANGE[0], min(ENCODER_LR_RANGE[1], head_lr), log=True)
weight_decay = trial.suggest_float("weight_decay", WEIGHT_DECAY_RANGE[0], WEIGHT_DECAY_RANGE[1], log=True)
dropout_p = trial.suggest_float("dropout_p", DROPOUT_P_RANGE[0], DROPOUT_P_RANGE[1])
params = {
"head_lr": head_lr,
"encoder_lr": encoder_lr,
"weight_decay": weight_decay,
"dropout_p": dropout_p,
"tmax": DEFAULT_TMAX,
"entropy_lr": DEFAULT_ENTROPY_LR,
}
if strategy != 2:
params["tmax"] = trial.suggest_int("tmax", TMAX_RANGE[0], TMAX_RANGE[1])
params["entropy_lr"] = trial.suggest_float("entropy_lr", ENTROPY_LR_RANGE[0], ENTROPY_LR_RANGE[1], log=True)
return params
def _format_hparam_value(key: str, value: Any) -> str:
if isinstance(value, float):
if key in {"head_lr", "encoder_lr", "entropy_lr"}:
return f"{value:.3e}"
return f"{value:.6g}"
return str(value)
def log_optuna_trial_start(
*,
study_name: str,
strategy: int,
bundle: DataBundle,
trial: optuna.trial.Trial,
trial_dir: Path,
params: dict[str, Any],
max_epochs: int,
) -> None:
run_name = run_identity_label(
strategy=strategy,
percent=bundle.percent,
trial_number=trial.number,
split_payload=bundle.split_payload,
)
lines = [
"",
"-" * 80,
f"OPTUNA TRIAL START | {run_name}",
"-" * 80,
f"Study name : {study_name}",
f"Run dir : {trial_dir}",
f"Max epochs : {max_epochs}",
f"Objective metric : {_strategy_selection_metric_name(strategy)}",
]
for key in sorted(params):
lines.append(f"{key:22s}: {_format_hparam_value(key, params[key])}")
tqdm.write("\n".join(lines))
def log_optuna_trial_result(
*,
strategy: int,
bundle: DataBundle,
trial: optuna.trial.Trial,
metric_value: float,
aggregate: dict[str, dict[str, float]],
) -> None:
run_name = run_identity_label(
strategy=strategy,
percent=bundle.percent,
trial_number=trial.number,
split_payload=bundle.split_payload,
)
tqdm.write(
f"[{run_name}] completed: {_strategy_selection_metric_name(strategy)}={metric_value:.4f}, "
f"best_test_iou={aggregate['iou']['mean']:.4f}"
)
def study_paths_for(
strategy: int,
percent: float,
model_config: RuntimeModelConfig | None = None,
) -> tuple[Path, Path, Path]:
pct_root = RUNS_ROOT / MODEL_NAME / f"pct_{percent_label(percent)}"
strategy_root = pct_root / strategy_dir_name(strategy, model_config)
study_root = strategy_root / "study"
trials_root = strategy_root / "trials"
return strategy_root, study_root, trials_root
def manual_hparams_key(strategy: int, percent: float) -> str:
return f"{strategy}:{percent_label(percent)}"
def reset_study_artifacts(strategy: int, percent: float, *, model_config: RuntimeModelConfig) -> None:
strategy_root, study_root, trials_root = study_paths_for(strategy, percent, model_config)
removed_any = False
for path in (study_root, trials_root):
if path.exists():
shutil.rmtree(path)
removed_any = True
if removed_any:
print(
f"[Optuna Reset] Removed cached study artifacts for strategy={strategy}, "
f"percent={percent_text(percent)} under {strategy_root}."
)
else:
print(
f"[Optuna Reset] No existing study artifacts found for strategy={strategy}, "
f"percent={percent_text(percent)}."
)
class _PlateauPruner(optuna.pruners.BasePruner):
"""Prune a trial whose metric has plateaued (no improvement to its
own personal best within a patience window).
Behaviour:
- During the first *n_warmup_steps* epochs: never prune.
- After warmup, track the trial's own best metric and the epoch
at which it was achieved.
- If *patience_steps* epochs pass without the trial beating its
own best, the trial is pruned (it has stagnated).
"""
def __init__(
self,
n_warmup_steps: int = 80,
patience_steps: int = 40,
) -> None:
self._n_warmup_steps = n_warmup_steps
self._patience_steps = patience_steps
def prune(
self,
study: "optuna.study.Study",
trial: "optuna.trial.FrozenTrial",
) -> bool:
step = trial.last_step
if step is None or step < self._n_warmup_steps:
return False
post_warmup = {
s: v for s, v in trial.intermediate_values.items()
if s >= self._n_warmup_steps
}
if not post_warmup:
return False
best_step = max(post_warmup, key=post_warmup.get)
epochs_since_improvement = step - best_step
return epochs_since_improvement >= self._patience_steps
def pruner_for_run() -> optuna.pruners.BasePruner:
if USE_TRIAL_PRUNING:
return _PlateauPruner(
n_warmup_steps=TRIAL_PRUNER_WARMUP_STEPS,
patience_steps=TRIAL_PRUNER_PATIENCE_STEPS,
)
return optuna.pruners.NopPruner()
def run_single_job(
*,
strategy: int,
model_config: RuntimeModelConfig,
bundle: DataBundle,
run_dir: Path,
params: dict[str, Any],
max_epochs: int,
trial: optuna.trial.Trial | None,
strategy2_checkpoint_path: str | Path | None = None,
resume_checkpoint_path: Path | None = None,
retrying_from_trial_number: int | None = None,
) -> tuple[dict[str, Any], list[dict[str, Any]], dict[str, dict[str, float]]]:
params = dict(params)
if strategy == 3:
params.setdefault(
"strategy3_freeze_bootstrapped_segmentation",
DEFAULT_STRATEGY3_FREEZE_BOOTSTRAPPED_SEGMENTATION,
)
bootstrap_freeze = (
strategy2_checkpoint_path is not None
and bool(params["strategy3_freeze_bootstrapped_segmentation"])
)
params.setdefault("num_actions", 5)
params.setdefault("strategy3_action_mode", "delta")
params.setdefault("decoder_lr", 0.0 if bootstrap_freeze else params["head_lr"] * 0.1)
params.setdefault("rl_lr", params["head_lr"])
params.setdefault("strategy3_decoder_ce_weight", 0.0 if bootstrap_freeze else DEFAULT_CE_WEIGHT)
params.setdefault("strategy3_decoder_dice_weight", 0.0 if bootstrap_freeze else DEFAULT_DICE_WEIGHT)
params.setdefault("gae_lambda", 0.95)
params.setdefault("a3c_entropy_coeff", 0.01)
params.setdefault("asymmetric_reward_alpha", 1.0)
params.setdefault("boundary_reward_weight", 0.0)
params.setdefault("binary_reward_weight", 0.7)
params.setdefault("reward_boundary_focus", 0.8)
params.setdefault("reward_inaction_cost", 0.05)
params.setdefault("gt_error_dropout", 0.40)
params.setdefault("mc_dropout_p", 0.3)
params.setdefault("mc_n_passes", 5)
params.setdefault("strategy3_rl_grad_clip_norm", 1.0)
params.setdefault("early_stopping_monitor", DEFAULT_EARLY_STOPPING_MONITOR)
params.setdefault("early_stopping_mode", DEFAULT_EARLY_STOPPING_MODE)
params.setdefault("early_stopping_min_delta", DEFAULT_EARLY_STOPPING_MIN_DELTA)
params.setdefault("early_stopping_start_epoch", DEFAULT_EARLY_STOPPING_START_EPOCH)
params.setdefault("early_stopping_patience", EARLY_STOPPING_PATIENCE)
set_current_job_params(params)
if "smp_encoder_proj_dim" in params and int(params["smp_encoder_proj_dim"]) != model_config.smp_encoder_proj_dim:
model_config = RuntimeModelConfig.from_payload(
{**model_config.to_payload(), "smp_encoder_proj_dim": int(params["smp_encoder_proj_dim"])}
).validate()
entropy_target_ratio = float(_job_param("entropy_target_ratio", 0.35))
entropy_alpha_init = float(_job_param("entropy_alpha_init", 0.12))
critic_loss_weight = float(_job_param("critic_loss_weight", DEFAULT_CRITIC_LOSS_WEIGHT))
ensure_dir(run_dir)
run_type = "trial" if trial is not None else "final"
config = {
"project_dir": str(PROJECT_DIR),
"data_root": str(DATA_ROOT),
"run_type": run_type,
"run_name": run_identity_label(
strategy=strategy,
percent=bundle.percent,
trial_number=trial.number if trial is not None else None,
split_payload=bundle.split_payload,
),
"strategy": strategy,
"dataset_percent": bundle.percent,
"dataset_name": bundle.split_payload["dataset_name"],
"dataset_split_policy": bundle.split_payload["dataset_split_policy"],
"dataset_splits_path": bundle.split_payload["dataset_splits_path"],
"split_type": bundle.split_payload["split_type"],
"train_subset_key": bundle.split_payload["train_subset_key"],
"train_subset_variant": bundle.split_payload.get("train_subset_variant", 0),
"train_subset_source": bundle.split_payload.get("train_subset_source", "persisted"),
"selected_split_manifest_path": bundle.split_payload.get("selected_split_manifest_path"),
"normalization_cache_path": bundle.split_payload["normalization_cache_path"],
"best_checkpoint_metric_name": _strategy_selection_metric_name(strategy),
"best_checkpoint_metrics": {str(key): value for key, value in BEST_CHECKPOINT_METRICS.items()},
"save_history_incrementally": bool(SAVE_HISTORY_INCREMENTALLY),
"write_epoch_diagnostic": bool(WRITE_EPOCH_DIAGNOSTIC),
"head_lr": params["head_lr"],
"encoder_lr": params["encoder_lr"],
"weight_decay": params["weight_decay"],
"dropout_p": params["dropout_p"],
"tmax": params["tmax"],
"entropy_lr": params["entropy_lr"],
"max_epochs": max_epochs,
"gamma": DEFAULT_GAMMA,
"critic_loss_weight": critic_loss_weight,
"grad_clip_norm": DEFAULT_GRAD_CLIP_NORM,
"scheduler_factor": SCHEDULER_FACTOR,
"scheduler_patience": SCHEDULER_PATIENCE,
"scheduler_threshold": SCHEDULER_THRESHOLD,
"scheduler_min_lr": SCHEDULER_MIN_LR,
"execution_mode": EXECUTION_MODE,
"evaluation_checkpoint_mode": EVAL_CHECKPOINT_MODE,
"strategy2_checkpoint_mode": STRATEGY2_CHECKPOINT_MODE,
"train_resume_mode": TRAIN_RESUME_MODE,
"train_resume_specific_checkpoint": TRAIN_RESUME_SPECIFIC_CHECKPOINT,
}
config.update({key: value for key, value in params.items() if key not in config})
config.update(model_config.to_payload())
if strategy2_checkpoint_path is not None:
config["strategy2_checkpoint_path"] = str(Path(strategy2_checkpoint_path))
if resume_checkpoint_path is not None:
config["resume_checkpoint_path"] = str(Path(resume_checkpoint_path))
if retrying_from_trial_number is not None:
config["retrying_from_trial_number"] = int(retrying_from_trial_number)
save_json(run_dir / "run_config.json", config)
model: nn.Module | None = None
try:
model, description, _compiled = build_model(
strategy,
params["dropout_p"],
model_config=model_config,
strategy2_checkpoint_path=strategy2_checkpoint_path,
)
summary, history = train_model(
run_type=run_type,
model_config=model_config,
run_config=config,
model=model,
description=description,
strategy=strategy,
run_dir=run_dir,
bundle=bundle,
max_epochs=max_epochs,
head_lr=params["head_lr"],
encoder_lr=params["encoder_lr"],
weight_decay=params["weight_decay"],
tmax=params["tmax"],
entropy_lr=params["entropy_lr"],
entropy_alpha_init=entropy_alpha_init,
entropy_target_ratio=entropy_target_ratio,
critic_loss_weight=critic_loss_weight,
ce_weight=DEFAULT_CE_WEIGHT,
dice_weight=DEFAULT_DICE_WEIGHT,
dropout_p=params["dropout_p"],
resume_checkpoint_path=resume_checkpoint_path,
trial=trial,
)
if trial is not None:
save_json(
run_dir / "summary.json",
{
"params": params,
"best_iou": float(summary["best_val_iou"]),
"best_model_metric_name": str(summary["best_model_metric_name"]),
"best_model_metric": float(summary["best_model_metric"]),
"resumed": bool(resume_checkpoint_path is not None),
"retrying_from_trial_number": retrying_from_trial_number,
},
)
return summary, history, {}
del model
model = None
run_cuda_cleanup()
aggregate, _per_sample = run_evaluation_for_run(
strategy=strategy,
percent=bundle.percent,
bundle=bundle,
run_dir=run_dir,
strategy2_checkpoint_path=strategy2_checkpoint_path,
)
return summary, history, aggregate
finally:
if model is not None:
del model
model = None
run_cuda_cleanup()
def _save_best_params_so_far(
study: optuna.study.Study,
study_root: Path,
strategy: int,
) -> None:
candidates = [
t for t in study.trials
if t.state in (optuna.trial.TrialState.COMPLETE, optuna.trial.TrialState.PRUNED) and t.value is not None
]
if not candidates:
return
best = max(candidates, key=lambda t: t.value)
params = dict(best.params)
if strategy == 2:
params.setdefault("tmax", DEFAULT_TMAX)
params.setdefault("entropy_lr", DEFAULT_ENTROPY_LR)
save_json(study_root / "best_params.json", params)
def run_study(
strategy: int,
bundle: DataBundle,
*,
model_config: RuntimeModelConfig,
strategy2_checkpoint_path: str | Path | None = None,
) -> dict[str, Any]:
strategy_root, study_root, trials_root = study_paths_for(strategy, bundle.percent, model_config)
ensure_dir(strategy_root.parent)
strategy_root = ensure_dir(strategy_root)
study_root = ensure_dir(strategy_root / "study")
trials_root = ensure_dir(strategy_root / "trials")
storage_path = study_root / "study.sqlite3"
storage = RDBStorage(
url=f"sqlite:///{storage_path.resolve()}",
heartbeat_interval=OPTUNA_HEARTBEAT_INTERVAL,
grace_period=OPTUNA_HEARTBEAT_GRACE_PERIOD,
)
sampler = optuna.samplers.TPESampler(seed=SEED)
study_name = (
f"{MODEL_NAME}_{model_config.backbone_tag()}_{run_identity_slug(strategy=strategy, percent=bundle.percent, split_payload=bundle.split_payload)}"
)
study = optuna.create_study(
study_name=study_name,
direction=STUDY_DIRECTION,
sampler=sampler,
pruner=pruner_for_run(),
storage=storage,
load_if_exists=LOAD_EXISTING_STUDIES,
)
existing_trials = [trial for trial in study.trials if trial.state.is_finished()]
if existing_trials:
print(
f"[Optuna Study] Loaded existing study '{study_name}' with "
f"{len(existing_trials)} existing finished trial(s). Running {NUM_TRIALS} new trial(s)."
)
else:
print(f"[Optuna Study] Starting new study '{study_name}' with {NUM_TRIALS} trial(s).")
def objective(trial: optuna.trial.Trial) -> float:
trial_dir = ensure_dir(trials_root / f"trial_{trial.number:03d}")
params = suggest_hyperparameters(trial, strategy)
log_optuna_trial_start(
study_name=study_name,
strategy=strategy,
bundle=bundle,
trial=trial,
trial_dir=trial_dir,
params=params,
max_epochs=strategy_epochs(strategy),
)
summary: dict[str, Any] | None = None
_history: list[dict[str, Any]] | None = None
aggregate: dict[str, dict[str, float]] | None = None
completed_successfully = False
run_cuda_cleanup()
try:
summary, _history, aggregate = run_single_job(
strategy=strategy,
model_config=model_config,
bundle=bundle,
run_dir=trial_dir,
params=params,
max_epochs=strategy_epochs(strategy),
trial=trial,
strategy2_checkpoint_path=strategy2_checkpoint_path,
)
metric_value = float(summary["best_model_metric"])
completed_successfully = True
tqdm.write(
f"[{run_identity_label(strategy=strategy, percent=bundle.percent, trial_number=trial.number, split_payload=bundle.split_payload)}] "
f"completed: {summary['best_model_metric_name']}={metric_value:.4f}"
)
return metric_value
finally:
_save_best_params_so_far(study, study_root, strategy)
if aggregate is not None:
del aggregate
aggregate = None
if _history is not None:
del _history
_history = None
if summary is not None:
del summary
summary = None
prune_optuna_trial_dir(trial_dir)
run_cuda_cleanup(context=f"trial {trial.number:03d} boundary")
study.optimize(objective, n_trials=NUM_TRIALS, show_progress_bar=True)
trials_with_values = [
t for t in study.trials
if t.state in (optuna.trial.TrialState.COMPLETE, optuna.trial.TrialState.PRUNED) and t.value is not None
]
if not trials_with_values:
raise RuntimeError(
f"Study '{study_name}' has no trials with recorded values, so best params cannot be resolved. "
f"Finished trials={len([trial for trial in study.trials if trial.state.is_finished()])}, "
f"configured cap={NUM_TRIALS}."
)
best_params = dict(study.best_trial.params)
if strategy == 2:
best_params.setdefault("tmax", DEFAULT_TMAX)
best_params.setdefault("entropy_lr", DEFAULT_ENTROPY_LR)
save_json(study_root / "best_params.json", best_params)
save_json(
study_root / "summary.json",
{
"best_params": best_params,
"optimized_param_names": sorted(best_params.keys()),
"best_metric_name": _strategy_selection_metric_name(strategy),
"best_metric_value": float(study.best_value),
"best_iou": float(study.best_value) if _strategy_selection_metric_name(strategy) == "val_iou" else None,
"finished_trials": len([trial for trial in study.trials if trial.state.is_finished()]),
"completed_trials": len([t for t in study.trials if t.state == optuna.trial.TrialState.COMPLETE]),
"target_trials": int(NUM_TRIALS),
"ran_trials": int(NUM_TRIALS),
},
)
prune_optuna_study_dir(study_root)
if trials_root.exists():
shutil.rmtree(trials_root, ignore_errors=True)
return best_params
def run_final_training(
strategy: int,
bundle: DataBundle,
params: dict[str, Any],
*,
model_config: RuntimeModelConfig,
strategy2_checkpoint_path: str | Path | None = None,
) -> None:
final_root = final_root_for_strategy(strategy, bundle.percent, model_config)
if SKIP_EXISTING_FINALS and (final_root / "summary.json").exists():
print(f"Skipping existing final run: {final_root}")
return
save_json(final_root / "best_params.json", params)
resume_checkpoint_path = resolve_train_resume_checkpoint_path(final_root)
run_single_job(
strategy=strategy,
model_config=model_config,
bundle=bundle,
run_dir=final_root,
params=params,
max_epochs=strategy_epochs(strategy),
trial=None,
strategy2_checkpoint_path=strategy2_checkpoint_path,
resume_checkpoint_path=resume_checkpoint_path,
)
def print_environment_summary(model_config: RuntimeModelConfig) -> None:
banner("RUNTIME SUMMARY")
images_dir, annotations_dir = current_dataset_dirs()
print(f"Project dir : {PROJECT_DIR}")
print(f"Data root : {DATA_ROOT}")
print(f"Runs root : {RUNS_ROOT}")
print(f"Dataset name : {current_dataset_name()}")
if current_dataset_name() == "BUSI_with_classes":
print(f"Dataset split policy : {current_busi_with_classes_split_policy()}")
print(f"Images dir : {images_dir}")
print(f"Masks dir : {annotations_dir}")
print(f"Dataset splits json : {current_dataset_splits_json_path()}")
print(f"Split type : {SPLIT_TYPE}")
print(f"Experiment mode : {EXPERIMENT_MODE}")
print(f"Device : {DEVICE}")
print(f"Device source : {DEVICE_FALLBACK_SOURCE}")
print(f"Model name : {MODEL_NAME}")
print(f"Seed : {SEED}")
print(f"PyTorch version : {torch.__version__}")
print(f"Batch size : {BATCH_SIZE}")
print(f"Use AMP : {USE_AMP}")
print(f"Num workers : {NUM_WORKERS}")
print(f"Pin memory : {USE_PIN_MEMORY}")
print(f"CuDNN deterministic : {torch.backends.cudnn.deterministic}")
print(f"CuDNN benchmark : {torch.backends.cudnn.benchmark}")
if DEVICE.type == "cuda":
props = torch.cuda.get_device_properties(0)
print(f"GPU : {torch.cuda.get_device_name(0)}")
print(f"GPU VRAM : {props.total_memory / (1024 ** 3):.2f} GB")
print(f"AMP dtype : {resolve_amp_dtype(AMP_DTYPE)}")
print(f"Trial pruning : {USE_TRIAL_PRUNING}")
print(f"Backbone family : {model_config.backbone_family}")
if model_config.backbone_family == "custom_vgg":
print(f"VGG feature scales : {model_config.vgg_feature_scales}")
print(f"VGG feature dilation : {model_config.vgg_feature_dilation}")
else:
print(f"SMP encoder : {model_config.smp_encoder_name}")
print(f"SMP encoder depth : {model_config.smp_encoder_depth}")
print(f"SMP encoder proj dim : {model_config.smp_encoder_proj_dim}")
print(f"SMP decoder : {model_config.smp_decoder_type}")
print(f"Strategies : {STRATEGIES}")
print(f"Dataset percents : {[percent_text(value) for value in DATASET_PERCENTS]}")
print(f"Best metrics : {BEST_CHECKPOINT_METRICS}")
print(f"History incremental : {SAVE_HISTORY_INCREMENTALLY}")
print(f"Write diagnostics : {WRITE_EPOCH_DIAGNOSTIC}")
print_imagenet_normalization_status()
print(f"Trials per study : {NUM_TRIALS}")
print(f"Execution mode : {EXECUTION_MODE}")
print(f"Run Optuna : {RUN_OPTUNA}")
print(f"Use saved best params : {USE_EXISTING_BEST_PARAMS_WHEN_OPTUNA_OFF}")
print(f"Reset studies/run : {RESET_ALL_STUDIES_EACH_RUN}")
print(f"Load existing studies : {LOAD_EXISTING_STUDIES}")
print(f"Eval ckpt selector : {EVAL_CHECKPOINT_MODE}")
print(f"S2 ckpt selector : {STRATEGY2_CHECKPOINT_MODE}")
print(f"S3 bootstrap from S2 : {STRATEGY3_BOOTSTRAP_FROM_STRATEGY2}")
print(f"S3 freeze default : {DEFAULT_STRATEGY3_FREEZE_BOOTSTRAPPED_SEGMENTATION}")
print(f"Train resume mode : {TRAIN_RESUME_MODE}")
print(f"Verbose epoch log : {VERBOSE_EPOCH_LOG}")
print(f"Validate every epochs : {VALIDATE_EVERY_N_EPOCHS}")
print(f"Smoke test enabled : {RUN_SMOKE_TEST}")
print(f"Overfit test enabled : {RUN_OVERFIT_TEST}")
print(f"Overfit batches : {OVERFIT_N_BATCHES}")
print(f"Overfit epochs : {OVERFIT_N_EPOCHS}")
def maybe_run_strategy_smoke_test(
*,
strategy: int,
model_config: RuntimeModelConfig,
bundle: DataBundle,
strategy2_checkpoint_path: str | Path | None = None,
) -> None:
if not RUN_SMOKE_TEST:
return
if EXECUTION_MODE == "eval_only":
return
run_smoke_test(
strategy=strategy,
model_config=model_config,
bundle=bundle,
smoke_root=strategy_root_for_percent(strategy, bundle.percent, model_config) / "smoke_test",
strategy2_checkpoint_path=strategy2_checkpoint_path,
)
"""=============================================================================
REPEATED HOLDOUT INTEGRATION
=============================================================================
"""
base = sys.modules[__name__]
REPEATED_HOLDOUT_ROOT = base.RUNS_ROOT / base.MODEL_NAME / "repeated_holdout"
EXPERIMENT_ROOT = REPEATED_HOLDOUT_ROOT / FOLDS_EXPERIMENT_NAME
EXPERIMENT_DB_PATH = EXPERIMENT_ROOT / "experiment_state.sqlite3"
SPLIT_MANIFESTS_DIR = EXPERIMENT_ROOT / "manifests" / "splits"
SUBSET_MANIFESTS_DIR = EXPERIMENT_ROOT / "manifests" / "subsets"
EXPORTS_DIR = EXPERIMENT_ROOT / "exports"
"""=============================================================================
RUNTIME STATE
=============================================================================
"""
@dataclass(frozen=True)
class PercentRepeatSpec:
percent_int: int
fraction: float
repeat_count: int
@dataclass(frozen=True)
class FoldRunContext:
split_repeat_index: int
subset_repeat_index: int
percent_int: int
percent_fraction: float
split_seed: int
subset_seed: int
repeat_root: Path
split_manifest_path: Path
subset_manifest_path: Path
@dataclass(frozen=True)
class RunKey:
split_repeat_index: int
dataset_percent: int
subset_repeat_index: int
strategy: int
CURRENT_FOLD_CONTEXT: FoldRunContext | None = None
LEDGER_CONN: sqlite3.Connection | None = None
PERCENT_SPECS_CACHE: list[PercentRepeatSpec] | None = None
ORIGINAL_SAVE_JSON = base.save_json
ORIGINAL_PERCENT_ROOT = base.percent_root
ORIGINAL_STRATEGY_ROOT_FOR_PERCENT = base.strategy_root_for_percent
ORIGINAL_FINAL_ROOT_FOR_STRATEGY = base.final_root_for_strategy
ORIGINAL_STUDY_PATHS_FOR = base.study_paths_for
ORIGINAL_SAVE_CHECKPOINT = base.save_checkpoint
ORIGINAL_RUN_EVALUATION_FOR_RUN = base.run_evaluation_for_run
BASE_RESUME_IDENTITY_KEYS = tuple(base.RESUME_IDENTITY_KEYS)
RUNTIME_ONLY_CONFIG_KEYS = frozenset(
{
"PERCENT_EXECUTION_MODE",
"SELECTED_DATASET_PERCENTS",
"SPLIT_EXECUTION_MODE",
"SELECTED_SPLIT_INDICES",
"REPEAT_EXECUTION_MODE",
"SELECTED_REPEAT_INDICES",
}
)
"""=============================================================================
UTILITIES
=============================================================================
"""
def now_utc_iso() -> str:
return datetime.now(timezone.utc).isoformat()
def _jsonify(value: Any) -> Any:
if isinstance(value, Path):
return str(value)
if isinstance(value, dict):
return {str(key): _jsonify(val) for key, val in sorted(value.items(), key=lambda item: str(item[0]))}
if isinstance(value, (list, tuple)):
return [_jsonify(item) for item in value]
if isinstance(value, set):
return [_jsonify(item) for item in sorted(value, key=str)]
if isinstance(value, (str, int, float, bool)) or value is None:
return value
return repr(value)
def atomic_write_text(path: str | Path, text: str) -> None:
target = Path(path)
ensure_dir(target.parent)
fd, tmp_name = tempfile.mkstemp(prefix=f".{target.name}.", suffix=".tmp", dir=str(target.parent))
tmp_path = Path(tmp_name)
try:
with os.fdopen(fd, "w", encoding="utf-8") as handle:
handle.write(text)
handle.flush()
os.fsync(handle.fileno())
os.replace(tmp_path, target)
finally:
if tmp_path.exists():
tmp_path.unlink(missing_ok=True)
def atomic_write_bytes(path: str | Path, payload: bytes) -> None:
target = Path(path)
ensure_dir(target.parent)
fd, tmp_name = tempfile.mkstemp(prefix=f".{target.name}.", suffix=".tmp", dir=str(target.parent))
tmp_path = Path(tmp_name)
try:
with os.fdopen(fd, "wb") as handle:
handle.write(payload)
handle.flush()
os.fsync(handle.fileno())
os.replace(tmp_path, target)
finally:
if tmp_path.exists():
tmp_path.unlink(missing_ok=True)
def atomic_save_json(path: str | Path, payload: Any) -> None:
atomic_write_text(path, json.dumps(payload, indent=2, sort_keys=True))
def atomic_torch_save(path: str | Path, payload: Any) -> None:
target = Path(path)
ensure_dir(target.parent)
fd, tmp_name = tempfile.mkstemp(prefix=f".{target.name}.", suffix=".tmp", dir=str(target.parent))
tmp_path = Path(tmp_name)
try:
with os.fdopen(fd, "wb") as handle:
torch.save(payload, handle)
handle.flush()
os.fsync(handle.fileno())
os.replace(tmp_path, target)
finally:
if tmp_path.exists():
tmp_path.unlink(missing_ok=True)
def stable_hash(text: str) -> str:
return hashlib.sha256(text.encode("utf-8")).hexdigest()
def stable_int(text: str) -> int:
return base.stable_int_from_text(text)
def fold_seed(tag: str) -> int:
return int(base.SEED) + stable_int(tag)
def all_split_repeat_indices() -> list[int]:
return list(range(1, int(NUM_STRATIFIED_SPLIT_REPEATS) + 1))
def max_subset_repeat_index() -> int:
return max(int(spec.repeat_count) for spec in percent_specs())
def current_percent_sampling_mode() -> str:
mode = str(PERCENT_SAMPLING_MODE).strip().lower()
if mode not in SUPPORTED_PERCENT_SAMPLING_MODES:
raise ValueError(
f"PERCENT_SAMPLING_MODE must be one of {SUPPORTED_PERCENT_SAMPLING_MODES}, got {mode!r}"
)
return mode
def current_split_execution_mode() -> str:
mode = str(SPLIT_EXECUTION_MODE).strip().lower()
if mode not in SUPPORTED_SPLIT_EXECUTION_MODES:
raise ValueError(
f"SPLIT_EXECUTION_MODE must be one of {SUPPORTED_SPLIT_EXECUTION_MODES}, got {mode!r}"
)
return mode
def current_repeat_execution_mode() -> str:
mode = str(REPEAT_EXECUTION_MODE).strip().lower()
if mode not in SUPPORTED_REPEAT_EXECUTION_MODES:
raise ValueError(
f"REPEAT_EXECUTION_MODE must be one of {SUPPORTED_REPEAT_EXECUTION_MODES}, got {mode!r}"
)
return mode
def current_percent_execution_mode() -> str:
mode = str(PERCENT_EXECUTION_MODE).strip().lower()
if mode not in SUPPORTED_PERCENT_EXECUTION_MODES:
raise ValueError(
f"PERCENT_EXECUTION_MODE must be one of {SUPPORTED_PERCENT_EXECUTION_MODES}, got {mode!r}"
)
return mode
def split_repeat_indices_to_run() -> list[int]:
split_indices = all_split_repeat_indices()
if current_split_execution_mode() == "auto":
return split_indices
if not SELECTED_SPLIT_INDICES:
raise ValueError(
"SELECTED_SPLIT_INDICES must be non-empty when SPLIT_EXECUTION_MODE='manual'."
)
selected: list[int] = []
seen: set[int] = set()
max_index = split_indices[-1]
for raw_index in SELECTED_SPLIT_INDICES:
if isinstance(raw_index, bool) or not isinstance(raw_index, int):
raise TypeError(
"SELECTED_SPLIT_INDICES entries must be integer split indices in the "
f"range [1, {max_index}]."
)
if raw_index < 1 or raw_index > max_index:
raise ValueError(
f"SELECTED_SPLIT_INDICES entries must be in the range [1, {max_index}], got {raw_index}."
)
if raw_index in seen:
raise ValueError(f"SELECTED_SPLIT_INDICES contains duplicate split index {raw_index}.")
seen.add(raw_index)
selected.append(raw_index)
return selected
def subset_repeat_indices_to_run() -> list[int]:
repeat_indices = list(range(1, max_subset_repeat_index() + 1))
if current_repeat_execution_mode() == "auto":
return repeat_indices
if not SELECTED_REPEAT_INDICES:
raise ValueError(
"SELECTED_REPEAT_INDICES must be non-empty when REPEAT_EXECUTION_MODE='manual'."
)
selected: list[int] = []
seen: set[int] = set()
max_index = repeat_indices[-1]
for raw_index in SELECTED_REPEAT_INDICES:
if isinstance(raw_index, bool) or not isinstance(raw_index, int):
raise TypeError(
"SELECTED_REPEAT_INDICES entries must be integer repeat indices in the "
f"range [1, {max_index}]."
)
if raw_index < 1 or raw_index > max_index:
raise ValueError(
f"SELECTED_REPEAT_INDICES entries must be in the range [1, {max_index}], got {raw_index}."
)
if raw_index in seen:
raise ValueError(f"SELECTED_REPEAT_INDICES contains duplicate repeat index {raw_index}.")
seen.add(raw_index)
selected.append(raw_index)
return selected
def percent_specs_to_run() -> list[PercentRepeatSpec]:
all_specs = percent_specs()
if current_percent_execution_mode() == "auto":
return all_specs
if not SELECTED_DATASET_PERCENTS:
raise ValueError(
"SELECTED_DATASET_PERCENTS must be non-empty when PERCENT_EXECUTION_MODE='manual'."
)
all_percent_ints = {spec.percent_int for spec in all_specs}
selected: list[PercentRepeatSpec] = []
seen: set[int] = set()
for raw_percent in SELECTED_DATASET_PERCENTS:
if isinstance(raw_percent, bool) or not isinstance(raw_percent, int):
raise TypeError(
"SELECTED_DATASET_PERCENTS entries must be integer percentages in the range [1, 100]."
)
if raw_percent not in all_percent_ints:
raise ValueError(
f"SELECTED_DATASET_PERCENTS entry {raw_percent} is not defined in "
f"DATASET_PERCENT_REPEAT_COUNTS. Available: {sorted(all_percent_ints)}."
)
if raw_percent in seen:
raise ValueError(f"SELECTED_DATASET_PERCENTS contains duplicate percent {raw_percent}.")
seen.add(raw_percent)
spec_map = {spec.percent_int: spec for spec in all_specs}
for raw_percent in SELECTED_DATASET_PERCENTS:
selected.append(spec_map[raw_percent])
selected.sort(key=lambda s: s.percent_int)
return selected
def validate_repeated_holdout_settings() -> None:
if int(NUM_STRATIFIED_SPLIT_REPEATS) <= 0:
raise ValueError("NUM_STRATIFIED_SPLIT_REPEATS must be a positive integer.")
current_percent_sampling_mode()
current_split_execution_mode()
current_repeat_execution_mode()
current_percent_execution_mode()
split_repeat_indices_to_run()
subset_repeat_indices_to_run()
percent_specs_to_run()
def repeated_holdout_split_policy() -> str | None:
if base.current_dataset_name() == "BUSI_with_classes":
return base.current_busi_with_classes_split_policy()
return None
def active_specs_for_subset_repeat(subset_repeat_index: int) -> list[PercentRepeatSpec]:
return [
spec
for spec in percent_specs()
if subset_repeat_index <= int(spec.repeat_count)
]
def percent_specs() -> list[PercentRepeatSpec]:
global PERCENT_SPECS_CACHE
if PERCENT_SPECS_CACHE is not None:
return list(PERCENT_SPECS_CACHE)
specs: list[PercentRepeatSpec] = []
if not DATASET_PERCENT_REPEAT_COUNTS:
raise ValueError("DATASET_PERCENT_REPEAT_COUNTS must contain at least one percentage entry.")
for raw_percent, raw_repeat_count in DATASET_PERCENT_REPEAT_COUNTS.items():
if isinstance(raw_percent, bool) or not isinstance(raw_percent, int):
raise TypeError(
"DATASET_PERCENT_REPEAT_COUNTS keys must be integer percentages in the range [1, 100]."
)
if raw_percent <= 0 or raw_percent > 100:
raise ValueError(f"Invalid dataset percent {raw_percent}; expected an integer in [1, 100].")
if isinstance(raw_repeat_count, bool) or int(raw_repeat_count) <= 0:
raise ValueError(
f"Invalid repeat count for percent {raw_percent}: {raw_repeat_count!r}. Expected a positive integer."
)
repeat_count = int(raw_repeat_count)
if raw_percent == 100 and repeat_count > 1:
print(
f"[Repeated Holdout] Percent 100 was configured with repeat_count={repeat_count}. "
"Collapsing to one effective repeat per split."
)
repeat_count = 1
fraction = float(raw_percent) / 100.0
specs.append(PercentRepeatSpec(percent_int=raw_percent, fraction=fraction, repeat_count=repeat_count))
specs.sort(key=lambda item: item.percent_int)
PERCENT_SPECS_CACHE = list(specs)
return list(PERCENT_SPECS_CACHE)
def fold_experiment_summary(model_config: base.RuntimeModelConfig) -> None:
base.banner("RUNNER FOLDS | REPEATED STRATIFIED HOLDOUT")
print(f"Experiment name : {FOLDS_EXPERIMENT_NAME}")
print(f"Resume folds : {RESUME_FOLDS}")
print(f"Experiment root : {EXPERIMENT_ROOT}")
print(f"Experiment DB : {EXPERIMENT_DB_PATH}")
print(f"Dataset name : {base.current_dataset_name()}")
print(f"Split type : {base.SPLIT_TYPE}")
print(f"Split repeats : {NUM_STRATIFIED_SPLIT_REPEATS}")
print(f"Sampling mode : {current_percent_sampling_mode()}")
print(f"Split execution mode : {current_split_execution_mode()}")
if current_split_execution_mode() == "manual":
print(f"Selected split indices: {split_repeat_indices_to_run()}")
print(f"Repeat execution mode : {current_repeat_execution_mode()}")
if current_repeat_execution_mode() == "manual":
print(f"Selected repeat idxs : {subset_repeat_indices_to_run()}")
print(f"Percent execution mode: {current_percent_execution_mode()}")
if current_percent_execution_mode() == "manual":
print(f"Selected percents : {[s.percent_int for s in percent_specs_to_run()]}")
print(f"Strategies : {base.STRATEGIES}")
print(
"Percent repeats : "
+ ", ".join(f"{spec.percent_int}% x{spec.repeat_count}" for spec in percent_specs())
)
print(f"Execution mode : {base.EXECUTION_MODE}")
print(f"Run smoke test : {base.RUN_SMOKE_TEST}")
print(f"Run overfit test : {base.RUN_OVERFIT_TEST}")
print(f"Run Optuna : {base.RUN_OPTUNA}")
print(f"Load existing studies : {base.LOAD_EXISTING_STUDIES}")
print(f"Backbone : {model_config.backbone_display_name()}")
def config_snapshot(model_config: base.RuntimeModelConfig) -> dict[str, Any]:
base_config = {
name: _jsonify(getattr(base, name))
for name in sorted(dir(base))
if name.isupper() and not name.startswith("_")
and name not in RUNTIME_ONLY_CONFIG_KEYS
}
return {
"folds_runner": {
"NUM_STRATIFIED_SPLIT_REPEATS": int(NUM_STRATIFIED_SPLIT_REPEATS),
"DATASET_PERCENT_REPEAT_COUNTS": _jsonify(DATASET_PERCENT_REPEAT_COUNTS),
"PERCENT_SAMPLING_MODE": current_percent_sampling_mode(),
"FOLDS_EXPERIMENT_NAME": str(FOLDS_EXPERIMENT_NAME),
"RESUME_FOLDS": bool(RESUME_FOLDS),
"REPEATED_HOLDOUT_ROOT": str(REPEATED_HOLDOUT_ROOT),
"EXPERIMENT_ROOT": str(EXPERIMENT_ROOT),
"EXPERIMENT_DB_PATH": str(EXPERIMENT_DB_PATH),
},
"runner": base_config,
"model_config": model_config.to_payload(),
}
def config_fingerprint(snapshot: dict[str, Any]) -> str:
return stable_hash(json.dumps(snapshot, sort_keys=True))
def dataset_fingerprint(sample_records: list[dict[str, str]]) -> str:
payload = {
"dataset_name": base.current_dataset_name(),
"records": [
{
"filename": record["filename"],
"image_rel_path": record["image_rel_path"],
"mask_rel_path": record["mask_rel_path"],
"class_label": record.get("class_label"),
}
for record in sample_records
],
}
return stable_hash(json.dumps(payload, sort_keys=True))
def split_manifest_path(split_repeat_index: int) -> Path:
return SPLIT_MANIFESTS_DIR / f"split_{split_repeat_index:03d}.json"
def subset_manifest_path(split_repeat_index: int, percent_int: int, subset_repeat_index: int) -> Path:
return SUBSET_MANIFESTS_DIR / (
f"split_{split_repeat_index:03d}_pct_{percent_int:03d}_repeat_{subset_repeat_index:02d}.json"
)
def repeat_root(split_repeat_index: int, percent_int: int, subset_repeat_index: int) -> Path:
return (
EXPERIMENT_ROOT
/ f"split_{split_repeat_index:03d}"
/ f"pct_{percent_int:03d}"
/ f"repeat_{subset_repeat_index:02d}"
)
def run_dir_for(strategy: int, ctx: FoldRunContext, model_config: base.RuntimeModelConfig | None = None) -> Path:
strategy_dir = base.strategy_dir_name(strategy, model_config)
return ensure_dir(ctx.repeat_root / strategy_dir / "final")
def overfit_root_for(strategy: int, ctx: FoldRunContext, model_config: base.RuntimeModelConfig | None = None) -> Path:
strategy_dir = base.strategy_dir_name(strategy, model_config)
return ensure_dir(ctx.repeat_root / strategy_dir / "overfit_test")
def strategy_root_for(strategy: int, ctx: FoldRunContext, model_config: base.RuntimeModelConfig | None = None) -> Path:
strategy_dir = base.strategy_dir_name(strategy, model_config)
return ensure_dir(ctx.repeat_root / strategy_dir)
def fold_study_paths_for(strategy: int, ctx: FoldRunContext, model_config: base.RuntimeModelConfig | None = None) -> tuple[Path, Path, Path]:
strategy_root = strategy_root_for(strategy, ctx, model_config)
return strategy_root, ensure_dir(strategy_root / "study"), ensure_dir(strategy_root / "trials")
def select_sample_records() -> tuple[list[dict[str, str]], Path]:
dataset_name = base.current_dataset_name()
images_dir, annotations_dir = base.current_dataset_dirs()
if not images_dir.exists() or not annotations_dir.exists():
raise FileNotFoundError(
f"Expected dataset directories for {dataset_name} under {base.DATA_ROOT}: "
f"images={images_dir}, masks={annotations_dir}"
)
matched, missing_masks, missing_images = base.validate_image_mask_consistency(images_dir, annotations_dir)
if missing_masks or missing_images:
raise RuntimeError(
"BUSI image/mask mismatch detected. "
f"missing_masks={len(missing_masks)}, missing_images={len(missing_images)}"
)
dataset_root = images_dir.parent.resolve()
sample_records = base.build_sample_records(
matched,
images_subdir=images_dir.relative_to(dataset_root).as_posix(),
annotations_subdir=annotations_dir.relative_to(dataset_root).as_posix(),
dataset_name=dataset_name,
)
if dataset_name == "BUSI_with_classes":
pipeline_check_path = base.current_pipeline_check_path()
if pipeline_check_path is not None:
base.validate_busi_with_classes_pipeline_report(pipeline_check_path, sample_records)
return sample_records, dataset_root
def build_base_split_for_repeat(sample_records: list[dict[str, str]], split_seed: int) -> dict[str, list[dict[str, str]]]:
dataset_name = base.current_dataset_name()
if dataset_name == "BUSI_with_classes":
split_policy = repeated_holdout_split_policy()
if split_policy != "stratified":
raise ValueError(
"RUNNER_FOLDS.py requires BUSI_with_classes to use BUSI_WITH_CLASSES_SPLIT_POLICY='stratified'."
)
return base.build_stratified_base_split(
sample_records,
split_type=base.SPLIT_TYPE,
seed=split_seed,
)
return base.build_unstratified_base_split(
sample_records,
split_type=base.SPLIT_TYPE,
seed=split_seed,
)
def validate_base_split(base_splits: dict[str, list[dict[str, str]]], *, split_repeat_index: int) -> None:
split_filenames = {
split_name: [record["filename"] for record in records]
for split_name, records in base_splits.items()
}
leaks = base.check_data_leakage(split_filenames)
if leaks:
raise RuntimeError(
f"Data leakage detected for split_repeat_index={split_repeat_index}: {list(leaks.keys())}"
)
def build_subset_for_repeat(
train_records: list[dict[str, str]],
*,
percent_fraction: float,
subset_seed: int,
) -> list[dict[str, str]]:
if percent_fraction >= 1.0:
return [dict(record) for record in train_records]
subsets = base.build_nested_train_subsets(
train_records,
[percent_fraction],
split_type=base.SPLIT_TYPE,
seed=subset_seed,
split_policy=repeated_holdout_split_policy(),
subset_variant=0,
)
return subsets[base.percent_label(percent_fraction)]
def build_incremental_subset_chain(
train_records: list[dict[str, str]],
*,
active_specs: list[PercentRepeatSpec],
subset_seed: int,
) -> dict[str, list[dict[str, str]]]:
fractions = [spec.fraction for spec in active_specs]
return base.build_nested_train_subsets(
train_records,
fractions,
split_type=base.SPLIT_TYPE,
seed=subset_seed,
split_policy=repeated_holdout_split_policy(),
subset_variant=0,
)
def iter_manifested_contexts(
split_repeat_indices: list[int] | None = None,
subset_repeat_indices: list[int] | None = None,
) -> Iterator[FoldRunContext]:
selected_indices = all_split_repeat_indices() if split_repeat_indices is None else list(split_repeat_indices)
selected_subset_repeats = (
subset_repeat_indices_to_run() if subset_repeat_indices is None else list(subset_repeat_indices)
)
selected_subset_repeat_set = set(selected_subset_repeats)
for split_repeat_index in selected_indices:
for spec in percent_specs_to_run():
for subset_repeat_index in range(1, int(spec.repeat_count) + 1):
if subset_repeat_index not in selected_subset_repeat_set:
continue
yield load_context(split_repeat_index, spec.percent_int, subset_repeat_index)
def validate_subset_records(
train_records: list[dict[str, str]],
subset_records: list[dict[str, str]],
*,
split_repeat_index: int,
percent_int: int,
subset_repeat_index: int,
) -> None:
train_filenames = {record["filename"] for record in train_records}
subset_filenames = [record["filename"] for record in subset_records]
if len(subset_filenames) != len(set(subset_filenames)):
raise RuntimeError(
f"Duplicate filenames found in subset split={split_repeat_index}, "
f"percent={percent_int}, repeat={subset_repeat_index}."
)
outside_train = sorted(set(subset_filenames) - train_filenames)
if outside_train:
raise RuntimeError(
f"Subset contains filenames outside the base train split for "
f"split={split_repeat_index}, percent={percent_int}, repeat={subset_repeat_index}: {outside_train[:5]}"
)
"""=============================================================================
SQLITE LEDGER
=============================================================================
"""
def require_ledger() -> sqlite3.Connection:
if LEDGER_CONN is None:
raise RuntimeError("Ledger is not initialized.")
return LEDGER_CONN
def ledger_execute(sql: str, params: tuple[Any, ...] = ()) -> sqlite3.Cursor:
conn = require_ledger()
cursor = conn.execute(sql, params)
conn.commit()
return cursor
def setup_ledger(path: Path) -> sqlite3.Connection:
ensure_dir(path.parent)
conn = sqlite3.connect(path)
conn.row_factory = sqlite3.Row
conn.execute("PRAGMA journal_mode=WAL")
conn.execute("PRAGMA synchronous=FULL")
conn.execute(
"""
CREATE TABLE IF NOT EXISTS experiment_meta (
experiment_name TEXT PRIMARY KEY,
config_fingerprint TEXT NOT NULL,
config_json TEXT NOT NULL,
dataset_fingerprint TEXT NOT NULL,
base_seed INTEGER NOT NULL,
created_at TEXT NOT NULL
)
"""
)
conn.execute(
"""
CREATE TABLE IF NOT EXISTS split_manifests (
split_repeat_index INTEGER PRIMARY KEY,
split_seed INTEGER NOT NULL,
manifest_path TEXT NOT NULL,
train_count INTEGER NOT NULL,
val_count INTEGER NOT NULL,
test_count INTEGER NOT NULL,
config_fingerprint TEXT NOT NULL,
dataset_fingerprint TEXT NOT NULL,
created_at TEXT NOT NULL
)
"""
)
conn.execute(
"""
CREATE TABLE IF NOT EXISTS subset_manifests (
split_repeat_index INTEGER NOT NULL,
dataset_percent INTEGER NOT NULL,
subset_repeat_index INTEGER NOT NULL,
subset_seed INTEGER NOT NULL,
manifest_path TEXT NOT NULL,
train_subset_count INTEGER NOT NULL,
config_fingerprint TEXT NOT NULL,
dataset_fingerprint TEXT NOT NULL,
created_at TEXT NOT NULL,
PRIMARY KEY (split_repeat_index, dataset_percent, subset_repeat_index)
)
"""
)
conn.execute(
"""
CREATE TABLE IF NOT EXISTS run_status (
split_repeat_index INTEGER NOT NULL,
dataset_percent INTEGER NOT NULL,
subset_repeat_index INTEGER NOT NULL,
strategy INTEGER NOT NULL,
dataset_fraction REAL NOT NULL,
split_seed INTEGER NOT NULL,
subset_seed INTEGER NOT NULL,
split_manifest_path TEXT NOT NULL,
subset_manifest_path TEXT NOT NULL,
run_dir TEXT NOT NULL,
status TEXT NOT NULL,
stage TEXT NOT NULL,
attempt_count INTEGER NOT NULL DEFAULT 0,
started_at TEXT,
updated_at TEXT NOT NULL,
heartbeat_at TEXT,
completed_at TEXT,
last_epoch INTEGER,
latest_checkpoint_path TEXT,
best_checkpoint_path TEXT,
evaluation_path TEXT,
best_metric_name TEXT,
best_metric_value REAL,
elapsed_seconds REAL,
error_text TEXT,
PRIMARY KEY (split_repeat_index, dataset_percent, subset_repeat_index, strategy)
)
"""
)
conn.execute(
"""
CREATE TABLE IF NOT EXISTS final_metrics (
split_repeat_index INTEGER NOT NULL,
dataset_percent INTEGER NOT NULL,
subset_repeat_index INTEGER NOT NULL,
strategy INTEGER NOT NULL,
metric_name TEXT NOT NULL,
mean REAL NOT NULL,
std REAL,
run_dir TEXT NOT NULL,
evaluation_path TEXT NOT NULL,
PRIMARY KEY (split_repeat_index, dataset_percent, subset_repeat_index, strategy, metric_name)
)
"""
)
conn.commit()
return conn
def fetch_one(sql: str, params: tuple[Any, ...]) -> sqlite3.Row | None:
return require_ledger().execute(sql, params).fetchone()
def load_run_status(key: RunKey) -> sqlite3.Row | None:
return fetch_one(
"""
SELECT *
FROM run_status
WHERE split_repeat_index = ?
AND dataset_percent = ?
AND subset_repeat_index = ?
AND strategy = ?
""",
(key.split_repeat_index, key.dataset_percent, key.subset_repeat_index, key.strategy),
)
def upsert_experiment_meta(
*,
snapshot: dict[str, Any],
config_hash: str,
data_hash: str,
) -> None:
ledger_execute(
"""
INSERT OR REPLACE INTO experiment_meta (
experiment_name,
config_fingerprint,
config_json,
dataset_fingerprint,
base_seed,
created_at
) VALUES (?, ?, ?, ?, ?, ?)
""",
(
FOLDS_EXPERIMENT_NAME,
config_hash,
json.dumps(snapshot, sort_keys=True),
data_hash,
int(base.SEED),
now_utc_iso(),
),
)
def existing_experiment_meta() -> sqlite3.Row | None:
return fetch_one(
"SELECT * FROM experiment_meta WHERE experiment_name = ?",
(FOLDS_EXPERIMENT_NAME,),
)
def ledger_row_count(table_name: str) -> int:
row = require_ledger().execute(f"SELECT COUNT(*) AS count FROM {table_name}").fetchone()
return int(row["count"]) if row is not None else 0
def upsert_split_manifest_row(
*,
split_repeat_index: int,
split_seed: int,
manifest_path: Path,
train_count: int,
val_count: int,
test_count: int,
config_hash: str,
data_hash: str,
) -> None:
ledger_execute(
"""
INSERT OR REPLACE INTO split_manifests (
split_repeat_index,
split_seed,
manifest_path,
train_count,
val_count,
test_count,
config_fingerprint,
dataset_fingerprint,
created_at
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
""",
(
split_repeat_index,
split_seed,
str(manifest_path.resolve()),
train_count,
val_count,
test_count,
config_hash,
data_hash,
now_utc_iso(),
),
)
def upsert_subset_manifest_row(
*,
split_repeat_index: int,
percent_int: int,
subset_repeat_index: int,
subset_seed: int,
manifest_path: Path,
subset_count: int,
config_hash: str,
data_hash: str,
) -> None:
ledger_execute(
"""
INSERT OR REPLACE INTO subset_manifests (
split_repeat_index,
dataset_percent,
subset_repeat_index,
subset_seed,
manifest_path,
train_subset_count,
config_fingerprint,
dataset_fingerprint,
created_at
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
""",
(
split_repeat_index,
percent_int,
subset_repeat_index,
subset_seed,
str(manifest_path.resolve()),
subset_count,
config_hash,
data_hash,
now_utc_iso(),
),
)
def upsert_run_plan_row(
*,
key: RunKey,
dataset_fraction: float,
split_seed: int,
subset_seed: int,
split_manifest: Path,
subset_manifest: Path,
run_dir: Path,
) -> None:
existing = load_run_status(key)
if existing is not None:
return
ledger_execute(
"""
INSERT INTO run_status (
split_repeat_index,
dataset_percent,
subset_repeat_index,
strategy,
dataset_fraction,
split_seed,
subset_seed,
split_manifest_path,
subset_manifest_path,
run_dir,
status,
stage,
attempt_count,
updated_at
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""",
(
key.split_repeat_index,
key.dataset_percent,
key.subset_repeat_index,
key.strategy,
dataset_fraction,
split_seed,
subset_seed,
str(split_manifest.resolve()),
str(subset_manifest.resolve()),
str(run_dir.resolve()),
"planned",
"manifested",
0,
now_utc_iso(),
),
)
def mark_stale_running_as_interrupted() -> None:
ledger_execute(
"""
UPDATE run_status
SET status = 'interrupted',
updated_at = ?
WHERE status = 'running'
""",
(now_utc_iso(),),
)
def mark_run_running(key: RunKey, *, stage: str) -> None:
row = load_run_status(key)
attempt_count = 1 if row is None else int(row["attempt_count"]) + 1
started_at = row["started_at"] if row is not None else None
if not started_at:
started_at = now_utc_iso()
ledger_execute(
"""
UPDATE run_status
SET status = 'running',
stage = ?,
attempt_count = ?,
started_at = ?,
updated_at = ?,
heartbeat_at = ?,
error_text = NULL
WHERE split_repeat_index = ?
AND dataset_percent = ?
AND subset_repeat_index = ?
AND strategy = ?
""",
(
stage,
attempt_count,
started_at,
now_utc_iso(),
now_utc_iso(),
key.split_repeat_index,
key.dataset_percent,
key.subset_repeat_index,
key.strategy,
),
)
def mark_run_stage(key: RunKey, *, stage: str) -> None:
ledger_execute(
"""
UPDATE run_status
SET stage = ?,
status = 'running',
updated_at = ?,
heartbeat_at = ?
WHERE split_repeat_index = ?
AND dataset_percent = ?
AND subset_repeat_index = ?
AND strategy = ?
""",
(
stage,
now_utc_iso(),
now_utc_iso(),
key.split_repeat_index,
key.dataset_percent,
key.subset_repeat_index,
key.strategy,
),
)
def update_run_checkpoint_progress(
key: RunKey,
*,
checkpoint_path: Path,
epoch: int,
best_metric_name: str,
best_metric_value: float,
elapsed_seconds: float,
) -> None:
column_name = "best_checkpoint_path" if checkpoint_path.name == "best.pt" else "latest_checkpoint_path"
sql = f"""
UPDATE run_status
SET {column_name} = ?,
last_epoch = ?,
best_metric_name = ?,
best_metric_value = ?,
elapsed_seconds = ?,
status = 'running',
stage = 'training',
heartbeat_at = ?,
updated_at = ?
WHERE split_repeat_index = ?
AND dataset_percent = ?
AND subset_repeat_index = ?
AND strategy = ?
"""
ledger_execute(
sql,
(
str(checkpoint_path.resolve()),
int(epoch),
str(best_metric_name),
float(best_metric_value),
float(elapsed_seconds),
now_utc_iso(),
now_utc_iso(),
key.split_repeat_index,
key.dataset_percent,
key.subset_repeat_index,
key.strategy,
),
)
def mark_run_failed(key: RunKey, error_text: str) -> None:
ledger_execute(
"""
UPDATE run_status
SET status = 'failed',
updated_at = ?,
error_text = ?
WHERE split_repeat_index = ?
AND dataset_percent = ?
AND subset_repeat_index = ?
AND strategy = ?
""",
(
now_utc_iso(),
error_text,
key.split_repeat_index,
key.dataset_percent,
key.subset_repeat_index,
key.strategy,
),
)
def mark_run_interrupted(key: RunKey) -> None:
ledger_execute(
"""
UPDATE run_status
SET status = 'interrupted',
updated_at = ?
WHERE split_repeat_index = ?
AND dataset_percent = ?
AND subset_repeat_index = ?
AND strategy = ?
""",
(
now_utc_iso(),
key.split_repeat_index,
key.dataset_percent,
key.subset_repeat_index,
key.strategy,
),
)
def ingest_evaluation_into_db(key: RunKey, evaluation_path: Path, run_dir: Path) -> None:
payload = base.load_json(evaluation_path)
metrics = payload.get("metrics", {})
ledger_execute(
"""
DELETE FROM final_metrics
WHERE split_repeat_index = ?
AND dataset_percent = ?
AND subset_repeat_index = ?
AND strategy = ?
""",
(key.split_repeat_index, key.dataset_percent, key.subset_repeat_index, key.strategy),
)
conn = require_ledger()
for metric_name, metric_payload in metrics.items():
conn.execute(
"""
INSERT INTO final_metrics (
split_repeat_index,
dataset_percent,
subset_repeat_index,
strategy,
metric_name,
mean,
std,
run_dir,
evaluation_path
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
""",
(
key.split_repeat_index,
key.dataset_percent,
key.subset_repeat_index,
key.strategy,
str(metric_name),
float(metric_payload.get("mean", 0.0)),
float(metric_payload.get("std")) if metric_payload.get("std") is not None else None,
str(run_dir.resolve()),
str(evaluation_path.resolve()),
),
)
conn.commit()
best_metric_name = str(payload.get("best_metric_name", ""))
best_metric_value = None
if best_metric_name and best_metric_name in metrics:
best_metric_value = float(metrics[best_metric_name]["mean"])
ledger_execute(
"""
UPDATE run_status
SET status = 'completed',
stage = 'done',
evaluation_path = ?,
best_metric_name = COALESCE(?, best_metric_name),
best_metric_value = COALESCE(?, best_metric_value),
completed_at = ?,
updated_at = ?,
heartbeat_at = ?,
error_text = NULL
WHERE split_repeat_index = ?
AND dataset_percent = ?
AND subset_repeat_index = ?
AND strategy = ?
""",
(
str(evaluation_path.resolve()),
best_metric_name or None,
best_metric_value,
now_utc_iso(),
now_utc_iso(),
now_utc_iso(),
key.split_repeat_index,
key.dataset_percent,
key.subset_repeat_index,
key.strategy,
),
)
def completed_run_rows() -> list[sqlite3.Row]:
return list(
require_ledger().execute(
"""
SELECT *
FROM run_status
WHERE status = 'completed'
ORDER BY split_repeat_index, dataset_percent, subset_repeat_index, strategy
"""
).fetchall()
)
def metric_rows_for_completed_runs() -> list[sqlite3.Row]:
return list(
require_ledger().execute(
"""
SELECT
rs.split_repeat_index,
rs.dataset_percent,
rs.subset_repeat_index,
rs.strategy,
rs.run_dir,
rs.split_manifest_path,
rs.subset_manifest_path,
rs.evaluation_path,
fm.metric_name,
fm.mean AS metric_mean,
fm.std AS metric_std
FROM final_metrics fm
JOIN run_status rs
ON rs.split_repeat_index = fm.split_repeat_index
AND rs.dataset_percent = fm.dataset_percent
AND rs.subset_repeat_index = fm.subset_repeat_index
AND rs.strategy = fm.strategy
WHERE rs.status = 'completed'
ORDER BY rs.split_repeat_index, rs.dataset_percent, rs.subset_repeat_index, rs.strategy, fm.metric_name
"""
).fetchall()
)
def export_stats() -> None:
ensure_dir(EXPORTS_DIR)
rows = metric_rows_for_completed_runs()
raw_rows_by_run: dict[tuple[int, int, int, int], dict[str, Any]] = {}
for row in rows:
key = (
int(row["split_repeat_index"]),
int(row["dataset_percent"]),
int(row["subset_repeat_index"]),
int(row["strategy"]),
)
raw_row = raw_rows_by_run.setdefault(
key,
{
"split_repeat_index": int(row["split_repeat_index"]),
"dataset_percent": int(row["dataset_percent"]),
"subset_repeat_index": int(row["subset_repeat_index"]),
"strategy": int(row["strategy"]),
"run_dir": row["run_dir"],
"split_manifest_path": row["split_manifest_path"],
"subset_manifest_path": row["subset_manifest_path"],
"evaluation_path": row["evaluation_path"],
},
)
raw_row[f"{row['metric_name']}_mean"] = float(row["metric_mean"])
raw_row[f"{row['metric_name']}_std"] = (
float(row["metric_std"]) if row["metric_std"] is not None else None
)
raw_rows = list(raw_rows_by_run.values())
raw_rows.sort(
key=lambda item: (
item["split_repeat_index"],
item["dataset_percent"],
item["subset_repeat_index"],
item["strategy"],
)
)
if raw_rows:
raw_fieldnames = sorted({key for row in raw_rows for key in row.keys()})
with tempfile.NamedTemporaryFile("w", encoding="utf-8", newline="", delete=False, dir=str(EXPORTS_DIR)) as handle:
writer = csv.DictWriter(handle, fieldnames=raw_fieldnames)
writer.writeheader()
writer.writerows(raw_rows)
handle.flush()
os.fsync(handle.fileno())
tmp_csv = Path(handle.name)
os.replace(tmp_csv, EXPORTS_DIR / "raw_run_metrics.csv")
atomic_save_json(EXPORTS_DIR / "raw_run_metrics.json", raw_rows)
else:
atomic_write_text(EXPORTS_DIR / "raw_run_metrics.csv", "")
atomic_save_json(EXPORTS_DIR / "raw_run_metrics.json", [])
grouped: dict[tuple[int, int], dict[str, Any]] = {}
for row in rows:
group_key = (int(row["dataset_percent"]), int(row["strategy"]))
bucket = grouped.setdefault(
group_key,
{
"dataset_percent": int(row["dataset_percent"]),
"strategy": int(row["strategy"]),
"_metric_values": {},
},
)
bucket["_metric_values"].setdefault(str(row["metric_name"]), []).append(
{
"mean": float(row["metric_mean"]),
"std": float(row["metric_std"]) if row["metric_std"] is not None else None,
}
)
aggregated_rows: list[dict[str, Any]] = []
for (_percent_int, _strategy), bucket in sorted(grouped.items()):
row = {
"dataset_percent": bucket["dataset_percent"],
"strategy": bucket["strategy"],
}
metric_values: dict[str, list[dict[str, float | None]]] = bucket["_metric_values"]
row["n_runs"] = max((len(values) for values in metric_values.values()), default=0)
for metric_name, values in sorted(metric_values.items()):
means = [value["mean"] for value in values]
stds = [value["std"] for value in values if value["std"] is not None]
row[f"{metric_name}_mean"] = float(base.np.mean(means)) if means else None
row[f"{metric_name}_std"] = float(base.np.std(means)) if means else None
row[f"{metric_name}_within_run_std_mean"] = float(base.np.mean(stds)) if stds else None
aggregated_rows.append(row)
if aggregated_rows:
aggregated_fieldnames = sorted({key for row in aggregated_rows for key in row.keys()})
with tempfile.NamedTemporaryFile("w", encoding="utf-8", newline="", delete=False, dir=str(EXPORTS_DIR)) as handle:
writer = csv.DictWriter(handle, fieldnames=aggregated_fieldnames)
writer.writeheader()
writer.writerows(aggregated_rows)
handle.flush()
os.fsync(handle.fileno())
tmp_csv = Path(handle.name)
os.replace(tmp_csv, EXPORTS_DIR / "aggregated_metrics_by_percent_strategy.csv")
atomic_save_json(EXPORTS_DIR / "aggregated_metrics_by_percent_strategy.json", aggregated_rows)
else:
atomic_write_text(EXPORTS_DIR / "aggregated_metrics_by_percent_strategy.csv", "")
atomic_save_json(EXPORTS_DIR / "aggregated_metrics_by_percent_strategy.json", [])
"""=============================================================================
BASE MODULE PATCHES
=============================================================================
"""
def patched_save_json(path: str | Path, payload: Any) -> None:
atomic_save_json(path, payload)
def _context_matches_percent(ctx: FoldRunContext | None, percent: float) -> bool:
if ctx is None:
return False
return abs(float(percent) - float(ctx.percent_fraction)) <= 1e-12
def patched_percent_root(percent: float) -> Path:
if _context_matches_percent(CURRENT_FOLD_CONTEXT, percent):
return ensure_dir(CURRENT_FOLD_CONTEXT.repeat_root)
return ORIGINAL_PERCENT_ROOT(percent)
def patched_strategy_root_for_percent(
strategy: int,
percent: float,
model_config: base.RuntimeModelConfig | None = None,
) -> Path:
if _context_matches_percent(CURRENT_FOLD_CONTEXT, percent):
return strategy_root_for(strategy, CURRENT_FOLD_CONTEXT, model_config)
return ORIGINAL_STRATEGY_ROOT_FOR_PERCENT(strategy, percent, model_config)
def patched_final_root_for_strategy(
strategy: int,
percent: float,
model_config: base.RuntimeModelConfig | None = None,
) -> Path:
if _context_matches_percent(CURRENT_FOLD_CONTEXT, percent):
return run_dir_for(strategy, CURRENT_FOLD_CONTEXT, model_config)
return ORIGINAL_FINAL_ROOT_FOR_STRATEGY(strategy, percent, model_config)
def patched_study_paths_for(
strategy: int,
percent: float,
model_config: base.RuntimeModelConfig | None = None,
) -> tuple[Path, Path, Path]:
if _context_matches_percent(CURRENT_FOLD_CONTEXT, percent):
return fold_study_paths_for(strategy, CURRENT_FOLD_CONTEXT, model_config)
return ORIGINAL_STUDY_PATHS_FOR(strategy, percent, model_config)
def patched_save_checkpoint(
path: Path,
*,
run_type: str,
model: base.nn.Module,
optimizer: torch.optim.Optimizer,
scheduler: Any,
scaler: Any,
epoch: int,
best_metric_value: float,
best_metric_name: str,
run_config: dict[str, Any],
epoch_metrics: dict[str, Any],
patience_counter: int,
elapsed_seconds: float,
history: list[dict[str, Any]] | None = None,
log_alpha: torch.Tensor | None = None,
alpha_optimizer: torch.optim.Optimizer | None = None,
resume_source: dict[str, Any] | None = None,
) -> None:
payload = {
"run_type": run_type,
"epoch": epoch,
"model_state_dict": base._unwrap_compiled(model).state_dict(),
"optimizer_state_dict": optimizer.state_dict(),
"best_metric_name": best_metric_name,
"best_metric_value": best_metric_value,
"patience_counter": int(patience_counter),
"elapsed_seconds": float(elapsed_seconds),
"run_config": run_config,
"config": run_config,
"epoch_metrics": epoch_metrics,
}
if history is not None:
payload["history"] = [dict(row) for row in history]
if scheduler is not None:
payload["scheduler_state_dict"] = scheduler.state_dict()
if scaler is not None:
payload["scaler_state_dict"] = scaler.state_dict()
if log_alpha is not None:
payload["log_alpha"] = float(log_alpha.detach().item())
if alpha_optimizer is not None:
payload["alpha_optimizer_state_dict"] = alpha_optimizer.state_dict()
if resume_source is not None:
payload["resume_source"] = resume_source
base.validate_checkpoint_payload(
Path(path),
payload,
required_keys=base.checkpoint_required_keys(
optimizer=optimizer,
scheduler=scheduler,
scaler=scaler,
log_alpha=log_alpha,
alpha_optimizer=alpha_optimizer,
require_run_metadata=True,
),
expected_run_type=run_type,
)
atomic_torch_save(path, payload)
base.write_checkpoint_manifest(path, payload)
if run_type != "final" or CURRENT_FOLD_CONTEXT is None:
return
run_key = RunKey(
split_repeat_index=CURRENT_FOLD_CONTEXT.split_repeat_index,
dataset_percent=CURRENT_FOLD_CONTEXT.percent_int,
subset_repeat_index=CURRENT_FOLD_CONTEXT.subset_repeat_index,
strategy=int(run_config["strategy"]),
)
update_run_checkpoint_progress(
run_key,
checkpoint_path=Path(path),
epoch=int(epoch),
best_metric_name=str(best_metric_name),
best_metric_value=float(best_metric_value),
elapsed_seconds=float(elapsed_seconds),
)
def patched_run_evaluation_for_run(
*,
strategy: int,
percent: float,
bundle: base.DataBundle,
run_dir: Path,
strategy2_checkpoint_path: str | Path | None = None,
) -> dict[str, dict[str, float]]:
if CURRENT_FOLD_CONTEXT is not None:
run_key = RunKey(
split_repeat_index=CURRENT_FOLD_CONTEXT.split_repeat_index,
dataset_percent=CURRENT_FOLD_CONTEXT.percent_int,
subset_repeat_index=CURRENT_FOLD_CONTEXT.subset_repeat_index,
strategy=int(strategy),
)
mark_run_stage(run_key, stage="evaluating")
return ORIGINAL_RUN_EVALUATION_FOR_RUN(
strategy=strategy,
percent=percent,
bundle=bundle,
run_dir=run_dir,
strategy2_checkpoint_path=strategy2_checkpoint_path,
)
def install_base_patches() -> None:
base.save_json = patched_save_json
base.percent_root = patched_percent_root
base.strategy_root_for_percent = patched_strategy_root_for_percent
base.final_root_for_strategy = patched_final_root_for_strategy
base.study_paths_for = patched_study_paths_for
base.save_checkpoint = patched_save_checkpoint
base.run_evaluation_for_run = patched_run_evaluation_for_run
base.RESUME_IDENTITY_KEYS = BASE_RESUME_IDENTITY_KEYS + (
"folds_experiment_name",
"split_repeat_index",
"subset_repeat_index",
"split_seed",
"subset_seed",
"base_split_manifest_path",
"subset_manifest_path",
)
if RESUME_FOLDS and base.RUN_OPTUNA:
base.LOAD_EXISTING_STUDIES = True
@contextmanager
def activate_context(ctx: FoldRunContext) -> Iterator[None]:
global CURRENT_FOLD_CONTEXT
previous = CURRENT_FOLD_CONTEXT
CURRENT_FOLD_CONTEXT = ctx
try:
yield
finally:
CURRENT_FOLD_CONTEXT = previous
"""=============================================================================
EXPERIMENT PLAN MATERIALIZATION
=============================================================================
"""
def create_split_manifest_payload(
*,
split_repeat_index: int,
split_seed: int,
base_splits: dict[str, list[dict[str, str]]],
config_hash: str,
data_hash: str,
) -> dict[str, Any]:
return {
"experiment_name": FOLDS_EXPERIMENT_NAME,
"config_fingerprint": config_hash,
"dataset_fingerprint": data_hash,
"dataset_name": base.current_dataset_name(),
"dataset_split_policy": (
base.current_busi_with_classes_split_policy()
if base.current_dataset_name() == "BUSI_with_classes"
else None
),
"split_type": base.SPLIT_TYPE,
"split_repeat_index": split_repeat_index,
"split_seed": split_seed,
"percent_sampling_mode": current_percent_sampling_mode(),
"base_splits": {
split_name: [dict(record) for record in records]
for split_name, records in base_splits.items()
},
"counts": {split_name: len(records) for split_name, records in base_splits.items()},
"class_distributions": {
split_name: base.compute_class_distribution(records)
for split_name, records in base_splits.items()
},
}
def create_subset_manifest_payload(
*,
split_repeat_index: int,
split_seed: int,
percent_int: int,
percent_fraction: float,
subset_repeat_index: int,
subset_seed: int,
split_manifest: Path,
base_splits: dict[str, list[dict[str, str]]],
subset_records: list[dict[str, str]],
subset_sampling_source: str,
sampling_chain_dataset_percents: list[int],
config_hash: str,
data_hash: str,
) -> dict[str, Any]:
return {
"experiment_name": FOLDS_EXPERIMENT_NAME,
"config_fingerprint": config_hash,
"dataset_fingerprint": data_hash,
"dataset_name": base.current_dataset_name(),
"dataset_split_policy": (
base.current_busi_with_classes_split_policy()
if base.current_dataset_name() == "BUSI_with_classes"
else None
),
"split_type": base.SPLIT_TYPE,
"split_repeat_index": split_repeat_index,
"split_seed": split_seed,
"dataset_percent": percent_int,
"dataset_fraction": percent_fraction,
"subset_repeat_index": subset_repeat_index,
"subset_seed": subset_seed,
"percent_sampling_mode": current_percent_sampling_mode(),
"subset_sampling_source": subset_sampling_source,
"sampling_chain_dataset_percents": [int(value) for value in sampling_chain_dataset_percents],
"parent_split_manifest_path": str(split_manifest.resolve()),
"train_records": [dict(record) for record in subset_records],
"val_records": [dict(record) for record in base_splits["val"]],
"test_records": [dict(record) for record in base_splits["test"]],
"base_train_records": [dict(record) for record in base_splits["train"]],
"counts": {
"base_train": len(base_splits["train"]),
"train_subset": len(subset_records),
"val": len(base_splits["val"]),
"test": len(base_splits["test"]),
},
"class_distributions": {
"base_train": base.compute_class_distribution(base_splits["train"]),
"train_subset": base.compute_class_distribution(subset_records),
"val": base.compute_class_distribution(base_splits["val"]),
"test": base.compute_class_distribution(base_splits["test"]),
},
}
def materialize_experiment_plan(
*,
sample_records: list[dict[str, str]],
model_config: base.RuntimeModelConfig,
) -> None:
ensure_dir(EXPERIMENT_ROOT)
ensure_dir(SPLIT_MANIFESTS_DIR)
ensure_dir(SUBSET_MANIFESTS_DIR)
ensure_dir(EXPORTS_DIR)
snapshot = config_snapshot(model_config)
config_hash = config_fingerprint(snapshot)
data_hash = dataset_fingerprint(sample_records)
sampling_mode = current_percent_sampling_mode()
upsert_experiment_meta(snapshot=snapshot, config_hash=config_hash, data_hash=data_hash)
for split_repeat_index in all_split_repeat_indices():
split_seed = fold_seed(f"split::{split_repeat_index}")
base_splits = build_base_split_for_repeat(sample_records, split_seed)
validate_base_split(base_splits, split_repeat_index=split_repeat_index)
split_manifest = split_manifest_path(split_repeat_index)
split_payload = create_split_manifest_payload(
split_repeat_index=split_repeat_index,
split_seed=split_seed,
base_splits=base_splits,
config_hash=config_hash,
data_hash=data_hash,
)
atomic_save_json(split_manifest, split_payload)
upsert_split_manifest_row(
split_repeat_index=split_repeat_index,
split_seed=split_seed,
manifest_path=split_manifest,
train_count=len(base_splits["train"]),
val_count=len(base_splits["val"]),
test_count=len(base_splits["test"]),
config_hash=config_hash,
data_hash=data_hash,
)
if sampling_mode == "independent":
for spec in percent_specs():
for subset_repeat_index in range(1, int(spec.repeat_count) + 1):
subset_seed = fold_seed(
f"subset::{split_repeat_index}::{spec.percent_int}::{subset_repeat_index}"
)
subset_records = build_subset_for_repeat(
base_splits["train"],
percent_fraction=spec.fraction,
subset_seed=subset_seed,
)
validate_subset_records(
base_splits["train"],
subset_records,
split_repeat_index=split_repeat_index,
percent_int=spec.percent_int,
subset_repeat_index=subset_repeat_index,
)
subset_manifest = subset_manifest_path(
split_repeat_index,
spec.percent_int,
subset_repeat_index,
)
subset_payload = create_subset_manifest_payload(
split_repeat_index=split_repeat_index,
split_seed=split_seed,
percent_int=spec.percent_int,
percent_fraction=spec.fraction,
subset_repeat_index=subset_repeat_index,
subset_seed=subset_seed,
split_manifest=split_manifest,
base_splits=base_splits,
subset_records=subset_records,
subset_sampling_source="independent",
sampling_chain_dataset_percents=[spec.percent_int],
config_hash=config_hash,
data_hash=data_hash,
)
atomic_save_json(subset_manifest, subset_payload)
upsert_subset_manifest_row(
split_repeat_index=split_repeat_index,
percent_int=spec.percent_int,
subset_repeat_index=subset_repeat_index,
subset_seed=subset_seed,
manifest_path=subset_manifest,
subset_count=len(subset_records),
config_hash=config_hash,
data_hash=data_hash,
)
ctx = FoldRunContext(
split_repeat_index=split_repeat_index,
subset_repeat_index=subset_repeat_index,
percent_int=spec.percent_int,
percent_fraction=spec.fraction,
split_seed=split_seed,
subset_seed=subset_seed,
repeat_root=repeat_root(split_repeat_index, spec.percent_int, subset_repeat_index),
split_manifest_path=split_manifest,
subset_manifest_path=subset_manifest,
)
for strategy in base.STRATEGIES:
upsert_run_plan_row(
key=RunKey(
split_repeat_index=ctx.split_repeat_index,
dataset_percent=ctx.percent_int,
subset_repeat_index=ctx.subset_repeat_index,
strategy=int(strategy),
),
dataset_fraction=ctx.percent_fraction,
split_seed=ctx.split_seed,
subset_seed=ctx.subset_seed,
split_manifest=ctx.split_manifest_path,
subset_manifest=ctx.subset_manifest_path,
run_dir=run_dir_for(int(strategy), ctx, model_config),
)
continue
max_subset_repeat_index = max(spec.repeat_count for spec in percent_specs())
for subset_repeat_index in range(1, max_subset_repeat_index + 1):
active_specs = active_specs_for_subset_repeat(subset_repeat_index)
if not active_specs:
continue
subset_seed = fold_seed(f"subset::{split_repeat_index}::repeat::{subset_repeat_index}")
subset_chain = build_incremental_subset_chain(
base_splits["train"],
active_specs=active_specs,
subset_seed=subset_seed,
)
chain_dataset_percents = [spec.percent_int for spec in active_specs]
for spec in active_specs:
subset_records = subset_chain[base.percent_label(spec.fraction)]
validate_subset_records(
base_splits["train"],
subset_records,
split_repeat_index=split_repeat_index,
percent_int=spec.percent_int,
subset_repeat_index=subset_repeat_index,
)
subset_manifest = subset_manifest_path(
split_repeat_index,
spec.percent_int,
subset_repeat_index,
)
subset_payload = create_subset_manifest_payload(
split_repeat_index=split_repeat_index,
split_seed=split_seed,
percent_int=spec.percent_int,
percent_fraction=spec.fraction,
subset_repeat_index=subset_repeat_index,
subset_seed=subset_seed,
split_manifest=split_manifest,
base_splits=base_splits,
subset_records=subset_records,
subset_sampling_source="incremental_chain",
sampling_chain_dataset_percents=chain_dataset_percents,
config_hash=config_hash,
data_hash=data_hash,
)
atomic_save_json(subset_manifest, subset_payload)
upsert_subset_manifest_row(
split_repeat_index=split_repeat_index,
percent_int=spec.percent_int,
subset_repeat_index=subset_repeat_index,
subset_seed=subset_seed,
manifest_path=subset_manifest,
subset_count=len(subset_records),
config_hash=config_hash,
data_hash=data_hash,
)
ctx = FoldRunContext(
split_repeat_index=split_repeat_index,
subset_repeat_index=subset_repeat_index,
percent_int=spec.percent_int,
percent_fraction=spec.fraction,
split_seed=split_seed,
subset_seed=subset_seed,
repeat_root=repeat_root(split_repeat_index, spec.percent_int, subset_repeat_index),
split_manifest_path=split_manifest,
subset_manifest_path=subset_manifest,
)
for strategy in base.STRATEGIES:
upsert_run_plan_row(
key=RunKey(
split_repeat_index=ctx.split_repeat_index,
dataset_percent=ctx.percent_int,
subset_repeat_index=ctx.subset_repeat_index,
strategy=int(strategy),
),
dataset_fraction=ctx.percent_fraction,
split_seed=ctx.split_seed,
subset_seed=ctx.subset_seed,
split_manifest=ctx.split_manifest_path,
subset_manifest=ctx.subset_manifest_path,
run_dir=run_dir_for(int(strategy), ctx, model_config),
)
def validate_or_create_experiment(
*,
sample_records: list[dict[str, str]],
model_config: base.RuntimeModelConfig,
) -> None:
meta = existing_experiment_meta()
if not RESUME_FOLDS:
if meta is not None:
raise RuntimeError(
f"RESUME_FOLDS=False requires a fresh experiment root, but {EXPERIMENT_ROOT} already exists."
)
materialize_experiment_plan(sample_records=sample_records, model_config=model_config)
return
if meta is None:
if ledger_row_count("split_manifests") > 0 or ledger_row_count("run_status") > 0:
raise RuntimeError(
f"Experiment DB {EXPERIMENT_DB_PATH} contains run state but is missing experiment metadata."
)
materialize_experiment_plan(sample_records=sample_records, model_config=model_config)
return
current_snapshot = config_snapshot(model_config)
current_hash = config_fingerprint(current_snapshot)
current_data_hash = dataset_fingerprint(sample_records)
if str(meta["config_fingerprint"]) != current_hash:
raise RuntimeError(
f"Existing experiment config fingerprint does not match current configuration for {EXPERIMENT_ROOT}."
)
if str(meta["dataset_fingerprint"]) != current_data_hash:
raise RuntimeError(
f"Existing experiment dataset fingerprint does not match current dataset contents for {EXPERIMENT_ROOT}."
)
"""=============================================================================
RUNTIME BUNDLE CONSTRUCTION
=============================================================================
"""
def load_context(split_repeat_index: int, percent_int: int, subset_repeat_index: int) -> FoldRunContext:
split_payload = base.load_json(split_manifest_path(split_repeat_index))
subset_payload = base.load_json(subset_manifest_path(split_repeat_index, percent_int, subset_repeat_index))
return FoldRunContext(
split_repeat_index=split_repeat_index,
subset_repeat_index=subset_repeat_index,
percent_int=percent_int,
percent_fraction=float(subset_payload["dataset_fraction"]),
split_seed=int(split_payload["split_seed"]),
subset_seed=int(subset_payload["subset_seed"]),
repeat_root=repeat_root(split_repeat_index, percent_int, subset_repeat_index),
split_manifest_path=split_manifest_path(split_repeat_index),
subset_manifest_path=subset_manifest_path(split_repeat_index, percent_int, subset_repeat_index),
)
def build_fold_data_bundle(ctx: FoldRunContext) -> base.DataBundle:
split_payload = base.load_json(ctx.split_manifest_path)
subset_payload = base.load_json(ctx.subset_manifest_path)
dataset_root = Path(base.current_dataset_dirs()[0]).parent.resolve()
normalization_cache_path = (
ctx.repeat_root
/ f"norm_stats_{base.normalization_cache_tag()}_{base.SPLIT_TYPE}_{ctx.percent_int:03d}pct_repeat{ctx.subset_repeat_index:02d}.json"
)
train_records = [dict(record) for record in subset_payload["train_records"]]
val_records = [dict(record) for record in subset_payload["val_records"]]
test_records = [dict(record) for record in subset_payload["test_records"]]
base_train_records = [dict(record) for record in subset_payload["base_train_records"]]
base_train_class_distribution = base.compute_class_distribution(base_train_records)
train_class_distribution = base.compute_class_distribution(train_records)
val_class_distribution = base.compute_class_distribution(val_records)
test_class_distribution = base.compute_class_distribution(test_records)
base.print_loaded_class_distribution(
split_type=base.SPLIT_TYPE,
train_subset_key=str(ctx.percent_int),
base_train_records=base_train_records,
train_records=train_records,
val_records=val_records,
test_records=test_records,
)
global_mean, global_std, normalization_source = base.compute_busi_statistics(
dataset_root=dataset_root,
sample_records=train_records,
cache_path=normalization_cache_path,
)
payload = {
"dataset_name": base.current_dataset_name(),
"dataset_split_policy": (
base.current_busi_with_classes_split_policy()
if base.current_dataset_name() == "BUSI_with_classes"
else None
),
"dataset_splits_path": str(ctx.split_manifest_path.resolve()),
"dataset_root": str(dataset_root),
"split_source": "repeated_holdout_manifest",
"split_type": base.SPLIT_TYPE,
"percent_sampling_mode": str(
subset_payload.get("percent_sampling_mode", split_payload.get("percent_sampling_mode", "independent"))
),
"dataset_percent": ctx.percent_fraction,
"train_subset_key": str(ctx.percent_int),
"train_subset_variant": int(ctx.subset_repeat_index),
"train_subset_source": str(subset_payload.get("subset_sampling_source", "repeated_holdout_repeat")),
"selected_split_manifest_path": str(ctx.subset_manifest_path.resolve()),
"sampling_chain_dataset_percents": [
int(value) for value in subset_payload.get("sampling_chain_dataset_percents", [ctx.percent_int])
],
"base_train_count": len(base_train_records),
"train_count": len(train_records),
"val_count": len(val_records),
"test_count": len(test_records),
"base_train_class_distribution": base_train_class_distribution,
"train_class_distribution": train_class_distribution,
"val_class_distribution": val_class_distribution,
"test_class_distribution": test_class_distribution,
"val_test_frozen": True,
"leakage_check": "passed",
"global_mean": global_mean,
"global_std": global_std,
"normalization_cache_path": str(normalization_cache_path.resolve()),
"normalization_source": normalization_source,
"split_repeat_index": ctx.split_repeat_index,
"subset_repeat_index": ctx.subset_repeat_index,
"split_seed": ctx.split_seed,
"subset_seed": ctx.subset_seed,
"base_split_manifest_path": str(ctx.split_manifest_path.resolve()),
"subset_manifest_path": str(ctx.subset_manifest_path.resolve()),
"folds_experiment_name": FOLDS_EXPERIMENT_NAME,
"folds_experiment_root": str(EXPERIMENT_ROOT.resolve()),
}
base.print_split_summary(payload)
base.print_normalization_summary(payload)
train_ds = base.BUSIDataset(
train_records,
dataset_root,
global_mean,
global_std,
preload=base.PRELOAD_TO_RAM,
augment=True,
split_name=f"train {base.SPLIT_TYPE} {ctx.percent_int}% split{ctx.split_repeat_index:03d}",
)
val_ds = base.BUSIDataset(
val_records,
dataset_root,
global_mean,
global_std,
preload=base.PRELOAD_TO_RAM,
augment=False,
split_name=f"val {base.SPLIT_TYPE} split{ctx.split_repeat_index:03d}",
)
test_ds = base.BUSIDataset(
test_records,
dataset_root,
global_mean,
global_std,
preload=base.PRELOAD_TO_RAM,
augment=False,
split_name=f"test {base.SPLIT_TYPE} split{ctx.split_repeat_index:03d}",
)
bundle = base.DataBundle(
percent=ctx.percent_fraction,
split_payload=payload,
train_ds=train_ds,
val_ds=val_ds,
test_ds=test_ds,
train_loader=base.make_loader(
train_ds,
shuffle=True,
loader_tag=(
f"{base.SPLIT_TYPE}:{ctx.percent_int}:split{ctx.split_repeat_index:03d}:"
f"repeat{ctx.subset_repeat_index:02d}:train"
),
),
val_loader=base.make_loader(
val_ds,
shuffle=False,
loader_tag=(
f"{base.SPLIT_TYPE}:{ctx.percent_int}:split{ctx.split_repeat_index:03d}:"
f"repeat{ctx.subset_repeat_index:02d}:val"
),
),
test_loader=base.make_loader(
test_ds,
shuffle=False,
loader_tag=(
f"{base.SPLIT_TYPE}:{ctx.percent_int}:split{ctx.split_repeat_index:03d}:"
f"repeat{ctx.subset_repeat_index:02d}:test"
),
),
)
base.print_preload_summary(bundle)
return bundle
def release_bundle(bundle: base.DataBundle | None) -> None:
if bundle is None:
return
del bundle
gc.collect()
base.run_cuda_cleanup(context="bundle release")
def checkpoint_candidates(run_dir: Path) -> list[Path]:
return [
run_dir / "checkpoints" / "latest.pt",
run_dir / "checkpoints" / "best.pt",
]
def resolve_resume_checkpoint(run_dir: Path) -> Path | None:
for candidate in checkpoint_candidates(run_dir):
if candidate.exists():
return candidate
return None
"""=============================================================================
RUN EXECUTION
=============================================================================
"""
def strategy_requires_strategy2_checkpoint(strategy: int) -> bool:
return strategy in (4, 5) or (
base.EXECUTION_MODE == "train_eval" and strategy == 3 and base.STRATEGY3_BOOTSTRAP_FROM_STRATEGY2
)
def fold_param_metadata(ctx: FoldRunContext) -> dict[str, Any]:
subset_payload = base.load_json(ctx.subset_manifest_path)
return {
"folds_experiment_name": FOLDS_EXPERIMENT_NAME,
"split_repeat_index": int(ctx.split_repeat_index),
"subset_repeat_index": int(ctx.subset_repeat_index),
"split_seed": int(ctx.split_seed),
"subset_seed": int(ctx.subset_seed),
"percent_sampling_mode": str(subset_payload.get("percent_sampling_mode", current_percent_sampling_mode())),
"subset_sampling_source": str(subset_payload.get("subset_sampling_source", "independent")),
"base_split_manifest_path": str(ctx.split_manifest_path.resolve()),
"subset_manifest_path": str(ctx.subset_manifest_path.resolve()),
}
def finalize_run_from_artifacts(key: RunKey, run_dir: Path) -> bool:
evaluation_path = run_dir / "evaluation.json"
if not evaluation_path.exists():
return False
ingest_evaluation_into_db(key, evaluation_path, run_dir)
export_stats()
return True
def execute_final_run(
*,
strategy: int,
ctx: FoldRunContext,
bundle: base.DataBundle,
model_config: base.RuntimeModelConfig,
) -> None:
run_key = RunKey(
split_repeat_index=ctx.split_repeat_index,
dataset_percent=ctx.percent_int,
subset_repeat_index=ctx.subset_repeat_index,
strategy=int(strategy),
)
row = load_run_status(run_key)
if row is None:
raise RuntimeError(f"Run plan row is missing for {run_key}.")
if str(row["status"]) == "completed":
return
if str(row["status"]) == "failed":
print(
f"[Repeated Holdout] Skipping failed run "
f"{run_identity_label(strategy=strategy, percent=ctx.percent_fraction, split_payload=bundle.split_payload)}."
)
return
run_dir = run_dir_for(strategy, ctx, model_config)
if finalize_run_from_artifacts(run_key, run_dir):
return
strategy2_checkpoint_path: str | Path | None = None
run_name = run_identity_label(strategy=strategy, percent=ctx.percent_fraction, split_payload=bundle.split_payload)
with activate_context(ctx):
base.banner(f"REPEATED HOLDOUT RUN | {run_name}")
if strategy_requires_strategy2_checkpoint(strategy):
strategy2_checkpoint_path = base.resolve_strategy2_checkpoint_path(
strategy,
ctx.percent_fraction,
model_config,
)
if base.EXECUTION_MODE == "eval_only":
mark_run_running(run_key, stage="evaluating")
ORIGINAL_RUN_EVALUATION_FOR_RUN(
strategy=strategy,
percent=ctx.percent_fraction,
bundle=bundle,
run_dir=run_dir,
strategy2_checkpoint_path=strategy2_checkpoint_path,
)
finalize_run_from_artifacts(run_key, run_dir)
return
summary_path = run_dir / "summary.json"
if summary_path.exists() and not (run_dir / "evaluation.json").exists():
mark_run_running(run_key, stage="evaluating")
ORIGINAL_RUN_EVALUATION_FOR_RUN(
strategy=strategy,
percent=ctx.percent_fraction,
bundle=bundle,
run_dir=run_dir,
strategy2_checkpoint_path=strategy2_checkpoint_path,
)
finalize_run_from_artifacts(run_key, run_dir)
return
if base.RUN_SMOKE_TEST:
base.maybe_run_strategy_smoke_test(
strategy=strategy,
model_config=model_config,
bundle=bundle,
strategy2_checkpoint_path=strategy2_checkpoint_path,
)
params = base.resolve_job_params(
strategy,
ctx.percent_fraction,
bundle,
model_config=model_config,
strategy2_checkpoint_path=strategy2_checkpoint_path,
)
params = {**params, **fold_param_metadata(ctx)}
resume_checkpoint_path = None
if str(row["status"]) in {"interrupted", "running"}:
resume_checkpoint_path = resolve_resume_checkpoint(run_dir)
mark_run_running(run_key, stage="training")
base.run_single_job(
strategy=strategy,
model_config=model_config,
bundle=bundle,
run_dir=run_dir,
params=params,
max_epochs=base.strategy_epochs(strategy),
trial=None,
strategy2_checkpoint_path=strategy2_checkpoint_path,
resume_checkpoint_path=resume_checkpoint_path,
)
finalize_run_from_artifacts(run_key, run_dir)
def reconcile_existing_artifacts(ctx: FoldRunContext, strategy: int, model_config: base.RuntimeModelConfig) -> None:
run_key = RunKey(
split_repeat_index=ctx.split_repeat_index,
dataset_percent=ctx.percent_int,
subset_repeat_index=ctx.subset_repeat_index,
strategy=int(strategy),
)
row = load_run_status(run_key)
if row is None or str(row["status"]) == "completed":
return
run_dir = run_dir_for(strategy, ctx, model_config)
if finalize_run_from_artifacts(run_key, run_dir):
return
if (run_dir / "summary.json").exists():
mark_run_interrupted(run_key)
mark_run_stage(run_key, stage="evaluating")
return
if resolve_resume_checkpoint(run_dir) is not None:
mark_run_interrupted(run_key)
def maybe_reset_study_artifacts(model_config: base.RuntimeModelConfig) -> None:
if not base.RESET_ALL_STUDIES_EACH_RUN or not base.RUN_OPTUNA:
return
if RESUME_FOLDS:
print("[Repeated Holdout] RESET_ALL_STUDIES_EACH_RUN ignored because RESUME_FOLDS=True.")
return
for ctx in iter_manifested_contexts(split_repeat_indices_to_run()):
with activate_context(ctx):
for strategy in base.STRATEGIES:
base.reset_study_artifacts(strategy, ctx.percent_fraction, model_config=model_config)
def run_overfit_mode(model_config: base.RuntimeModelConfig) -> int:
base.banner("REPEATED HOLDOUT OVERFIT TEST MODE")
for ctx in iter_manifested_contexts(split_repeat_indices_to_run()):
bundle = build_fold_data_bundle(ctx)
try:
with activate_context(ctx):
for strategy in base.STRATEGIES:
strategy2_checkpoint_path = None
if strategy in (4, 5) or (
strategy == 3 and base.STRATEGY3_BOOTSTRAP_FROM_STRATEGY2
):
strategy2_checkpoint_path = base.resolve_strategy2_checkpoint_path(
strategy,
ctx.percent_fraction,
model_config,
)
base.run_overfit_test(
strategy=strategy,
model_config=model_config,
bundle=bundle,
overfit_root=overfit_root_for(strategy, ctx, model_config),
strategy2_checkpoint_path=strategy2_checkpoint_path,
)
finally:
release_bundle(bundle)
return 0
def run_pass_for_statuses(
statuses: set[str],
*,
model_config: base.RuntimeModelConfig,
) -> None:
for ctx in iter_manifested_contexts(split_repeat_indices_to_run()):
pending_strategies = []
for strategy in base.STRATEGIES:
run_key = RunKey(
split_repeat_index=ctx.split_repeat_index,
dataset_percent=ctx.percent_int,
subset_repeat_index=ctx.subset_repeat_index,
strategy=int(strategy),
)
row = load_run_status(run_key)
if row is not None and str(row["status"]) in statuses:
pending_strategies.append(int(strategy))
if not pending_strategies:
continue
bundle = build_fold_data_bundle(ctx)
try:
for strategy in pending_strategies:
run_key = RunKey(
split_repeat_index=ctx.split_repeat_index,
dataset_percent=ctx.percent_int,
subset_repeat_index=ctx.subset_repeat_index,
strategy=int(strategy),
)
row = load_run_status(run_key)
if row is None or str(row["status"]) == "completed":
continue
try:
execute_final_run(
strategy=strategy,
ctx=ctx,
bundle=bundle,
model_config=model_config,
)
except KeyboardInterrupt:
mark_run_interrupted(run_key)
raise
except Exception:
error_text = traceback.format_exc()
mark_run_failed(run_key, error_text)
print(error_text)
finally:
release_bundle(bundle)
"""=============================================================================
MAIN
=============================================================================
"""
def run_repeated_holdout_main() -> int:
global LEDGER_CONN
validate_repeated_holdout_settings()
if not str(FOLDS_EXPERIMENT_NAME).strip():
raise ValueError("FOLDS_EXPERIMENT_NAME must be non-empty.")
if base.SPLIT_TYPE != "80_10_10":
raise ValueError(
f"RUNNER_FOLDS.py currently requires SPLIT_TYPE='80_10_10', got {base.SPLIT_TYPE!r}."
)
install_base_patches()
base.SAVE_LATEST_EVERY_EPOCH = True
base.set_global_seed(base.SEED)
model_config = base.current_model_config()
fold_experiment_summary(model_config)
sample_records, _dataset_root = select_sample_records()
if not RESUME_FOLDS and EXPERIMENT_ROOT.exists():
raise RuntimeError(
f"RESUME_FOLDS=False requires a fresh experiment root, but {EXPERIMENT_ROOT} already exists."
)
if RESUME_FOLDS and not EXPERIMENT_DB_PATH.exists() and EXPERIMENT_ROOT.exists() and any(EXPERIMENT_ROOT.iterdir()):
raise RuntimeError(
f"Experiment root {EXPERIMENT_ROOT} already exists without a valid SQLite ledger at {EXPERIMENT_DB_PATH}. "
"Refusing to attach to ambiguous state."
)
LEDGER_CONN = setup_ledger(EXPERIMENT_DB_PATH)
try:
validate_or_create_experiment(sample_records=sample_records, model_config=model_config)
mark_stale_running_as_interrupted()
for ctx in iter_manifested_contexts(split_repeat_indices_to_run()):
for strategy in base.STRATEGIES:
reconcile_existing_artifacts(ctx, int(strategy), model_config)
export_stats()
maybe_reset_study_artifacts(model_config)
if base.RUN_OVERFIT_TEST:
return run_overfit_mode(model_config)
run_pass_for_statuses({"interrupted", "running"}, model_config=model_config)
run_pass_for_statuses({"planned"}, model_config=model_config)
export_stats()
base.banner("REPEATED HOLDOUT COMPLETE")
print(f"Experiment root : {EXPERIMENT_ROOT}")
print(f"Experiment DB : {EXPERIMENT_DB_PATH}")
print(f"Raw metrics export : {EXPORTS_DIR / 'raw_run_metrics.csv'}")
print(f"Aggregate export : {EXPORTS_DIR / 'aggregated_metrics_by_percent_strategy.csv'}")
return 0
finally:
if LEDGER_CONN is not None:
LEDGER_CONN.close()
LEDGER_CONN = None
def run_single_run_main() -> int:
global DATASET_PERCENTS
banner("MLR ALL STRATEGIES BAYES RUNNER")
DATASET_PERCENTS = normalize_dataset_percents(DATASET_PERCENTS)
set_global_seed(SEED)
model_config = current_model_config()
dataset_name = current_dataset_name()
images_dir, annotations_dir = current_dataset_dirs()
if EXECUTION_MODE not in {"train_eval", "eval_only"}:
raise ValueError(f"EXECUTION_MODE must be 'train_eval' or 'eval_only', got {EXECUTION_MODE!r}")
if SPLIT_TYPE not in SUPPORTED_SPLIT_TYPES:
raise ValueError(f"SPLIT_TYPE must be one of {SUPPORTED_SPLIT_TYPES}, got {SPLIT_TYPE!r}")
if not images_dir.exists() or not annotations_dir.exists():
raise FileNotFoundError(
f"Expected dataset directories for {dataset_name} under {DATA_ROOT}: "
f"images={images_dir}, masks={annotations_dir}"
)
ensure_specific_checkpoint_scope("EVAL_CHECKPOINT_MODE", EVAL_CHECKPOINT_MODE)
ensure_specific_checkpoint_scope("STRATEGY2_CHECKPOINT_MODE", STRATEGY2_CHECKPOINT_MODE)
ensure_specific_checkpoint_scope("TRAIN_RESUME_MODE", TRAIN_RESUME_MODE)
print_environment_summary(model_config)
split_registry, split_source = load_or_create_dataset_splits(
images_dir=images_dir,
annotations_dir=annotations_dir,
split_json_path=current_dataset_splits_json_path(),
train_fractions=DATASET_PERCENTS,
seed=SEED,
)
bundles: dict[float, DataBundle] = {}
for percent in DATASET_PERCENTS:
bundles[percent] = build_data_bundle(percent, split_registry, split_source)
if RUN_OVERFIT_TEST:
run_configured_overfit_tests(bundles, model_config=model_config)
banner("OVERFIT TESTS COMPLETE")
return 0
if RESET_ALL_STUDIES_EACH_RUN:
if RUN_OPTUNA:
banner("RESETTING OPTUNA STUDIES")
for strategy in STRATEGIES:
for percent in DATASET_PERCENTS:
reset_study_artifacts(strategy, percent, model_config=model_config)
else:
print("[Optuna Reset] Skipped because RUN_OPTUNA=False.")
try:
for percent in DATASET_PERCENTS:
banner(f"PERCENT STAGE | {percent_text(percent)}")
bundle = bundles[percent]
for strategy in STRATEGIES:
strategy2_checkpoint_path = None
if strategy in (4, 5) or (
EXECUTION_MODE == "train_eval" and strategy == 3 and STRATEGY3_BOOTSTRAP_FROM_STRATEGY2
):
strategy2_checkpoint_path = resolve_strategy2_checkpoint_path(strategy, percent, model_config)
if EXECUTION_MODE == "train_eval":
maybe_run_strategy_smoke_test(
strategy=strategy,
model_config=model_config,
bundle=bundle,
strategy2_checkpoint_path=strategy2_checkpoint_path,
)
params = resolve_job_params(
strategy,
percent,
bundle,
model_config=model_config,
strategy2_checkpoint_path=strategy2_checkpoint_path,
)
banner(
f"FINAL RETRAIN | {run_identity_label(strategy=strategy, percent=percent, split_payload=bundle.split_payload)}"
)
run_final_training(
strategy,
bundle,
params,
model_config=model_config,
strategy2_checkpoint_path=strategy2_checkpoint_path,
)
else:
banner(
f"EVAL ONLY | {run_identity_label(strategy=strategy, percent=percent, split_payload=bundle.split_payload)}"
)
run_evaluation_for_run(
strategy=strategy,
percent=percent,
bundle=bundle,
run_dir=final_root_for_strategy(strategy, percent, model_config),
strategy2_checkpoint_path=strategy2_checkpoint_path,
)
except Exception:
banner("RUN FAILED")
traceback.print_exc()
return 1
banner("ALL DONE")
return 0
def main() -> int:
if EXPERIMENT_MODE not in SUPPORTED_EXPERIMENT_MODES:
raise ValueError(
f"EXPERIMENT_MODE must be one of {SUPPORTED_EXPERIMENT_MODES}, got {EXPERIMENT_MODE!r}"
)
if EXPERIMENT_MODE == "repeated_holdout":
return run_repeated_holdout_main()
return run_single_run_main()
if __name__ == "__main__":
raise SystemExit(main())
|