File size: 105,460 Bytes
4f2fd46 90f559d 4f2fd46 90f559d 4f2fd46 90f559d 4f2fd46 196a33b 4f2fd46 90f559d 4f2fd46 196a33b 7ae5b2d 4f2fd46 7ae5b2d 196a33b 4f2fd46 196a33b 4f2fd46 196a33b 4f2fd46 7ae5b2d 196a33b 4f2fd46 196a33b 4f2fd46 196a33b 4f2fd46 90f559d 4f2fd46 90f559d 4f2fd46 90f559d 4f2fd46 90f559d 4f2fd46 90f559d 4f2fd46 90f559d 4f2fd46 90f559d 4f2fd46 90f559d 4f2fd46 | 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 | #!/usr/bin/env python3
"""
Meta-Learner Trainer with Fold-Consistency Analysis
Trains a configurable meta-learner on top of OOF predictions from one or two
ensemble runs (CE and/or KL), analyses rule stability across folds, and
benchmarks inference time vs accuracy tradeoff.
Usage:
python meta_learner_trainer.py \
--ce_oof_path ce_ensemble.parquet \
--kl_oof_path kl_ensemble.parquet \
--data_path data.parquet \
--label_col category \
--mapping_dict_path mapping.json \
--ce_config_path ce_ensemble_config.json \
--kl_config_path kl_ensemble_config.json \
--meta_type lgbm \
--model_subset videberta-base,mlm_listing_checkpoint-32442,tfidf_lgbm \
--use_derived_features \
--fold_consistency_threshold 0.5 \
--k_folds 5 \
--output_dir meta_outputs
Notes:
- OOF parquets must contain columns like: {model_clean_name}_logprob_{class}
as produced by ensemble_distillation_generator.py
- model_subset filters by the "clean name" (model_name.split('/')[-1])
- If kl_oof_path is omitted, only CE OOF probs are used
- Inference benchmarking simulates per-model forward pass timing on CPU
to reflect production conditions (no GPU guarantee at serving time)
"""
import argparse
import gc
import json
import pickle
import time
import warnings
from pathlib import Path
from itertools import combinations
# Shared MetaLearner class β also imported by meta_learner_inference.py.
# Must be imported (not defined inline) so pickle/joblib deserialisation works
# from any script that loads a saved MetaLearner instance.
import sys as _sys, os as _os
_sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__)))
from meta_learner_core import MetaLearner # noqa: E402
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import seaborn as sns
from scipy.stats import spearmanr
from scipy.optimize import minimize
from sklearn.linear_model import LogisticRegression, Ridge
from sklearn.calibration import CalibratedClassifierCV
from sklearn.model_selection import StratifiedKFold
from sklearn.metrics import precision_recall_fscore_support, log_loss
from sklearn.preprocessing import LabelEncoder
import lightgbm as lgb
warnings.filterwarnings("ignore")
# =============================================================================
# ARGUMENT PARSING
# =============================================================================
def parse_args():
p = argparse.ArgumentParser()
# --- Data inputs ---
p.add_argument("--ce_oof_path", type=str, default=None,
help="Parquet with CE ensemble OOF logprob columns")
p.add_argument("--kl_oof_path", type=str, default=None,
help="Parquet with KL student OOF logprob columns (optional)")
p.add_argument("--data_path", type=str, required=True,
help="Original data parquet with labels")
p.add_argument("--label_col", type=str, required=True)
p.add_argument("--mapping_dict_path", type=str, required=True,
help="JSON mapping label -> integer index")
p.add_argument("--ce_config_path", type=str, default=None,
help="JSON config used to train CE ensemble")
p.add_argument("--kl_config_path", type=str, default=None,
help="JSON config used to train KL student ensemble")
# --- Model selection ---
p.add_argument("--unknown_label_value", type=str, default="N",
help="Raw label string in data that represents the unknown/null class "
"(maps to the 'UNKNOWN' OOF column). Default: 'N'.")
p.add_argument("--model_subset", type=str, default=None,
help="Comma-separated clean model names to include. "
"If omitted, all trained models are used.")
p.add_argument("--ensemble_source", type=str, default="both",
choices=["ce", "kl", "both"],
help="Which ensemble(s) to draw OOF features from.")
# --- Meta-learner ---
p.add_argument("--meta_type", type=str, default="lgbm",
choices=["lgbm", "logistic", "ridge", "weighted_avg", "mlp"],
help="Meta-learner architecture. "
"lgbm: LightGBM β best with derived features (entropy, KL div). "
"ridge: Ridge regression OvR + softmax β fastest, rarely overfits, "
"strong baseline for pure probability stacking. "
"logistic: Multinomial logistic with isotonic calibration. "
"weighted_avg: Nelder-Mead optimized blend weights β most interpretable. "
"mlp: small MLP with dropout β best when adding embeddings.")
p.add_argument("--use_derived_features", action="store_true",
help="Append entropy, KL-divergence, and per-class diff features.")
p.add_argument("--compare_meta_types", action="store_true",
help="Run ALL meta-learner types on the full feature set and print a "
"comparison table. Useful for choosing --meta_type.")
# --- Fold-consistency ---
p.add_argument("--k_folds", type=int, default=5)
p.add_argument("--fold_consistency_threshold", type=float, default=0.5,
help="Max coefficient-of-variation for a feature to be "
"considered 'stable'. Features above this CV are flagged.")
p.add_argument("--seed", type=int, default=42)
# --- Combination selection strategy ---
p.add_argument("--selection_strategy", type=str, default="greedy",
choices=["greedy", "exhaustive"],
help="Strategy for the accuracy-vs-speed model subset sweep. "
"greedy (default): forward selection β start with best single "
"model, greedily add the most complementary model at each step. "
"O(n^2) evaluations. Finds near-optimal subsets without exhaustive "
"enumeration. "
"exhaustive: try all subsets up to --max_combo_size (original "
"behaviour). Use only for small n_models.")
p.add_argument("--greedy_max_models", type=int, default=6,
help="Maximum number of models to select in greedy forward selection. "
"Selection stops earlier if F1 improvement < --greedy_min_gain.")
p.add_argument("--greedy_min_gain", type=float, default=0.001,
help="Minimum CV F1 gain to continue greedy selection. "
"Stops adding models once the marginal gain falls below this.")
# --- Option 2: OOF embeddings from fine-tuned fold models ---
p.add_argument("--use_oof_embeddings", action="store_true",
help="Extract [CLS] embeddings from each fine-tuned fold model using "
"the same K-fold OOF structure. PCA-reduced per model (per-fold "
"fit to avoid leakage), then concatenated to the feature matrix. "
"Requires --text_col, --ce_artifacts_dir / --kl_artifacts_dir.")
p.add_argument("--oof_emb_n_components", type=int, default=32,
help="PCA components to keep per model for OOF embeddings.")
p.add_argument("--oof_emb_batch_size", type=int, default=16,
help="Batch size for OOF embedding extraction inference.")
p.add_argument("--oof_emb_ce_cache", type=str, default="oof_emb_ce.parquet",
help="Parquet cache path for CE OOF embeddings. Re-used on subsequent "
"runs if the file exists and column count matches.")
p.add_argument("--oof_emb_kl_cache", type=str, default="oof_emb_kl.parquet",
help="Parquet cache path for KL OOF embeddings.")
# --- Option 3: Frozen encoder embeddings ---
p.add_argument("--frozen_encoder", type=str, default=None,
help="Path or HuggingFace name of a pretrained encoder to use as a "
"frozen feature extractor. No fine-tuning involved β embeddings "
"are extracted once and cached. Example: "
"pretrained_checkpoints/MikeGreen2710__mlm_listing_checkpoint-32442")
p.add_argument("--frozen_encoder_tokenizer", type=str, default=None,
help="Tokenizer for --frozen_encoder. Defaults to --frozen_encoder "
"itself if not set. Example: VinAI/phobert-base")
p.add_argument("--frozen_emb_n_components", type=int, default=64,
help="PCA components for frozen encoder embeddings.")
p.add_argument("--frozen_emb_batch_size", type=int, default=32,
help="Batch size for frozen embedding extraction.")
p.add_argument("--frozen_emb_cache", type=str, default="frozen_emb.parquet",
help="Parquet cache path for frozen encoder embeddings.")
# --- Inference benchmarking ---
p.add_argument("--benchmark_n_samples", type=int, default=200,
help="Number of samples to use for timing the base model forward passes.")
p.add_argument("--benchmark_repeats", type=int, default=5,
help="Repeats per model for the latency benchmark (median is taken).")
p.add_argument("--benchmark_device", type=str, default="cpu",
help="Device for base-model latency benchmarking ('cpu' or 'cuda'). "
"Use the device that matches your production serving environment.")
p.add_argument("--text_col", type=str, default=None,
help="Column in --data_path containing raw text, used for tokenisation "
"during base-model latency benchmarking. Required when "
"--ce_artifacts_dir or --kl_artifacts_dir is provided.")
p.add_argument("--max_length", type=int, default=256,
help="Tokenisation max_length for the latency benchmark.")
p.add_argument("--ce_artifacts_dir", type=str, default=None,
help="Root artifact directory from the CE ensemble run "
"(contains {model_safe_name}/fold_1/model/). "
"When provided, each CE model is loaded and timed individually.")
p.add_argument("--kl_artifacts_dir", type=str, default=None,
help="Root artifact directory from the KL student ensemble run. "
"When provided, each KL model is loaded and timed individually.")
p.add_argument("--max_combo_size", type=int, default=3,
help="Maximum subset size for the accuracy-vs-speed combination sweep. "
"All subsets of size 1..max_combo_size are evaluated. "
"Warning: combinatorial β keep <=4 for large model counts.")
p.add_argument("--ce_metadata_path", type=str, default=None,
help="Path to the CE ensemble metadata JSON (e.g. ensemble_metadata.json). "
"If latency_ms is already present it will be reused; otherwise models "
"are timed and the result is written back to this file.")
p.add_argument("--kl_metadata_path", type=str, default=None,
help="Path to the KL ensemble metadata JSON (e.g. ensemble_metadata_kl_round1.json). "
"Same read/write behaviour as --ce_metadata_path.")
# --- Output ---
p.add_argument("--output_dir", type=str, default="meta_outputs")
p.add_argument("--export_label", type=str, default=None,
help="Label from accuracy_vs_speed.csv to export as a deployment "
"artifact. If not set, the best F1 config is exported. "
"Example: 'lgbm/KL:mlm_listing_che+KL:rembert'")
p.add_argument("--export_only", action="store_true",
help="Skip all training, benchmarking, and sweep steps. "
"Load an existing --results_csv, re-train only the chosen "
"config's meta-learner on the OOF parquets, and write "
"deployment artifacts. Use after a full run to export a "
"different config without repeating expensive CV/benchmarking.")
p.add_argument("--results_csv", type=str, default=None,
help="Path to an existing accuracy_vs_speed.csv produced by a "
"previous full run. Required when --export_only is set.")
return p.parse_args()
# =============================================================================
# UTILITIES
# =============================================================================
def load_mapping(path: str) -> dict:
with open(path) as f:
return json.load(f)
def get_class_order_from_mapping(mapping: dict) -> list:
"""
Reconstruct the class index order used by ensemble_distillation_generator.
The generator assigns:
known classes β mapping_value - ordinal_min_label (so sort by value asc)
unknown class β ordinal_num_classes (always placed last)
We identify "unknown" as any entry whose value is < 0.
"""
known = sorted([(k, v) for k, v in mapping.items() if v >= 0], key=lambda x: x[1])
unknown = [k for k, v in mapping.items() if v < 0]
return [k for k, _ in known] + unknown
def get_active_models(config_path: str) -> list[dict]:
"""
Return models with use=True from the config.
The 'trained' flag has been removed from config files β the filesystem
(artifact_exists) is the source of truth for whether a model has been
trained. Here we only need the list of enabled model configs to know
which OOF columns to expect in the parquet and how to configure serving.
"""
with open(config_path) as f:
configs = json.load(f)
return [c for c in configs if c.get("use", True)]
def clean_name(model_name: str) -> str:
return model_name.split("/")[-1]
def logprob_cols_for_model(df_cols: list, model_clean_name: str,
class_order: list = None) -> list:
"""
Return logprob columns for a model in the correct class-index order.
class_order: list of class-name strings ordered by their 0-based index,
as returned by get_class_order_from_mapping(mapping).
When provided, columns are returned in that order so that
col i corresponds to class i β matching how y is encoded.
Falls back to alphabetical if not provided (fine for LightGBM
features, broken for weighted_avg argmax comparisons).
"""
prefix = f"{model_clean_name}_logprob_"
available = {c.split("_logprob_")[1]: c for c in df_cols if c.startswith(prefix)}
if class_order is not None:
ordered = [available[cls] for cls in class_order if cls in available]
covered = set(ordered)
ordered += [c for c in sorted(available.values()) if c not in covered]
return ordered
return sorted(available.values())
def get_class_order_from_mapping(mapping: dict) -> list:
"""
Return class name strings in 0-based index order, matching the generator.
Known classes (value >= 0) first, sorted by value. Unknown (value < 0) last.
"""
known = sorted([(k, v) for k, v in mapping.items() if v >= 0], key=lambda x: x[1])
unknown = [k for k, v in mapping.items() if v < 0]
return [k for k, _ in known] + unknown
def entropy(probs: np.ndarray, eps: float = 1e-7) -> np.ndarray:
p = np.clip(probs, eps, 1.0)
return -np.sum(p * np.log(p), axis=1)
def kl_div_row(p: np.ndarray, q: np.ndarray, eps: float = 1e-7) -> np.ndarray:
"""Symmetric KL divergence between two prob arrays, row-wise."""
p = np.clip(p, eps, 1.0)
q = np.clip(q, eps, 1.0)
return 0.5 * (np.sum(p * np.log(p / q), axis=1) +
np.sum(q * np.log(q / p), axis=1))
# =============================================================================
# FEATURE BUILDER
# =============================================================================
class OOFFeatureBuilder:
"""
Builds a feature matrix from OOF probability columns.
Feature groups:
base : raw per-class probs for every selected model
derived : entropy, argmax, per-pair KL divergence, CE-KL diff
"""
def __init__(self, ce_df, kl_df, ce_models, kl_models,
model_subset=None, use_derived=True,
ensemble_source="both", class_order=None):
self.ce_df = ce_df
self.kl_df = kl_df
self.ce_models = ce_models # list of clean names
self.kl_models = kl_models # list of clean names
self.subset = set(model_subset) if model_subset else None
self.use_derived = use_derived
self.source = ensemble_source
self.class_order = class_order # ordered class names from mapping
# Resolved model lists
self._ce_active = self._filter(self.ce_models, "ce")
self._kl_active = self._filter(self.kl_models, "kl")
self.feature_names = []
def _filter(self, names, source):
if source == "ce" and self.source == "kl":
return []
if source == "kl" and self.source == "ce":
return []
if self.subset:
return [n for n in names if n in self.subset]
return names
def _get_probs(self, df, model_name):
cols = logprob_cols_for_model(list(df.columns), model_name, self.class_order)
if not cols:
return None, []
return df[cols].values, cols
def build(self):
blocks = []
names = []
# --- CE base probs ---
for m in self._ce_active:
probs, cols = self._get_probs(self.ce_df, m)
if probs is None:
print(f" [WARN] CE model {m}: no logprob columns found β skipping")
continue
blocks.append(probs)
names.extend([f"CE_{m}_{c.split('_logprob_')[1]}" for c in cols])
# --- KL base probs ---
for m in self._kl_active:
if self.kl_df is None:
break
probs, cols = self._get_probs(self.kl_df, m)
if probs is None:
print(f" [WARN] KL model {m}: no logprob columns found β skipping")
continue
blocks.append(probs)
names.extend([f"KL_{m}_{c.split('_logprob_')[1]}" for c in cols])
if not blocks:
raise ValueError("No features built β check model_subset and OOF column names.")
X = np.hstack(blocks)
# --- Derived features ---
if self.use_derived:
derived_blocks = []
derived_names = []
n_classes = blocks[0].shape[1]
all_probs = {}
for i, m in enumerate(self._ce_active):
p, _ = self._get_probs(self.ce_df, m)
if p is None: continue
all_probs[f"CE_{m}"] = p
ent = entropy(p)
derived_blocks.append(ent.reshape(-1, 1))
derived_names.append(f"CE_{m}_entropy")
am = np.argmax(p, axis=1).reshape(-1, 1).astype(float)
derived_blocks.append(am)
derived_names.append(f"CE_{m}_argmax")
for m in self._kl_active:
if self.kl_df is None: break
p, _ = self._get_probs(self.kl_df, m)
if p is None: continue
all_probs[f"KL_{m}"] = p
ent = entropy(p)
derived_blocks.append(ent.reshape(-1, 1))
derived_names.append(f"KL_{m}_entropy")
am = np.argmax(p, axis=1).reshape(-1, 1).astype(float)
derived_blocks.append(am)
derived_names.append(f"KL_{m}_argmax")
# Pairwise symmetric KL between CE and KL versions of same model
for m in self._ce_active:
ce_key = f"CE_{m}"
kl_key = f"KL_{m}"
if ce_key in all_probs and kl_key in all_probs:
div = kl_div_row(all_probs[ce_key], all_probs[kl_key])
derived_blocks.append(div.reshape(-1, 1))
derived_names.append(f"CE_KL_{m}_sym_kl")
diff = all_probs[ce_key] - all_probs[kl_key]
derived_blocks.append(diff)
derived_names.extend(
[f"CE_KL_{m}_diff_class{i}" for i in range(diff.shape[1])])
# Pairwise disagreement between CE models
ce_prob_list = [(k, v) for k, v in all_probs.items() if k.startswith("CE_")]
for (n1, p1), (n2, p2) in combinations(ce_prob_list, 2):
div = kl_div_row(p1, p2)
derived_blocks.append(div.reshape(-1, 1))
derived_names.append(f"CE_pair_{n1}_vs_{n2}_kl")
if derived_blocks:
X = np.hstack([X] + derived_blocks)
names.extend(derived_names)
self.feature_names = names
return X, names
# =============================================================================
# META-LEARNER WRAPPER
# =============================================================================
# MetaLearner lives in meta_learner_core.py β imported below.
# See that file to modify the class.
# =============================================================================
# FOLD CONSISTENCY ANALYSER
# =============================================================================
def fold_consistency_analysis(X, y, feature_names, meta_type, n_classes,
k_folds, seed, threshold, n_prob_cols=None):
"""
Train a meta-learner on each fold's training split, record feature importances,
then compute coefficient-of-variation across folds.
Returns:
fold_importances : (k_folds, n_features) array
cv_per_feature : (n_features,) array of CV values
stable_mask : boolean mask of stable features (CV <= threshold)
"""
print(f"\n{'='*60}")
print("FOLD CONSISTENCY ANALYSIS")
print(f"{'='*60}")
kfold = StratifiedKFold(n_splits=k_folds, shuffle=True, random_state=seed)
fold_importances = []
fold_val_f1s = []
for fold, (train_idx, val_idx) in enumerate(kfold.split(X, y)):
X_tr, X_val = X[train_idx], X[val_idx]
y_tr, y_val = y[train_idx], y[val_idx]
meta = MetaLearner(meta_type, n_classes, seed,
n_prob_cols=n_prob_cols).fit(X_tr, y_tr)
val_preds = np.argmax(meta.predict_proba(X_val), axis=1)
f1 = precision_recall_fscore_support(
y_val, val_preds, average="macro", zero_division=0)[2]
fold_val_f1s.append(f1)
print(f" Fold {fold+1}/{k_folds} β Val Macro F1: {f1:.4f}")
imp = meta.get_feature_importances()
if imp is not None:
fold_importances.append(imp)
if not fold_importances:
print(" [WARN] Meta-learner does not expose feature importances.")
return None, None, None, fold_val_f1s
fold_importances = np.array(fold_importances) # (k, n_features)
# Normalise each fold's importances to sum to 1 (comparable scale)
fold_importances_norm = (fold_importances /
fold_importances.sum(axis=1, keepdims=True).clip(min=1e-9))
mean_imp = fold_importances_norm.mean(axis=0)
std_imp = fold_importances_norm.std(axis=0)
cv = np.where(mean_imp > 1e-9, std_imp / mean_imp, np.inf)
stable_mask = cv <= threshold
n_stable = stable_mask.sum()
print(f"\n Feature stability (CV threshold={threshold}):")
print(f" Stable features : {n_stable}/{len(feature_names)}")
print(f" Mean Val F1 : {np.mean(fold_val_f1s):.4f} Β± {np.std(fold_val_f1s):.4f}")
# Top 20 most stable important features
rank = np.argsort(-mean_imp)
print(f"\n Top-20 features by mean importance (stable=β, unstable=β):")
for i, idx in enumerate(rank[:20]):
tag = "β" if stable_mask[idx] else "β"
print(f" {tag} [{cv[idx]:.2f} CV] {feature_names[idx]:<60s} "
f"imp={mean_imp[idx]:.4f}")
return fold_importances_norm, cv, stable_mask, fold_val_f1s
# =============================================================================
# INFERENCE TIME BENCHMARK
# =============================================================================
# =============================================================================
# PER-MODEL LATENCY BENCHMARKING
# =============================================================================
def _get_model_fold_dir(artifacts_dir: str, model_name: str, stage: str = None) -> Path:
"""
Resolve the saved fold-1 model directory for a given model.
Mirrors the artifact naming in ensemble_distillation_generator.py:
artifact_name = model_name (or model_name + "__stage1" / "__stage2")
safe_name = artifact_name.replace("/", "__")
"""
artifact_name = model_name if stage is None else f"{model_name}__{stage}"
safe_name = artifact_name.replace("/", "__")
return Path(artifacts_dir) / safe_name / "fold_1" / "model"
def _normalise_device(device_str: str) -> str:
"""Map user-friendly aliases ('gpu') to PyTorch device strings ('cuda')."""
return "cuda" if device_str.lower() == "gpu" else device_str.lower()
def benchmark_transformer_model(
original_model_name: str,
tokenizer_name: str,
texts: list,
max_length: int,
device: str,
n_repeats: int,
drop_token_type_ids: bool = False,
use_fp16: bool = False,
use_bf16: bool = False,
) -> float:
"""
Load the BASE ENCODER of a model from its original pretrained checkpoint and
time its forward pass.
Why the base encoder, not the saved fold model?
------------------------------------------------
The generator saves models as custom nn.Module wrappers:
- MultimodalClassificationModel (models with other_cols)
- OrdinalRegressionModel (task_type=ordinal)
These are not AutoModelForSequenceClassification and cannot be loaded
with it β their state_dict keys have 'base_model.*' prefixes that
AutoModel* classes do not recognise.
For latency benchmarking this does not matter: the transformer encoder
is >99% of inference time. The classification/ordinal head and the
extra tabular features (other_cols) add <1ms and are not what we are
comparing across models.
We load from the ORIGINAL pretrained checkpoint (always available, always
has model_type, no custom wrapper) and apply the same dtype (fp16/bf16)
that was used during training so the timing reflects production conditions.
"""
import torch
from transformers import AutoModel, AutoTokenizer
device = _normalise_device(device)
tok_src = tokenizer_name if tokenizer_name else original_model_name
tokenizer = AutoTokenizer.from_pretrained(tok_src, trust_remote_code=True)
dtype = (torch.bfloat16 if use_bf16
else torch.float16 if use_fp16
else torch.float32)
model = AutoModel.from_pretrained(
original_model_name, trust_remote_code=True, torch_dtype=dtype)
model.eval()
model.to(device)
enc = tokenizer(
texts, padding=True, truncation=True,
max_length=max_length, return_tensors="pt"
)
if drop_token_type_ids:
enc.pop("token_type_ids", None)
enc = {k: v.to(device) for k, v in enc.items()}
is_cuda = device.startswith("cuda")
# Warmup
with torch.no_grad():
_ = model(**enc)
if is_cuda:
torch.cuda.synchronize()
times = []
for _ in range(n_repeats):
if is_cuda:
torch.cuda.synchronize()
t0 = time.perf_counter()
with torch.no_grad():
_ = model(**enc)
if is_cuda:
torch.cuda.synchronize()
times.append(time.perf_counter() - t0)
del model, enc
if is_cuda:
torch.cuda.empty_cache()
gc.collect()
return float(np.median(times)) * 1000.0 # ms
def benchmark_lgbm_model(artifacts_dir: str, texts: list,
n_tabular_features: int, n_repeats: int) -> float:
"""
Load the TF-IDF + LightGBM pipeline pickle from fold_1 and time it.
n_tabular_features: len(cfg["other_cols"]) β the number of extra numeric
columns that were appended during training (on_front_street, etc.).
For timing we pad with zeros: the values don't affect latency, only the
feature count matters for the LightGBM predict call.
"""
from scipy.sparse import hstack, csr_matrix
pkl_path = Path(artifacts_dir) / "tfidf_lgbm" / "fold_1" / "model.pkl"
if not pkl_path.exists():
return None
with open(pkl_path, "rb") as f:
bundle = pickle.load(f)
cal = bundle["calibrated_model"]
wtf = bundle["word_tfidf"]
ctf = bundle["char_tfidf"]
X = hstack([wtf.transform(texts), ctf.transform(texts)])
if n_tabular_features > 0:
tab_zeros = csr_matrix((len(texts), n_tabular_features), dtype="float32")
X = hstack([X, tab_zeros])
times = []
for _ in range(n_repeats):
t0 = time.perf_counter()
_ = cal.predict_proba(X)
times.append(time.perf_counter() - t0)
return float(np.median(times)) * 1000.0 # ms
# =============================================================================
# EMBEDDING EXTRACTION β OPTIONS 2 AND 3
# =============================================================================
def _load_encoder_from_fold(fold_model_dir, original_model_name,
use_fp16, use_bf16, device):
"""
Load just the base transformer encoder from a saved fold checkpoint.
The generator saves models as custom wrappers (MultimodalClassificationModel,
OrdinalRegressionModel) whose state_dict keys have a "base_model." prefix.
We strip that prefix to reconstruct the plain AutoModel state dict.
For models saved as plain AutoModelForSequenceClassification (no other_cols),
keys are direct and strict=False discards the classifier head automatically.
"""
import torch
from transformers import AutoModel
fold_model_dir = Path(fold_model_dir)
st_path = fold_model_dir / "model.safetensors"
use_safe = st_path.exists()
if not use_safe:
st_path = fold_model_dir / "pytorch_model.bin"
if not st_path.exists():
raise FileNotFoundError("No weights file in " + str(fold_model_dir))
if use_safe:
from safetensors.torch import load_file
raw_sd = load_file(str(st_path))
else:
raw_sd = torch.load(str(st_path), map_location="cpu", weights_only=True)
# Strip "base_model." prefix (custom wrapper models)
encoder_sd = {k[len("base_model."):]: v
for k, v in raw_sd.items()
if k.startswith("base_model.")}
if not encoder_sd:
# Plain AutoModelForSequenceClassification β use full state dict,
# strict=False will ignore classifier/pooler keys.
encoder_sd = raw_sd
dtype = (torch.bfloat16 if use_bf16 else
torch.float16 if use_fp16 else
torch.float32)
encoder = AutoModel.from_pretrained(
original_model_name, trust_remote_code=True, dtype=dtype)
missing, unexpected = encoder.load_state_dict(encoder_sd, strict=False)
n_loaded = len(encoder_sd) - len(unexpected)
print(" weights loaded={} missing={} unexpected={}".format(
n_loaded, len(missing), len(unexpected)))
encoder.eval()
encoder.to(device)
return encoder
def _encode_texts(encoder, tokenizer, texts, max_length, device,
batch_size, drop_token_type_ids):
"""Run encoder on texts, return CLS embeddings as float32 numpy array."""
import torch
all_embs = []
for start in range(0, len(texts), batch_size):
batch = texts[start:start + batch_size]
enc = tokenizer(batch, padding=True, truncation=True,
max_length=max_length, return_tensors="pt")
if drop_token_type_ids:
enc.pop("token_type_ids", None)
enc = {k: v.to(device) for k, v in enc.items()}
with torch.no_grad():
out = encoder(**enc)
cls = out.last_hidden_state[:, 0, :].float().cpu().numpy()
all_embs.append(cls)
return np.vstack(all_embs)
def extract_oof_embeddings(ce_configs, kl_configs,
ce_artifacts_dir, kl_artifacts_dir,
texts, y,
max_length, device, n_components,
batch_size, k_folds, seed,
ce_cache, kl_cache):
"""
Option 2: extract OOF embeddings from fine-tuned fold checkpoints.
For each model and each fold:
1. Load the fold-k checkpoint encoder (fine-tuned weights).
2. Encode the fold-k validation samples -> raw CLS embeddings.
After all folds, fit PCA on the full OOF embedding matrix for each model
(PCA directions from embedding geometry, no label involvement β safe).
Results are cached; subsequent calls with the same cache path are instant.
split_unknown_stage models: use stage1 checkpoint (trained on all samples as
binary; stage2 only covers known samples so cannot fill the full OOF matrix).
"""
from sklearn.decomposition import PCA
from transformers import AutoTokenizer
device = _normalise_device(device)
kfold = StratifiedKFold(n_splits=k_folds, shuffle=True, random_state=seed)
def _extract_one_ensemble(configs, artifacts_dir, tag, cache_path):
cache = Path(cache_path)
if cache.exists():
print(" [{}] Loading cached OOF embeddings <- {}".format(tag, cache_path))
df_c = pd.read_parquet(cache)
return df_c.values, list(df_c.columns)
blocks, names = [], []
trained = [c for c in configs if c.get("use", True)]
for cfg in trained:
mname = cfg["model_name"]
cname = clean_name(mname)
tok_name = cfg.get("tokenizer_name") or mname
drop_tti = cfg.get("drop_token_type_ids", False)
split_unk = cfg.get("split_unknown_stage", False)
use_fp16 = cfg.get("use_fp16", False)
use_bf16 = cfg.get("use_bf16", False)
# For split_unknown_stage use stage1 (covers all samples)
stage = "stage1" if split_unk else None
task = cfg.get("task_type", "classification")
if task == "tfidf_lgbm":
print(" [{}] {} is tfidf_lgbm β no embeddings, skipping".format(tag, cname))
continue
print(" [{}] OOF embeddings: {} ...".format(tag, cname))
tokenizer = AutoTokenizer.from_pretrained(tok_name, trust_remote_code=True)
n_samples = len(texts)
raw_oof = None # (n_samples, hidden_dim) filled fold by fold
for fold_idx, (_, val_idx) in enumerate(kfold.split(texts, y)):
fold_n = fold_idx + 1
artifact_name = (mname if stage is None
else mname + "__" + stage)
safe_name = artifact_name.replace("/", "__")
fold_dir = (Path(artifacts_dir) / safe_name
/ ("fold_" + str(fold_n)) / "model")
if not fold_dir.exists():
print(" [WARN] fold {} dir not found: {}".format(fold_n, fold_dir))
continue
encoder = _load_encoder_from_fold(
fold_dir, mname, use_fp16, use_bf16, device)
val_texts = [texts[i] for i in val_idx]
val_embs = _encode_texts(
encoder, tokenizer, val_texts, max_length,
device, batch_size, drop_tti) # (n_val, H)
if raw_oof is None:
raw_oof = np.zeros((n_samples, val_embs.shape[1]),
dtype=np.float32)
raw_oof[val_idx] = val_embs
del encoder
gc.collect()
import torch
if device.startswith("cuda"):
torch.cuda.empty_cache()
print(" fold {}/{} done".format(fold_n, k_folds))
if raw_oof is None:
print(" [{}] {} β no folds loaded, skipping".format(tag, cname))
continue
# PCA fitted on full OOF matrix (no label info in embeddings -> safe)
n_keep = min(n_components, raw_oof.shape[1], raw_oof.shape[0])
pca = PCA(n_components=n_keep, random_state=seed)
reduced = pca.fit_transform(raw_oof).astype(np.float32)
var = pca.explained_variance_ratio_.sum()
print(" PCA {}->{} var_explained={:.1%}".format(
raw_oof.shape[1], n_keep, var))
blocks.append(reduced)
names.extend(["{}_OOF_{}_pc{}".format(tag, cname, i)
for i in range(n_keep)])
if not blocks:
return np.zeros((len(texts), 0), dtype=np.float32), []
X_emb = np.hstack(blocks)
emb_df = pd.DataFrame(X_emb, columns=names)
emb_df.to_parquet(cache_path)
print(" [{}] OOF embeddings cached -> {} shape={}".format(
tag, cache_path, X_emb.shape))
return X_emb, names
X_ce, n_ce = _extract_one_ensemble(
ce_configs, ce_artifacts_dir, "CE", ce_cache) if ce_artifacts_dir else (
np.zeros((len(texts), 0)), [])
X_kl, n_kl = _extract_one_ensemble(
kl_configs, kl_artifacts_dir, "KL", kl_cache) if kl_artifacts_dir else (
np.zeros((len(texts), 0)), [])
parts = [x for x in [X_ce, X_kl] if x.shape[1] > 0]
nparts = n_ce + n_kl
if not parts:
return np.zeros((len(texts), 0), dtype=np.float32), []
return np.hstack(parts), nparts
def extract_frozen_embeddings(model_name, tokenizer_name, texts,
max_length, device, n_components,
batch_size, cache_path):
"""
Option 3: extract embeddings from a frozen (non-fine-tuned) pretrained encoder.
No fold structure needed β pretrained weights never see labels so there is no
leakage risk. PCA is fitted on the full dataset. Results are cached.
"""
from sklearn.decomposition import PCA
from transformers import AutoModel, AutoTokenizer
import torch
cache = Path(cache_path)
if cache.exists():
print(" Loading cached frozen embeddings <- {}".format(cache_path))
df_c = pd.read_parquet(cache)
return df_c.values, list(df_c.columns)
device = _normalise_device(device)
cname = clean_name(model_name)
tok_src = tokenizer_name if tokenizer_name else model_name
print(" Frozen encoder embeddings: {} ({} samples)...".format(
model_name, len(texts)))
tokenizer = AutoTokenizer.from_pretrained(tok_src, trust_remote_code=True)
encoder = AutoModel.from_pretrained(model_name, trust_remote_code=True)
encoder.eval()
encoder.to(device)
all_embs = []
n_batches = (len(texts) + batch_size - 1) // batch_size
for b_idx, start in enumerate(range(0, len(texts), batch_size)):
batch = texts[start:start + batch_size]
enc = tokenizer(batch, padding=True, truncation=True,
max_length=max_length, return_tensors="pt")
enc = {k: v.to(device) for k, v in enc.items()}
with torch.no_grad():
out = encoder(**enc)
cls = out.last_hidden_state[:, 0, :].float().cpu().numpy()
all_embs.append(cls)
if b_idx % 50 == 0 or b_idx == n_batches - 1:
print(" batch {}/{}".format(b_idx + 1, n_batches))
del encoder
gc.collect()
if device.startswith("cuda"):
torch.cuda.empty_cache()
embeddings = np.vstack(all_embs) # (n_samples, H)
n_keep = min(n_components, embeddings.shape[1], embeddings.shape[0])
pca = PCA(n_components=n_keep)
reduced = pca.fit_transform(embeddings).astype(np.float32)
var = pca.explained_variance_ratio_.sum()
print(" PCA {}->{} var_explained={:.1%}".format(
embeddings.shape[1], n_keep, var))
col_names = ["FROZEN_{}_pc{}".format(cname, i) for i in range(n_keep)]
pd.DataFrame(reduced, columns=col_names).to_parquet(cache_path)
print(" Frozen embeddings cached -> {} shape={}".format(
cache_path, reduced.shape))
# CRITICAL: save the fitted PCA + the exact tokenisation settings so that
# inference reproduces the SAME transform. Re-fitting PCA on inference data
# would yield different components and break the meta-learner.
import joblib
pca_path = str(Path(cache_path).with_suffix("")) + "_pca.joblib"
joblib.dump({
"pca": pca,
"col_names": col_names,
"model_name": model_name,
"tokenizer_name": tok_src,
"max_length": max_length,
"n_components": n_keep,
"hidden_dim": embeddings.shape[1],
}, pca_path)
print(" Frozen PCA transform saved -> {}".format(pca_path))
return reduced, col_names
def _load_metadata(path: str) -> dict:
if path and Path(path).exists():
with open(path) as f:
return json.load(f)
return {}
def _save_metadata(path: str, data: dict):
with open(path, "w") as f:
json.dump(data, f, indent=2)
print(f" Saved latency_ms β {path}")
def build_latency_map(
ce_configs: list,
kl_configs: list,
ce_artifacts_dir: str,
kl_artifacts_dir: str,
ce_metadata_path: str,
kl_metadata_path: str,
texts: list,
max_length: int,
device: str,
n_repeats: int,
) -> dict:
"""
Return a latency map: {"CE:{clean_name}": ms, "KL:{clean_name}": ms, ...}
For each ensemble (CE / KL):
1. Load its metadata JSON.
2. If "latency_ms" key already exists β use cached values, skip loading models.
3. Otherwise β benchmark every trained model, write results back to the metadata file.
Latency is stored in metadata as {clean_name: ms} (no CE/KL prefix, since each
metadata file already belongs to one ensemble). The combined latency_map uses the
"CE:" / "KL:" prefix so callers can look up models unambiguously.
"""
latency_map = {}
device = _normalise_device(device) # "gpu" -> "cuda" etc.
def _bench_ensemble(configs, artifacts_dir, metadata_path, tag):
"""Handle one ensemble (CE or KL): check cache, bench if needed, write back."""
meta = _load_metadata(metadata_path)
cached = meta.get("latency_ms", {}) # {clean_name: ms}
# Check which trained models already have cached latency
trained = [c for c in configs if c.get("use", True)]
trained_names = [clean_name(c["model_name"]) for c in trained]
missing_names = [n for n in trained_names if n not in cached]
if not missing_names:
print(f" [{tag}] All {len(trained_names)} model latencies loaded from {metadata_path}")
for n in trained_names:
latency_map[f"{tag}:{n}"] = cached[n]
return
# Some or all need benchmarking
if cached:
print(f" [{tag}] {len(cached)} cached, {len(missing_names)} need benchmarking: "
f"{missing_names}")
else:
print(f" [{tag}] No cached latencies in {metadata_path} β timing all models.")
newly_measured = {}
def _bench_one(cfg):
mname = cfg["model_name"]
cname = clean_name(mname)
task = cfg.get("task_type", "classification")
tok_name = cfg.get("tokenizer_name", None)
drop_tti = cfg.get("drop_token_type_ids", False)
split_unk = cfg.get("split_unknown_stage", False)
use_fp16 = cfg.get("use_fp16", False)
use_bf16 = cfg.get("use_bf16", False)
# Use cache if available
if cname in cached:
print(f" [{tag}] {cname}: using cached {cached[cname]:.1f} ms")
latency_map[f"{tag}:{cname}"] = cached[cname]
return
print(f" [{tag}] Timing {cname} ...")
if task == "tfidf_lgbm":
n_tab = len(cfg.get("other_cols", []))
ms = benchmark_lgbm_model(artifacts_dir, texts, n_tab, n_repeats)
if ms is None:
print(f" [WARN] pickle not found β skipping")
return
elif split_unk:
# 2-stage model: encoder runs twice (once per stage) with the same
# base architecture, so we time once and double it.
ms_single = benchmark_transformer_model(
mname, tok_name, texts, max_length, device, n_repeats,
drop_tti, use_fp16, use_bf16)
ms = ms_single * 2.0
print(f" encoder x2 (stage1+stage2): {ms:.1f} ms / {len(texts)} samples")
else:
ms = benchmark_transformer_model(
mname, tok_name, texts, max_length, device, n_repeats,
drop_tti, use_fp16, use_bf16)
print(f" {ms:.1f} ms / {len(texts)} samples")
latency_map[f"{tag}:{cname}"] = ms
newly_measured[cname] = round(ms, 3)
for cfg in trained:
_bench_one(cfg)
# Write back to metadata only if we measured anything new
if newly_measured and metadata_path:
meta["latency_ms"] = {**cached, **newly_measured}
meta["latency_benchmark_n_samples"] = len(texts)
meta["latency_benchmark_device"] = device
_save_metadata(metadata_path, meta)
if ce_artifacts_dir:
_bench_ensemble(ce_configs, ce_artifacts_dir, ce_metadata_path, "CE")
if kl_artifacts_dir:
_bench_ensemble(kl_configs, kl_artifacts_dir, kl_metadata_path, "KL")
return latency_map
def lookup_subset_latency(ce_sub, kl_sub, latency_map,
extra_latency_ms: float = 0.0):
"""
Sum latencies for all models in a subset. Returns (total_ms, any_missing).
extra_latency_ms: fixed overhead to add to every config regardless of which
base models are selected (e.g. frozen encoder that always runs at inference,
OOF embedding encoders that run at inference time).
"""
total = extra_latency_ms
missing = []
for m in ce_sub:
key = f"CE:{m}"
if key in latency_map:
total += latency_map[key]
else:
missing.append(key)
for m in kl_sub:
key = f"KL:{m}"
if key in latency_map:
total += latency_map[key]
else:
missing.append(key)
return total, missing
def benchmark_inference(X_subset, meta_learner, n_repeats=20):
"""Median wall-clock time for a single predict_proba call over X_subset."""
times = []
for _ in range(n_repeats):
t0 = time.perf_counter()
_ = meta_learner.predict_proba(X_subset)
times.append(time.perf_counter() - t0)
return np.median(times), np.std(times)
# =============================================================================
# COMPLEMENTARITY ANALYSIS & GREEDY FORWARD SELECTION
# =============================================================================
def compute_complementarity_matrix(X_all, y, tagged, n_classes):
"""
For every pair of models, compute the joint error ratio:
P(A wrong AND B wrong) / P(A wrong OR B wrong)
Low ratio = high complementarity (errors on different samples).
High ratio = redundant pair.
tagged: list of (clean_name, "CE"|"KL")
"""
preds = {}
for i, (name, src) in enumerate(tagged):
key = f"{src}:{name}"
start = i * n_classes
probs = X_all[:, start:start + n_classes]
preds[key] = np.argmax(probs, axis=1)
keys = list(preds.keys())
wrong = {k: (preds[k] != y) for k in keys}
rows = []
for i, a in enumerate(keys):
for j, b in enumerate(keys):
if i >= j:
continue
both = (wrong[a] & wrong[b]).sum()
either = (wrong[a] | wrong[b]).sum()
ratio = both / max(either, 1)
rows.append({"model_a": a, "model_b": b,
"joint_error_ratio": round(ratio, 4),
"a_err_rate": round(wrong[a].mean(), 4),
"b_err_rate": round(wrong[b].mean(), 4)})
return pd.DataFrame(rows).sort_values("joint_error_ratio")
def greedy_forward_selection(X_full, y, tagged, n_classes, class_order,
df_ce, df_kl, use_derived, meta_type,
k_folds, seed, max_models, min_gain,
extra_features=None):
"""
Greedy forward selection of model subsets.
Start with best single model; at each step add the candidate that gives
the largest CV F1 gain. Stop when max_models reached or gain < min_gain.
Returns singles + every greedy prefix as (label, ce_subset, kl_subset).
extra_features: optional (n_samples, d) numpy array of fixed features
(e.g. frozen encoder embeddings, OOF embeddings) that are concatenated
to every subset's feature matrix. These are fixed regardless of which
base models are selected β they represent encoders that always run at
serving time.
"""
kfold = StratifiedKFold(n_splits=k_folds, shuffle=True, random_state=seed)
def _cv_f1(ce_sub, kl_sub):
b = OOFFeatureBuilder(
ce_df=df_ce, kl_df=df_kl,
ce_models=ce_sub, kl_models=kl_sub,
use_derived=use_derived,
ensemble_source="both",
class_order=class_order,
)
try:
Xs, _ = b.build()
except ValueError:
return 0.0
n_prob = Xs.shape[1] # prob cols before any embeddings are appended
if extra_features is not None and extra_features.shape[1] > 0:
Xs = np.hstack([Xs, extra_features])
f1s = []
for tr, val in kfold.split(Xs, y):
m = MetaLearner(meta_type, n_classes, seed,
n_prob_cols=n_prob).fit(Xs[tr], y[tr])
p = np.argmax(m.predict_proba(Xs[val]), axis=1)
f1s.append(precision_recall_fscore_support(
y[val], p, average="macro", zero_division=0)[2])
return float(np.mean(f1s))
remaining = list(tagged)
selected = []
best_f1 = 0.0
path = []
print(" Greedy forward selection"
f" (max_models={max_models}, min_gain={min_gain}):")
for step in range(max_models):
best_candidate = None
best_candidate_f1 = best_f1
for candidate in remaining:
trial = selected + [candidate]
ce_sub = [n for n, s in trial if s == "CE"]
kl_sub = [n for n, s in trial if s == "KL"]
f1 = _cv_f1(ce_sub, kl_sub)
if f1 > best_candidate_f1:
best_candidate_f1 = f1
best_candidate = candidate
if best_candidate is None or (best_candidate_f1 - best_f1) < min_gain:
print(f" Step {step+1}: no gain >={min_gain:.4f} β stopping.")
break
selected.append(best_candidate)
remaining.remove(best_candidate)
gain = best_candidate_f1 - best_f1
best_f1 = best_candidate_f1
name, src = best_candidate
ce_sub = [n for n, s in selected if s == "CE"]
kl_sub = [n for n, s in selected if s == "KL"]
label = "+".join(f"{s}:{n.split('__')[-1][:15]}" for n, s in selected)
short = name.split("__")[-1][:25]
print(f" Step {step+1}: +{src}:{short:<25} "
f"F1={best_f1:.4f} gain=+{gain:.4f}")
path.append((label, list(ce_sub), list(kl_sub), best_f1))
# Singles always included for reference
singles = []
for name, src in tagged:
ce_sub = [name] if src == "CE" else []
kl_sub = [name] if src == "KL" else []
lbl = f"{src}:{name.split('__')[-1][:25]}"
singles.append((lbl, ce_sub, kl_sub))
path_configs = [(lbl, ce, kl) for lbl, ce, kl, _ in path]
seen = set()
result = []
for cfg in singles + path_configs:
key = (frozenset(f"CE:{m}" for m in cfg[1]) |
frozenset(f"KL:{m}" for m in cfg[2]))
if key not in seen:
seen.add(key)
result.append(cfg)
return result
def build_subset_configs(ce_models, kl_models, max_combo_size=3):
"""
Generate candidate model subsets for the accuracy-vs-speed sweep.
Each model is tagged with its source ("CE" or "KL"). All subsets of
size 1..max_combo_size are generated, plus the full ALL_CE, ALL_KL,
and ALL_CE+KL aggregates.
Returns list of (label, ce_subset, kl_subset) tuples.
"""
# Tag every model with its source so we can split them back out
tagged = [(m, "CE") for m in ce_models] + [(m, "KL") for m in kl_models]
n_total = len(tagged)
seen = set()
configs = []
def add(label, ce_sub, kl_sub):
key = (frozenset(f"CE:{m}" for m in ce_sub) |
frozenset(f"KL:{m}" for m in kl_sub))
if key not in seen:
seen.add(key)
configs.append((label, list(ce_sub), list(kl_sub)))
# All subsets of size 1..max_combo_size
cap = min(max_combo_size, n_total)
for size in range(1, cap + 1):
for combo in combinations(tagged, size):
ce_sub = [m for m, src in combo if src == "CE"]
kl_sub = [m for m, src in combo if src == "KL"]
# Build a readable label: prefix only when mixing sources
parts = [f"CE:{m.split('__')[-1][:18]}" if src == "CE"
else f"KL:{m.split('__')[-1][:18]}"
for m, src in combo]
label = "+".join(parts) if len(parts) <= 3 else f"COMBO_{len(parts)}m"
add(label, ce_sub, kl_sub)
# Full aggregates (always include regardless of max_combo_size)
add("ALL_CE", ce_models, [])
if kl_models:
add("ALL_KL", [], kl_models)
add("ALL_CE+KL", ce_models, kl_models)
return configs
# =============================================================================
# PLOTTING
# =============================================================================
def plot_fold_consistency(fold_importances, cv, feature_names, stable_mask, output_dir):
"""Heatmap of per-fold importances for top features, and CV bar plot."""
# weighted_avg importances cover only the leading prob columns (see
# MetaLearner.get_feature_importances) β align names/counts to the array.
feature_names = list(feature_names)[:fold_importances.shape[1]]
top_n = min(30, fold_importances.shape[1])
mean_imp = fold_importances.mean(axis=0)
top_idx = np.argsort(-mean_imp)[:top_n]
fig, axes = plt.subplots(1, 2, figsize=(18, 8))
fig.suptitle("Fold Consistency Analysis", fontsize=14, fontweight="bold")
# Heatmap
data = fold_importances[:, top_idx]
cols = [feature_names[i] for i in top_idx]
# Truncate long names for display
cols_short = [c[-40:] if len(c) > 40 else c for c in cols]
sns.heatmap(data.T, ax=axes[0], xticklabels=[f"Fold {i+1}" for i in range(len(fold_importances))],
yticklabels=cols_short, cmap="YlOrRd", fmt=".3f", annot=True,
annot_kws={"size": 6}, linewidths=0.3)
axes[0].set_title("Normalised Importance per Fold (Top Features)")
axes[0].tick_params(axis='y', labelsize=6)
# CV bar chart
cv_top = cv[top_idx]
colours = ["#2ecc71" if stable_mask[i] else "#e74c3c" for i in top_idx]
axes[1].barh(range(top_n), cv_top[::-1], color=colours[::-1])
axes[1].set_yticks(range(top_n))
axes[1].set_yticklabels(cols_short[::-1], fontsize=6)
axes[1].axvline(x=cv.mean(), color="grey", linestyle="--", label=f"mean CV={cv.mean():.2f}")
axes[1].set_xlabel("Coefficient of Variation (lower = more stable)")
axes[1].set_title("Feature Stability (green=stable, red=unstable)")
axes[1].legend(fontsize=8)
plt.tight_layout()
out = Path(output_dir) / "fold_consistency.png"
plt.savefig(out, dpi=150, bbox_inches="tight")
plt.close()
print(f" Saved β {out}")
def plot_accuracy_vs_speed(results_df, output_dir):
"""Scatter plot: inference time (x) vs macro F1 (y), annotated by config label."""
fig, ax = plt.subplots(figsize=(12, 7))
# Colour by whether the config uses KL features
colours = ["#3498db" if "KL" in r["label"] else "#e67e22"
for _, r in results_df.iterrows()]
time_col = "est_total_ms" if "est_total_ms" in results_df.columns else "meta_overhead_ms"
scatter = ax.scatter(results_df[time_col], results_df["meta_f1"],
c=colours, s=120, alpha=0.85, edgecolors="white", linewidth=0.5)
for _, row in results_df.iterrows():
ax.annotate(row["label"], (row[time_col], row["meta_f1"]),
textcoords="offset points", xytext=(6, 3), fontsize=7)
ax.set_xlabel(f"Estimated Total Inference Time ({time_col}, ms) for {len(results_df)} samples")
ax.set_ylabel("Meta-Learner Macro F1 (OOF CV)")
ax.set_title("Accuracy vs Inference Speed\n(blue=KL involved, orange=CE only)")
ax.grid(True, alpha=0.3)
# Pareto frontier
pareto = _pareto_frontier(results_df[[time_col, "meta_f1"]].values)
if len(pareto) >= 2:
pareto = pareto[np.argsort(pareto[:, 0])]
ax.plot(pareto[:, 0], pareto[:, 1], "k--", linewidth=1.2, alpha=0.6,
label="Pareto frontier")
ax.legend(fontsize=9)
plt.tight_layout()
out = Path(output_dir) / "accuracy_vs_speed.png"
plt.savefig(out, dpi=150, bbox_inches="tight")
plt.close()
print(f" Saved β {out}")
def _pareto_frontier(points):
"""Return points on the Pareto frontier (minimise time, maximise F1)."""
dominated = np.zeros(len(points), dtype=bool)
for i in range(len(points)):
for j in range(len(points)):
if i == j: continue
# j dominates i if j is faster AND has >= F1
if points[j, 0] <= points[i, 0] and points[j, 1] >= points[i, 1]:
if points[j, 0] < points[i, 0] or points[j, 1] > points[i, 1]:
dominated[i] = True
break
return points[~dominated]
def plot_model_agreement(X, feature_names, ce_models, kl_models, n_classes, output_dir):
"""
Pairwise Spearman correlation between each model's argmax predictions.
Helps visualise which models are redundant.
"""
argmax_preds = {}
for m in ce_models:
idx = [i for i, f in enumerate(feature_names) if f.startswith(f"CE_{m}_") and "_entropy" not in f and "_argmax" not in f and "_kl" not in f and "_diff" not in f]
if idx:
probs = X[:, idx]
argmax_preds[f"CE_{m[:20]}"] = np.argmax(probs, axis=1)
for m in kl_models:
idx = [i for i, f in enumerate(feature_names) if f.startswith(f"KL_{m}_") and "_entropy" not in f and "_argmax" not in f and "_kl" not in f and "_diff" not in f]
if idx:
probs = X[:, idx]
argmax_preds[f"KL_{m[:20]}"] = np.argmax(probs, axis=1)
if len(argmax_preds) < 2:
return
keys = list(argmax_preds.keys())
n = len(keys)
corr_mat = np.eye(n)
for i in range(n):
for j in range(i+1, n):
rho, _ = spearmanr(argmax_preds[keys[i]], argmax_preds[keys[j]])
corr_mat[i, j] = corr_mat[j, i] = rho
fig, ax = plt.subplots(figsize=(max(6, n), max(5, n-1)))
sns.heatmap(corr_mat, xticklabels=keys, yticklabels=keys,
annot=True, fmt=".2f", cmap="coolwarm", vmin=-1, vmax=1, ax=ax,
linewidths=0.3)
ax.set_title("Pairwise Spearman Correlation of Model Argmax Predictions\n"
"(high correlation = redundant pair)")
plt.tight_layout()
out = Path(output_dir) / "model_agreement.png"
plt.savefig(out, dpi=150, bbox_inches="tight")
plt.close()
print(f" Saved β {out}")
# =============================================================================
# MAIN
# =============================================================================
# =============================================================================
# DEPLOYMENT EXPORT
# =============================================================================
def _export_deployment(export_row, results_df, out_dir, ce_configs, kl_configs,
df_ce, df_kl, y, idx_to_label, class_order,
extra_features_arr, n_classes, args, time_col_s):
"""
Re-train a meta-learner for the chosen config on the full training set and
write all deployment artifacts to out_dir/deployment/:
meta_learner.pkl - joblib-serialised MetaLearner
deployment_config.json - everything the inference script needs
"""
import joblib
export_dir = out_dir / "deployment"
export_dir.mkdir(exist_ok=True)
label = export_row["label"]
exp_mt = export_row["meta_type"]
exp_ce = [m for m in str(export_row.get("ce_models", "")).split(",") if m]
exp_kl = [m for m in str(export_row.get("kl_models", "")).split(",") if m]
print("\n Exporting deployment artifacts for:", label)
# Re-train on full training data (not just a fold)
exp_builder = OOFFeatureBuilder(
ce_df=df_ce, kl_df=df_kl,
ce_models=exp_ce, kl_models=exp_kl,
use_derived=args.use_derived_features,
ensemble_source="both",
class_order=class_order,
)
X_exp, fn_exp = exp_builder.build()
n_prob_exp = X_exp.shape[1]
if extra_features_arr is not None and extra_features_arr.shape[1] > 0:
X_exp = np.hstack([X_exp, extra_features_arr])
exp_meta = MetaLearner(exp_mt, n_classes, args.seed,
n_prob_cols=n_prob_exp).fit(X_exp, y)
meta_path = export_dir / "meta_learner.pkl"
joblib.dump({
"model": exp_meta,
"feature_names": fn_exp,
"n_prob_cols": n_prob_exp,
"n_classes": n_classes,
"class_order": class_order,
"idx_to_label": idx_to_label,
}, meta_path)
print(" meta_learner.pkl ->", meta_path)
# Per-model serving info: everything the inference script needs to load
# and run each model (architecture, tokenizer, fold paths, other_cols, dtype)
def _model_info(cname, source):
cfgs = ce_configs if source == "CE" else kl_configs
for c in cfgs:
if clean_name(c["model_name"]) == cname:
return c
return {}
def _verify_other_cols(model_name, artifacts_dir, declared_cols, split_unk):
"""
Cross-check declared other_cols against the actual trained checkpoint.
The checkpoint's head input width tells us whether tabular features were
used at training: a multimodal head has input dim = hidden + len(other_cols),
a plain head has input dim = hidden. If the declared other_cols disagree
with the checkpoint, the config is stale β trust the checkpoint and warn.
Returns the corrected other_cols (possibly cleared to []).
"""
if not artifacts_dir:
return declared_cols
try:
from safetensors.torch import load_file
safe_name = model_name.replace("/", "__")
if split_unk:
safe_name += "__stage1"
# Find fold_1 model dir
base = Path(artifacts_dir) / ("pretrained_checkpoints__" + safe_name)
if not base.exists():
base = Path(artifacts_dir) / safe_name
st = base / "fold_1" / "model" / "model.safetensors"
if not st.exists():
return declared_cols # can't verify, keep declared
sd = load_file(str(st))
# Find the head's input width
head_in = None
hidden = None
for k, v in sd.items():
kk = k[len("base_model."):] if k.startswith("base_model.") else k
first = kk.split(".", 1)[0]
if first in ("classifier", "feature_extractor") and kk.endswith(".weight"):
# First head linear: input width is v.shape[1]
if kk in ("classifier.0.weight", "feature_extractor.0.weight",
"classifier.weight"):
if head_in is None or kk.endswith("0.weight"):
head_in = v.shape[1]
# encoder hidden size: word embeddings width
if "embeddings.word_embeddings.weight" in kk:
hidden = v.shape[1]
if head_in is None or hidden is None:
return declared_cols
checkpoint_tab = head_in - hidden # tabular feature count in checkpoint
declared_tab = len(declared_cols or [])
if checkpoint_tab != declared_tab:
print(" [WARN] {}: declared other_cols={} ({} features) but "
"checkpoint head expects {} tabular features. "
"Trusting checkpoint.".format(
clean_name(model_name), declared_cols,
declared_tab, checkpoint_tab))
if checkpoint_tab <= 0:
return []
# checkpoint expects tab but declared has wrong count β keep declared
# names if count matches, else warn and keep as-is
return declared_cols
except Exception as e:
print(" [NOTE] Could not verify other_cols for {}: {}".format(
clean_name(model_name), e))
return declared_cols
def _portable(path):
"""Deployment configs must survive machine moves (VM1 <-> VM2 <-> HF).
Store artifact dirs relative to the project root (cwd at export time);
the inference script's resolver finds them via its cwd rule on any
machine. Absolute paths are kept only if outside the project tree."""
if not path:
return None
rp = Path(path).resolve()
try:
return str(rp.relative_to(Path.cwd()))
except ValueError:
return str(rp)
model_entries = []
for cname in exp_ce:
c = _model_info(cname, "CE")
ce_art = _portable(args.ce_artifacts_dir)
verified_cols = _verify_other_cols(
c.get("model_name", cname), ce_art,
c.get("other_cols", []), c.get("split_unknown_stage", False))
model_entries.append({
"source": "CE",
"clean_name": cname,
"model_name": c.get("model_name", cname),
"tokenizer_name": c.get("tokenizer_name"),
"task_type": c.get("task_type", "classification"),
"split_unknown_stage": c.get("split_unknown_stage", False),
"other_cols": verified_cols,
"drop_token_type_ids": c.get("drop_token_type_ids", False),
"use_fp16": c.get("use_fp16", False),
"use_bf16": c.get("use_bf16", False),
"artifacts_dir": ce_art,
})
for cname in exp_kl:
c = _model_info(cname, "KL")
kl_art = _portable(args.kl_artifacts_dir)
verified_cols = _verify_other_cols(
c.get("model_name", cname), kl_art,
c.get("other_cols", []), c.get("split_unknown_stage", False))
model_entries.append({
"source": "KL",
"clean_name": cname,
"model_name": c.get("model_name", cname),
"tokenizer_name": c.get("tokenizer_name"),
"task_type": c.get("task_type", "classification"),
"split_unknown_stage": c.get("split_unknown_stage", False),
"other_cols": verified_cols,
"drop_token_type_ids": c.get("drop_token_type_ids", False),
"use_fp16": c.get("use_fp16", False),
"use_bf16": c.get("use_bf16", False),
"artifacts_dir": kl_art,
})
# Store meta_learner_path as just the filename β it always lives next to
# the config. This makes the deployment dir portable (move it anywhere and
# inference still works without editing the JSON).
# artifacts_dir paths are absolute β they live outside the deployment dir.
# frozen_emb_cache: absolute path (may be in a different experiment subdir).
deployment_cfg = {
"label": label,
"meta_type": exp_mt,
"meta_f1_cv": float(export_row["meta_f1"]),
"est_total_ms": float(export_row.get(time_col_s, 0)),
"benchmark_n_samples": args.benchmark_n_samples,
"n_classes": n_classes,
"class_order": class_order,
"idx_to_label": {str(k): v for k, v in idx_to_label.items()},
"k_folds": args.k_folds,
"use_derived_features": args.use_derived_features,
"max_length": args.max_length,
"n_prob_cols": n_prob_exp,
"meta_learner_path": meta_path.name, # filename only β resolved relative to config dir
"models": model_entries,
"frozen_encoder": args.frozen_encoder,
"frozen_encoder_tokenizer": args.frozen_encoder_tokenizer,
"frozen_emb_n_components": args.frozen_emb_n_components if args.frozen_encoder else None,
"frozen_emb_cache": str(Path(args.frozen_emb_cache).resolve()) if args.frozen_encoder and args.frozen_emb_cache else None,
}
cfg_path = export_dir / "deployment_config.json"
with open(cfg_path, "w") as f:
json.dump(deployment_cfg, f, indent=2)
print(" deployment_config ->", cfg_path)
print("\n To run inference:")
print(" python meta_learner_inference.py \\")
print(" --config", cfg_path, "\\")
print(" --data_path <new_data.parquet> \\")
print(" --text_col text \\")
print(" --output_path predictions.parquet")
def main():
args = parse_args()
out_dir = Path(args.output_dir)
out_dir.mkdir(parents=True, exist_ok=True)
# ββ Fast export-only path βββββββββββββββββββββββββββββββββββββββββββββββββ
if args.export_only:
if not args.results_csv:
raise ValueError("--results_csv is required when --export_only is set.")
if not Path(args.results_csv).exists():
raise FileNotFoundError("results_csv not found: " + args.results_csv)
print("\n" + "="*60)
print("META-LEARNER TRAINER [export-only mode]")
print("="*60)
print("Loading existing results from:", args.results_csv)
results_df = pd.read_csv(args.results_csv)
best = results_df.sort_values("meta_f1", ascending=False).iloc[0]
# Minimal data reload for re-training the meta-learner
df_data = pd.read_parquet(args.data_path)
df_ce = pd.read_parquet(args.ce_oof_path) if args.ce_oof_path else None
df_kl = pd.read_parquet(args.kl_oof_path) if args.kl_oof_path else None
mapping = load_mapping(args.mapping_dict_path)
known = sorted([(k, v) for k, v in mapping.items() if v >= 0], key=lambda x: x[1])
unknown = [(k, v) for k, v in mapping.items() if v < 0]
n_known = len(known)
label_to_idx = {}
for new_idx, (label_str, _) in enumerate(known):
label_to_idx[label_str] = new_idx
for i, (label_str, _) in enumerate(unknown):
label_to_idx[label_str] = n_known + i
idx_to_label = {v: k for k, v in label_to_idx.items()}
n_classes = len(label_to_idx)
class_order = get_class_order_from_mapping(mapping)
raw_labels = df_data[args.label_col].astype(str).values
valid_mask = np.array([l in label_to_idx for l in raw_labels])
y = np.array([label_to_idx[l] for l in raw_labels[valid_mask]])
if df_ce is not None:
df_ce = df_ce.iloc[valid_mask].reset_index(drop=True)
if df_kl is not None:
df_kl = df_kl.iloc[valid_mask].reset_index(drop=True)
# Load configs
ce_configs = get_active_models(args.ce_config_path) if args.ce_config_path else []
kl_configs = get_active_models(args.kl_config_path) if args.kl_config_path else []
# Load frozen embeddings if applicable
extra_features_arr = None
if args.frozen_encoder and args.frozen_emb_cache:
cache = Path(args.frozen_emb_cache)
if cache.exists():
print("Loading cached frozen embeddings from:", args.frozen_emb_cache)
emb_df = pd.read_parquet(args.frozen_emb_cache)
extra_features_arr = emb_df.values[valid_mask]
else:
print("[WARN] frozen_emb_cache not found β embeddings will not be included.")
# Pick export row
if args.export_label:
match = results_df[results_df["label"] == args.export_label]
export_row = match.iloc[0] if not match.empty else best
if match.empty:
print("[WARN] --export_label not found; using best F1 config.")
else:
export_row = best
time_col_s = "est_total_ms" if "est_total_ms" in results_df.columns else "meta_overhead_ms"
_export_deployment(
export_row=export_row, results_df=results_df, out_dir=out_dir,
ce_configs=ce_configs, kl_configs=kl_configs,
df_ce=df_ce, df_kl=df_kl, y=y, idx_to_label=idx_to_label,
class_order=class_order, extra_features_arr=extra_features_arr,
n_classes=n_classes, args=args, time_col_s=time_col_s,
)
return
# ββ Full training path ββββββββββββββββββββββββββββββββββββββββββββββββββββ
print("\n" + "="*60)
print("META-LEARNER TRAINER")
print("="*60)
# --- Load data ---
print("\n[1] Loading data...")
df_data = pd.read_parquet(args.data_path)
df_ce = pd.read_parquet(args.ce_oof_path) if args.ce_oof_path else None
df_kl = pd.read_parquet(args.kl_oof_path) if args.kl_oof_path else None
mapping = load_mapping(args.mapping_dict_path)
# Encode labels exactly as the generator does:
# known classes (value >= 0): 0-based index = value - ordinal_min_label
# unknown classes (value < 0): placed last, index = n_known_classes + i
# valid_mask keeps any row whose label string is a key in mapping.
# Rows whose label string is not in mapping at all (e.g. NaN coerced to "nan") are dropped.
known = sorted([(k, v) for k, v in mapping.items() if v >= 0], key=lambda x: x[1])
unknown = [(k, v) for k, v in mapping.items() if v < 0]
n_known = len(known)
label_to_idx = {}
for new_idx, (label_str, _) in enumerate(known):
label_to_idx[label_str] = new_idx # "ON_MAIN_STREET" -> 0, etc.
for i, (label_str, _) in enumerate(unknown):
label_to_idx[label_str] = n_known + i # "UNKNOWN" -> 5
idx_to_label = {v: k for k, v in label_to_idx.items()}
n_classes = len(label_to_idx)
raw_labels = df_data[args.label_col].astype(str).values
valid_mask = np.array([l in label_to_idx for l in raw_labels])
if not valid_mask.all():
dropped = (~valid_mask).sum()
examples = list(set(raw_labels[~valid_mask]))[:5]
print(f" Dropping {dropped} rows with label strings not in mapping. Examples: {examples}")
y = np.array([label_to_idx[l] for l in raw_labels[valid_mask]])
print(f" Label mapping (from mapping.json):")
for idx in range(n_classes):
lbl = idx_to_label[idx]
count = int((y == idx).sum())
print(f" class {idx}: '{lbl}' [{count:,} samples]")
# Align all dataframes to valid rows
if df_ce is not None:
df_ce = df_ce.iloc[valid_mask].reset_index(drop=True)
if df_kl is not None:
df_kl = df_kl.iloc[valid_mask].reset_index(drop=True)
print(f" Samples: {len(y):,} | Classes: {n_classes}")
# --- Load configs ---
ce_configs = get_active_models(args.ce_config_path) if args.ce_config_path else []
ce_model_names = [clean_name(c["model_name"]) for c in ce_configs]
kl_model_names = []
if args.kl_config_path:
kl_configs = get_active_models(args.kl_config_path)
kl_model_names = [clean_name(c["model_name"]) for c in kl_configs]
# Apply model_subset filter
model_subset = None
if args.model_subset:
model_subset = [s.strip() for s in args.model_subset.split(",")]
print(f" Filtering to subset: {model_subset}")
print(f" CE models: {ce_model_names}")
print(f" KL models: {kl_model_names}")
# --- Build features ---
print("\n[2] Building OOF feature matrix...")
class_order = get_class_order_from_mapping(mapping)
builder = OOFFeatureBuilder(
ce_df=df_ce,
kl_df=df_kl,
ce_models=ce_model_names,
kl_models=kl_model_names,
model_subset=model_subset,
use_derived=args.use_derived_features,
ensemble_source=args.ensemble_source,
class_order=class_order,
)
X, feature_names = builder.build()
print(f" Feature matrix shape: {X.shape}")
print(f" Feature groups:")
for prefix in ["CE_", "KL_", "CE_KL_", "CE_pair_"]:
count = sum(1 for f in feature_names if f.startswith(prefix))
if count:
print(f" {prefix:<12} {count} features")
# Sanity check: class_order (from mapping) drives both y encoding and column ordering.
# Both should always be β now. Printed so any future regression is immediately visible.
print(f" Label β OOF column alignment (class_order from mapping):")
all_ok = True
for i, cls in enumerate(class_order):
expected_y_label = idx_to_label.get(i, "???")
ok = (cls == expected_y_label)
tag = "β" if ok else f"β y has '{expected_y_label}'"
if not ok: all_ok = False
count = int((y == i).sum())
print(f" class {i}: '{cls}' {tag} [{count:,} samples]")
if all_ok:
print(" All aligned.")
print()
# --- Embedding features (Options 2 and 3) ---
extra_features_arr = None # populated below if any embedding flags are set
X_oof_emb = np.zeros((len(y), 0), dtype=np.float32)
X_frozen = np.zeros((len(y), 0), dtype=np.float32)
emb_needs_text = args.use_oof_embeddings or args.frozen_encoder
if emb_needs_text and not args.text_col:
raise ValueError("--text_col is required when using --use_oof_embeddings "
"or --frozen_encoder.")
if emb_needs_text:
all_texts = df_data.iloc[valid_mask][args.text_col].fillna("").tolist()
emb_device = _normalise_device(args.benchmark_device)
if args.use_oof_embeddings:
need_dirs = (not args.ce_artifacts_dir and not args.kl_artifacts_dir)
if need_dirs:
raise ValueError("--use_oof_embeddings requires at least one of "
"--ce_artifacts_dir / --kl_artifacts_dir.")
print("\n[2b] Extracting OOF embeddings (Option 2)...")
X_oof_emb, oof_emb_names = extract_oof_embeddings(
ce_configs = ce_configs,
kl_configs = kl_configs,
ce_artifacts_dir = args.ce_artifacts_dir,
kl_artifacts_dir = args.kl_artifacts_dir,
texts = all_texts,
y = y,
max_length = args.max_length,
device = emb_device,
n_components = args.oof_emb_n_components,
batch_size = args.oof_emb_batch_size,
k_folds = args.k_folds,
seed = args.seed,
ce_cache = args.oof_emb_ce_cache,
kl_cache = args.oof_emb_kl_cache,
)
if X_oof_emb.shape[1] > 0:
X = np.hstack([X, X_oof_emb])
feature_names = feature_names + oof_emb_names
print(" Added {} OOF embedding features. "
"Total features: {}".format(len(oof_emb_names), X.shape[1]))
if args.frozen_encoder:
print("\n[2c] Extracting frozen encoder embeddings (Option 3)...")
X_frozen, frozen_names = extract_frozen_embeddings(
model_name = args.frozen_encoder,
tokenizer_name = args.frozen_encoder_tokenizer,
texts = all_texts,
max_length = args.max_length,
device = emb_device,
n_components = args.frozen_emb_n_components,
batch_size = args.frozen_emb_batch_size,
cache_path = args.frozen_emb_cache,
)
if X_frozen.shape[1] > 0:
X = np.hstack([X, X_frozen])
feature_names = feature_names + frozen_names
print(" Added {} frozen embedding features. "
"Total features: {}".format(len(frozen_names), X.shape[1]))
# Collect fixed embedding features to pass into greedy selection and sweep.
# These are "always-on" at serving time β every request runs these encoders
# regardless of which base models are selected.
extra_feature_parts = []
if args.use_oof_embeddings and "X_oof_emb" in dir():
if X_oof_emb.shape[1] > 0:
extra_feature_parts.append(X_oof_emb)
if args.frozen_encoder and "X_frozen" in dir():
if X_frozen.shape[1] > 0:
extra_feature_parts.append(X_frozen)
extra_features_arr = (np.hstack(extra_feature_parts)
if extra_feature_parts else None)
if extra_features_arr is not None:
print(" Fixed embedding features for sweep/greedy: {} dims".format(
extra_features_arr.shape[1]))
# --- Model agreement plot ---
print("\n[3] Plotting model agreement...")
plot_model_agreement(X, feature_names,
builder._ce_active, builder._kl_active,
n_classes, out_dir)
# --- Fold consistency analysis ---
print("\n[4] Running fold consistency analysis...")
# n_prob_cols: columns that are valid probability distributions.
# Embedding columns appended after are real-valued and not prob distributions.
n_prob_cols = X.shape[1] - (extra_features_arr.shape[1]
if extra_features_arr is not None else 0)
fold_importances, cv, stable_mask, fold_f1s = fold_consistency_analysis(
X=X,
y=y,
feature_names=feature_names,
meta_type=args.meta_type,
n_classes=n_classes,
k_folds=args.k_folds,
seed=args.seed,
threshold=args.fold_consistency_threshold,
n_prob_cols=n_prob_cols,
)
if fold_importances is not None:
plot_fold_consistency(fold_importances, cv, feature_names, stable_mask, out_dir)
# Save stability report
stability_df = pd.DataFrame({
"feature": list(feature_names)[:fold_importances.shape[1]],
"mean_importance": fold_importances.mean(axis=0),
"std_importance": fold_importances.std(axis=0),
"cv": cv,
"stable": stable_mask,
}).sort_values("mean_importance", ascending=False)
stability_df.to_csv(out_dir / "feature_stability.csv", index=False)
print(f" Saved β {out_dir / 'feature_stability.csv'}")
# --- Train final meta-learner on stable features ---
print("\n[5] Training final meta-learner...")
X_final = X
if stable_mask is not None and len(stable_mask) != X.shape[1]:
# weighted_avg importances (hence this mask) cover only the leading
# prob columns; column selection would also break the per-model
# n_classes block structure its blending relies on. Keep all features.
print(" Stability mask covers %d of %d columns (weighted_avg "
"prob-cols only) β skipping stable-feature selection."
% (len(stable_mask), X.shape[1]))
stable_mask = None
if stable_mask is not None and stable_mask.any() and stable_mask.sum() > n_classes:
print(f" Using {stable_mask.sum()} stable features out of {X.shape[1]}")
X_final = X[:, stable_mask]
feature_names_final = [f for f, s in zip(feature_names, stable_mask) if s]
else:
print(" Using all features (stable mask not applicable or too few stable).")
feature_names_final = feature_names
final_meta = MetaLearner(args.meta_type, n_classes, args.seed,
n_prob_cols=n_prob_cols).fit(X_final, y)
final_preds = np.argmax(final_meta.predict_proba(X_final), axis=1)
final_f1 = precision_recall_fscore_support(y, final_preds, average="macro",
zero_division=0)[2]
print(f" Final meta-learner (train) Macro F1: {final_f1:.4f}")
print(f" Cross-val Macro F1: {np.mean(fold_f1s):.4f} Β± {np.std(fold_f1s):.4f}")
# --- Accuracy vs Speed sweep ---
print("\n[6] Accuracy vs Inference Speed analysis...")
bm_idx = np.random.default_rng(args.seed).choice(
len(X), size=min(args.benchmark_n_samples, len(X)), replace=False)
# Build per-model latency map by loading and timing each checkpoint
latency_map = {}
has_latency = args.ce_artifacts_dir or args.kl_artifacts_dir
if has_latency:
if not args.text_col:
raise ValueError("--text_col is required when --ce_artifacts_dir or "
"--kl_artifacts_dir is provided.")
texts_for_bench = df_data.iloc[valid_mask][args.text_col].fillna("").tolist()
texts_for_bench = [texts_for_bench[i] for i in bm_idx]
print(f" Benchmarking base model latency on {len(texts_for_bench)} samples "
f"(device={args.benchmark_device}, repeats={args.benchmark_repeats})...")
latency_map = build_latency_map(
ce_configs = ce_configs if args.ce_artifacts_dir else [],
kl_configs = kl_configs if args.kl_artifacts_dir else [],
ce_artifacts_dir = args.ce_artifacts_dir,
kl_artifacts_dir = args.kl_artifacts_dir,
ce_metadata_path = args.ce_metadata_path,
kl_metadata_path = args.kl_metadata_path,
texts = texts_for_bench,
max_length = args.max_length,
device = args.benchmark_device,
n_repeats = args.benchmark_repeats,
)
print(f" Latency map ({len(latency_map)} models):")
for k, v in sorted(latency_map.items()):
print(f" {k:<60s} {v:.1f} ms / {len(texts_for_bench)} samples")
else:
print(" NOTE: --ce_artifacts_dir / --kl_artifacts_dir not provided.")
print(" Only meta overhead is timed. Transformer latency dominates in production.")
print(" Re-run with those flags for realistic per-model timing.")
# Measure inference-time latency of embedding encoders.
# These run on EVERY request at serving time regardless of which base models
# are selected β they are a fixed overhead added to every config's total_ms.
# The parquet cache is only for training; at serving time you re-run them.
extra_inference_ms = 0.0
extra_notes = []
if args.frozen_encoder and has_latency:
print(" Timing frozen encoder inference latency...")
frozen_ms = benchmark_transformer_model(
original_model_name = args.frozen_encoder,
tokenizer_name = args.frozen_encoder_tokenizer,
texts = texts_for_bench,
max_length = args.max_length,
device = args.benchmark_device,
n_repeats = args.benchmark_repeats,
use_fp16 = False,
use_bf16 = False,
)
extra_inference_ms += frozen_ms
extra_notes.append("frozen_encoder={:.1f}ms".format(frozen_ms))
print(" Frozen encoder: {:.1f} ms / {} samples".format(
frozen_ms, len(texts_for_bench)))
if args.use_oof_embeddings and has_latency:
# OOF encoders at serving time = run each fine-tuned base model a second
# time to extract embeddings. We approximate as the sum of CE encoder
# latencies (stage1 for split_unknown models) since those are already
# in latency_map and represent the same forward pass cost.
oof_enc_ms = 0.0
for cfg in ce_configs:
if not cfg.get("use", True): continue
if cfg.get("task_type") == "tfidf_lgbm": continue
cname = clean_name(cfg["model_name"])
key = "CE:" + cname
if key in latency_map:
oof_enc_ms += latency_map[key]
extra_inference_ms += oof_enc_ms
extra_notes.append("oof_emb_encoders={:.1f}ms".format(oof_enc_ms))
print(" OOF embedding encoder overhead: {:.1f} ms / {} samples".format(
oof_enc_ms, len(texts_for_bench)))
if extra_notes:
print(" Fixed inference overhead per request: {:.1f} ms ({})".format(
extra_inference_ms, ", ".join(extra_notes)))
else:
extra_inference_ms = 0.0
# --- Complementarity table (always computed, cheap) ---
all_tagged = ([(m, "CE") for m in builder._ce_active] +
[(m, "KL") for m in builder._kl_active])
# Build base-probs-only feature matrix for complementarity (no derived features)
b_base = OOFFeatureBuilder(
ce_df=df_ce, kl_df=df_kl,
ce_models=builder._ce_active, kl_models=builder._kl_active,
use_derived=False, ensemble_source="both", class_order=class_order)
X_base, _ = b_base.build()
comp_df = compute_complementarity_matrix(X_base, y, all_tagged, n_classes)
comp_path = out_dir / "complementarity.csv"
comp_df.to_csv(comp_path, index=False)
print(" Model pair complementarity (top-10 most complementary pairs):")
print(comp_df.head(10).to_string(index=False))
print(" Full table saved ->", comp_path)
# --- Subset generation and meta-type comparison ---
# When --compare_meta_types: run greedy selection for every meta-learner type
# so the comparison reflects (learner, subset) pairs β not just which learner
# wins on the full feature set. Different learners may reach their plateau with
# different numbers of models. Results are merged into a single sweep table.
#
# Without --compare_meta_types: run greedy/exhaustive for --meta_type only.
META_TYPES = ["ridge", "logistic", "weighted_avg", "lgbm", "mlp"]
types_to_run = META_TYPES if args.compare_meta_types else [args.meta_type]
results = []
all_subset_configs = {} # meta_type -> list of (label, ce_sub, kl_sub)
for mt in types_to_run:
if args.compare_meta_types:
print()
print(" ---- meta_type:", mt, "----")
if args.selection_strategy == "greedy":
mt_configs = greedy_forward_selection(
X_full=X_base, y=y,
tagged=all_tagged,
n_classes=n_classes,
class_order=class_order,
df_ce=df_ce, df_kl=df_kl,
use_derived=args.use_derived_features,
meta_type=mt,
k_folds=args.k_folds,
seed=args.seed,
max_models=args.greedy_max_models,
min_gain=args.greedy_min_gain,
extra_features=extra_features_arr,
)
print(" Greedy selected", len(mt_configs), "configs for", mt)
else:
mt_configs = build_subset_configs(
builder._ce_active, builder._kl_active,
max_combo_size=args.max_combo_size,
)
if mt == types_to_run[0]:
print(" Exhaustive:", len(mt_configs),
"subsets (max_combo_size={})".format(args.max_combo_size))
all_subset_configs[mt] = mt_configs
# Flatten: tag each config with its meta_type for the results table
sweep_tasks = [] # (meta_type, label, ce_sub, kl_sub)
seen_labels = set()
for mt, cfgs in all_subset_configs.items():
for label, ce_sub, kl_sub in cfgs:
tagged_label = label if not args.compare_meta_types else mt + "/" + label
sweep_tasks.append((mt, tagged_label, ce_sub, kl_sub))
seen_labels.add(tagged_label)
# When only one meta_type, deduplicate configs evaluated multiple times
if not args.compare_meta_types:
seen = set()
deduped = []
for task in sweep_tasks:
key = (task[0], frozenset(task[2]), frozenset(task[3]))
if key not in seen:
seen.add(key)
deduped.append(task)
sweep_tasks = deduped
kfold_cv = StratifiedKFold(n_splits=args.k_folds, shuffle=True, random_state=args.seed)
# Build a lookup of pre-computed single-model OOF F1 scores.
# For single-model sweep configs the meta-learner is a no-op, so we skip
# expensive CV and use the pre-computed OOF F1 directly.
#
# Source: metadata.json (written by the generator), NOT the config file.
# The config no longer stores oof_f1 β that was removed to keep configs
# immutable. metadata.json is the canonical record of training results.
def _load_f1_from_metadata(meta_path):
"""Return {clean_name: oof_f1} from a metadata.json, or {} if unavailable."""
if not meta_path or not Path(meta_path).exists():
return {}
with open(meta_path) as f:
meta = json.load(f)
names = meta.get("model_names", [])
scores = meta.get("f1_scores", [])
return {clean_name(n): float(s) for n, s in zip(names, scores)}
ce_f1_map = _load_f1_from_metadata(args.ce_metadata_path)
kl_f1_map = _load_f1_from_metadata(args.kl_metadata_path)
single_model_f1: dict = {} # "CE:<cname>" | "KL:<cname>" -> oof_f1
for cfg in ce_configs:
cname = clean_name(cfg["model_name"])
if cname in ce_f1_map:
single_model_f1["CE:" + cname] = ce_f1_map[cname]
for cfg in kl_configs:
cname = clean_name(cfg["model_name"])
if cname in kl_f1_map:
single_model_f1["KL:" + cname] = kl_f1_map[cname]
if single_model_f1:
print(" Single-model F1 loaded from metadata ({} models):".format(
len(single_model_f1)))
for k, v in sorted(single_model_f1.items()):
print(" {:<55s} {:.4f}".format(k, v))
else:
print(" [NOTE] No single-model F1 from metadata "
"(--ce_metadata_path / --kl_metadata_path not set or files missing).")
print(" Single-model configs will run full CV instead of using cached F1.")
for mt, label, ce_sub, kl_sub in sweep_tasks:
n_base_models = len(ce_sub) + len(kl_sub)
# --- Fast path: single-model configs ---
# The meta-learner sees only one model's OOF probs -> it cannot improve on
# the model's own OOF F1. Skip CV and read from metadata directly.
# (weighted_avg weight = [1.0], ridge/logistic β identity on well-calibrated
# probs, lgbm/mlp may marginally differ but not worth the compute.)
if n_base_models == 1:
key = ("CE:" + ce_sub[0]) if ce_sub else ("KL:" + kl_sub[0])
if key in single_model_f1:
mean_f1 = single_model_f1[key]
cv_f1s = [mean_f1] # single value β std will be 0
# Still time the meta overhead (fast, just one predict call)
sub_builder = OOFFeatureBuilder(
ce_df=df_ce, kl_df=df_kl,
ce_models=ce_sub, kl_models=kl_sub,
use_derived=args.use_derived_features,
ensemble_source="both", class_order=class_order)
try:
X_sub, _ = sub_builder.build()
except ValueError:
continue
n_prob_sub = X_sub.shape[1]
if extra_features_arr is not None and extra_features_arr.shape[1] > 0:
X_sub = np.hstack([X_sub, extra_features_arr])
m_bench = MetaLearner(mt, n_classes, args.seed,
n_prob_cols=n_prob_sub).fit(X_sub, y)
base_ms, missing = lookup_subset_latency(ce_sub, kl_sub, latency_map, extra_inference_ms)
meta_med_ms, _ = benchmark_inference(X_sub[bm_idx], m_bench, n_repeats=20)
meta_med_ms *= 1000
total_ms = base_ms + meta_med_ms
total_per_smp = total_ms / max(len(bm_idx), 1)
tag_str = label + " [F1 from metadata]"
print(" ", tag_str)
if has_latency:
print(" F1={:.4f} models={} transformer={:.1f}ms "
"meta={:.2f}ms total={:.1f}ms / {} samples".format(
mean_f1, n_base_models, base_ms,
meta_med_ms, total_ms, len(bm_idx)))
else:
print(" F1={:.4f} models={} meta_overhead={:.2f}ms".format(
mean_f1, n_base_models, meta_med_ms))
results.append({
"label": label, "meta_type": mt,
"ce_models": ",".join(ce_sub), "kl_models": ",".join(kl_sub),
"n_models": n_base_models, "meta_f1": round(mean_f1, 4),
"f1_std": 0.0,
"base_model_ms": round(base_ms - extra_inference_ms, 2),
"extra_enc_ms": round(extra_inference_ms, 2),
"transformer_ms": round(base_ms, 2),
"meta_overhead_ms": round(meta_med_ms, 3),
"est_total_ms": round(total_ms, 2),
"ms_per_sample": round(total_per_smp, 5),
})
continue # skip the full CV block below
sub_builder = OOFFeatureBuilder(
ce_df=df_ce, kl_df=df_kl,
ce_models=ce_sub, kl_models=kl_sub,
use_derived=args.use_derived_features,
ensemble_source="both",
class_order=class_order,
)
try:
X_sub, fn_sub = sub_builder.build()
except ValueError:
continue
# Append fixed embedding features (frozen encoder, OOF embeddings).
# These are identical for every subset β they don't depend on which
# base models are selected, only on the text input.
n_prob_sub = X_sub.shape[1] # record before appending embeddings
if extra_features_arr is not None and extra_features_arr.shape[1] > 0:
X_sub = np.hstack([X_sub, extra_features_arr])
# CV F1 β use the meta_type for this task, not the global --meta_type
cv_f1s = []
for tr_idx, val_idx in kfold_cv.split(X_sub, y):
m = MetaLearner(mt, n_classes, args.seed,
n_prob_cols=n_prob_sub).fit(X_sub[tr_idx], y[tr_idx])
preds = np.argmax(m.predict_proba(X_sub[val_idx]), axis=1)
f1 = precision_recall_fscore_support(y[val_idx], preds, average="macro",
zero_division=0)[2]
cv_f1s.append(f1)
mean_f1 = np.mean(cv_f1s)
# Meta overhead β use the task's meta_type
m_bench = MetaLearner(mt, n_classes, args.seed,
n_prob_cols=n_prob_sub).fit(X_sub, y)
X_bm = X_sub[bm_idx]
meta_med_ms, _ = benchmark_inference(X_bm, m_bench, n_repeats=20)
meta_med_ms *= 1000
# Per-model transformer latency (sum over all models in subset)
n_base_models = len(ce_sub) + len(kl_sub)
base_ms, missing = lookup_subset_latency(ce_sub, kl_sub, latency_map, extra_inference_ms)
total_ms = base_ms + meta_med_ms
total_per_smp = total_ms / max(len(bm_idx), 1)
if missing and has_latency:
print(f" {label} [WARN missing latency for: {missing}]")
else:
print(f" {label}")
if has_latency:
print(f" F1={mean_f1:.4f} models={n_base_models} "
f"transformer={base_ms:.1f}ms meta={meta_med_ms:.2f}ms "
f"total={total_ms:.1f}ms / {len(bm_idx)} samples")
else:
print(f" F1={mean_f1:.4f} models={n_base_models} "
f"meta_overhead={meta_med_ms:.2f}ms (β transformer latency not measured)")
results.append({
"label": label,
"meta_type": mt,
"ce_models": ",".join(ce_sub),
"kl_models": ",".join(kl_sub),
"n_models": n_base_models,
"meta_f1": round(mean_f1, 4),
"f1_std": round(np.std(cv_f1s), 4),
"base_model_ms": round(base_ms - extra_inference_ms, 2),
"extra_enc_ms": round(extra_inference_ms, 2),
"transformer_ms": round(base_ms, 2),
"meta_overhead_ms": round(meta_med_ms, 3),
"est_total_ms": round(total_ms, 2),
"ms_per_sample": round(total_per_smp, 5),
})
results_df = pd.DataFrame(results).sort_values("meta_f1", ascending=False)
results_df.to_csv(out_dir / "accuracy_vs_speed.csv", index=False)
print(f"\n Saved β {out_dir / 'accuracy_vs_speed.csv'}")
print("\n Top configs by F1:")
display_cols = ["meta_type", "label", "meta_f1", "f1_std",
"base_model_ms", "extra_enc_ms", "meta_overhead_ms",
"est_total_ms", "n_models"]
display_cols = [c for c in display_cols if c in results_df.columns]
print(results_df[display_cols].to_string(index=False))
plot_accuracy_vs_speed(results_df, out_dir)
# --- Summary ---
print("\n" + "="*60)
print("SUMMARY")
print("="*60)
best = results_df.iloc[0]
time_col_s = "est_total_ms" if "est_total_ms" in results_df.columns else "meta_overhead_ms"
pareto_pts = _pareto_frontier(results_df[[time_col_s, "meta_f1"]].values)
fastest_pareto_ms = min(p[0] for p in pareto_pts)
fastest_pareto = results_df[results_df[time_col_s] == fastest_pareto_ms].iloc[0]
print(f" Best F1 config : {best['label']} "
f"(F1={best['meta_f1']:.4f}, total={best[time_col_s]:.1f}ms / {args.benchmark_n_samples} samples)")
print(f" Fastest Pareto cfg : {fastest_pareto['label']} "
f"(F1={fastest_pareto['meta_f1']:.4f}, total={fastest_pareto[time_col_s]:.1f}ms / {args.benchmark_n_samples} samples)")
print(f"\n Outputs in: {out_dir}/")
print("="*60)
# --- Deployment export ---
# Select config row to export (explicit label or best F1)
if args.export_label:
match = results_df[results_df["label"] == args.export_label]
export_row = match.iloc[0] if not match.empty else best
if match.empty:
print("[WARN] --export_label not found; exporting best F1 config.")
else:
export_row = best
_export_deployment(
export_row = export_row,
results_df = results_df,
out_dir = out_dir,
ce_configs = ce_configs,
kl_configs = kl_configs,
df_ce = df_ce,
df_kl = df_kl,
y = y,
idx_to_label = idx_to_label,
class_order = class_order,
extra_features_arr = extra_features_arr,
n_classes = n_classes,
args = args,
time_col_s = time_col_s,
)
if __name__ == "__main__":
main() |