File size: 104,801 Bytes
4f2fd46 7e9f31f 4f2fd46 196a33b 4f2fd46 196a33b 4f2fd46 196a33b 4f2fd46 196a33b 4f2fd46 196a33b 4f2fd46 196a33b 4f2fd46 196a33b 4f2fd46 196a33b 4f2fd46 196a33b 4f2fd46 196a33b 4f2fd46 196a33b 4f2fd46 196a33b 4f2fd46 196a33b 4f2fd46 196a33b 4f2fd46 196a33b 4f2fd46 196a33b 4f2fd46 196a33b 4f2fd46 196a33b 4f2fd46 196a33b 4f2fd46 196a33b 4f2fd46 196a33b 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 | #!/usr/bin/env python3
"""
Heterogeneous Ensemble Distillation Generator
This script takes a dataset and an ensemble configuration (JSON), trains K-Fold Out-Of-Fold (OOF)
models for each configuration, mathematically merges their probability distributions (handling
2-stage Unknown vs Known logic), and exports a Parquet file with generated soft labels.
Usage:
python scripts/ensemble_distillation_generator.py \
--data_path data/dist_to_main_street.parquet \
--text_col text \
--label_col dist_to_main_street \
--mapping_dict_path configs/distance_mapping.json \
--unknown_label_value UNKNOWN \
--ordinal_num_classes 5 \
--ensemble_config_path configs/ce_ensemble.json \
--artifacts_dir experiments/ce_v1/artifacts \
--ensemble_output_path experiments/ce_v1/oof_predictions.parquet \
--metadata_path experiments/ce_v1/metadata.json
# Outputs written to experiments/ce_v1/:
# artifacts/ β fold checkpoints, one dir per model
# oof_predictions.parquet β OOF probability columns
# metadata.json β model names + OOF F1 scores
# run_config.json β frozen snapshot of input config + CLI args
# ensemble_log_*.txt β training log
#
# Input configs/ce_ensemble.json is NEVER modified.
# Resume a partial run by re-running with the same command β
# models with existing artifacts are skipped automatically.
"""
# =============================================================================
# LABEL MAPPING CONVENTION (read this before creating a new task!)
#
# The --mapping_dict_path json MUST contain EVERY label value present in the
# data, in this form (example from condition_tier):
#
# { "N": -1, "D": 1, "C": 2, "B": 3, "A": 4 }
#
# * UNKNOWN class -> value -1 (sentinel: "not part of the ordinal scale").
# It must ALSO be named via --unknown_label_value. Omitting it from the
# mapping makes label lookup produce NaN and crashes at astype(int).
# * Known classes -> 1-indexed integers whose ORDER defines the ordinal
# scale (1 = one end, N = the other; e.g. worst -> best).
#
# OUTPUT COLUMN ORDER produced everywhere downstream (oof_probs.npy,
# *_logprob_* columns, soft labels, deployment prob_* columns):
#
# [ known classes sorted by mapping value ASCENDING, then UNKNOWN last ]
#
# e.g. condition_tier: [D, C, B, A, N]
# dist_to_main_street: [ON_MAIN_STREET, ADJACENT, NEAR, MODERATE, FAR, UNKNOWN]
#
# Any consumer that hard-codes a class list must match this order exactly.
# (Forensic note: the May-2026 condition_tier "phobert collapse", F1 0.087,
# was an eval comparing against this order REVERSED; true F1 was 0.9008.)
# =============================================================================
import signal
import atexit
import pickle
import matplotlib.pyplot as plt
import seaborn as sns
import argparse
import gc
import json
import warnings
import sys
import copy
import shutil
from pathlib import Path
import numpy as np
import pandas as pd
import os
# Reduce CUDA allocator fragmentation (mid-run OOM with dynamic-padding batches
# on tight GPUs). Must be set before torch initialises CUDA; a value already
# set in the shell takes precedence.
os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True")
import torch
import torch.nn as nn
from datasets import Dataset
import datasets
from sklearn.metrics import accuracy_score, precision_recall_fscore_support, mean_absolute_error
from sklearn.preprocessing import StandardScaler
from sklearn.utils.class_weight import compute_class_weight
from sklearn.model_selection import StratifiedKFold
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.calibration import CalibratedClassifierCV
from scipy.sparse import hstack, csr_matrix
from torch.utils.data import WeightedRandomSampler
import lightgbm as lgb
from transformers import (
AutoModelForSequenceClassification,
AutoModel,
AutoTokenizer,
EarlyStoppingCallback,
Trainer,
TrainingArguments,
TrainerCallback,
)
warnings.filterwarnings("ignore")
# =============================================================================
# CLEAN LOGGER
# =============================================================================
import re
from datetime import datetime
class LoggerTee(object):
def __init__(self, filename, mode="a"):
self.terminal = sys.stdout
self.log = open(filename, mode)
self.line_buffer = ""
self.ansi_escape = re.compile(r'\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])')
self.tqdm_pattern = re.compile(r'\b\d+%\s*\|')
def write(self, message):
self.terminal.write(message)
for char in message:
if char == '\r':
self.line_buffer = ""
elif char == '\n':
clean_line = self.ansi_escape.sub('', self.line_buffer)
if self.tqdm_pattern.search(clean_line):
if "100%|" not in clean_line.replace(" ", ""):
self.line_buffer = ""
continue
self.log.write(clean_line + '\n')
self.log.flush()
self.line_buffer = ""
else:
self.line_buffer += char
def flush(self):
self.terminal.flush()
self.log.flush()
def isatty(self):
return self.terminal.isatty()
# Log file starts in cwd (args not parsed yet); main() moves it into artifacts_dir.
timestamp = datetime.now().strftime("%Y%m%d_%H%M")
log_filename = f"ensemble_log_{timestamp}.txt"
sys.stdout = LoggerTee(filename=log_filename)
sys.stderr = sys.stdout
# =============================================================================
# ARGUMENT PARSING
# =============================================================================
def parse_args():
parser = argparse.ArgumentParser(description="Generate Ensemble Soft Labels via K-Fold OOF Predictions.")
# --- Data ---
parser.add_argument("--data_path", type=str, required=True)
parser.add_argument("--text_col", type=str, required=True)
parser.add_argument("--label_col", type=str, required=True)
parser.add_argument("--mapping_dict_path", type=str, required=True)
parser.add_argument("--unknown_label_value", type=str, default="N")
parser.add_argument("--ordinal_num_classes", type=int, required=True)
parser.add_argument("--training_mode", type=str, default="kfold",
choices=["kfold", "final"],
help="kfold: K-fold CV producing OOF predictions (default, "
"resource-heavy at serving: K checkpoints per model). "
"final: ONE stratified holdout of --val_rows_per_class "
"rows per class; each model trains once on the rest and "
"is saved under <artifact>/final/model/ β 1/K serving "
"cost. Honest F1 is measured on the holdout; the output "
"parquet gains an __is_holdout column (fit the meta-"
"learner on those rows only).")
parser.add_argument("--val_rows_per_class", type=int, default=50,
help="Holdout size per class for --training_mode final.")
parser.add_argument("--ordinal_min_label", type=int, default=1)
# --- Ensemble structure ---
parser.add_argument("--ensemble_k_folds", type=int, default=5)
parser.add_argument("--ensemble_config_path", type=str, required=True)
parser.add_argument("--ensemble_output_path", type=str, default="ensemble_soft_labels.parquet")
parser.add_argument("--artifacts_dir", type=str, default="ensemble_artifacts")
parser.add_argument("--metadata_path", type=str, default="ensemble_metadata.json")
parser.add_argument("--soft_label_path", type=str, default=None,
help="Path to a processed ensemble parquet (output of --mode process) "
"that contains final_logprob_<class> columns. Required when any "
"model config has loss_type=kl.")
parser.add_argument("--artifact_suffix", type=str, default=None,
help="Suffix appended to artifacts_dir, metadata_path, and "
"ensemble_output_path. E.g. --artifact_suffix condition_tier "
"gives ensemble_artifacts_condition_tier/, "
"ensemble_metadata_condition_tier.json, etc.")
# --- Global training defaults (all overridable per-model in JSON) ---
parser.add_argument("--max_length", type=int, default=256)
parser.add_argument("--batch_size", type=int, default=8)
parser.add_argument("--max_steps", type=int, default=10000)
parser.add_argument("--eval_steps", type=int, default=200)
parser.add_argument("--learning_rate", type=float, default=2e-5)
parser.add_argument("--early_stopping_patience", type=int, default=5)
parser.add_argument("--seed", type=int, default=42)
parser.add_argument("--warmup_steps", type=int, default=0)
parser.add_argument("--weight_decay", type=float, default=0.01)
parser.add_argument("--adam_epsilon", type=float, default=1e-6,
help="Adam epsilon (floor on second-moment denominator). "
"1e-6 (vs PyTorch default 1e-8) prevents Adam blow-up when "
"gradients stay near-zero for many steps (e.g. saturated ordinal "
"BCE), which would otherwise let vΜβ0 and cause enormous effective "
"weight updates when gradients eventually become non-trivial.")
parser.add_argument("--max_grad_norm", type=float, default=1.0)
parser.add_argument("--label_smoothing", type=float, default=0.0,
help="Label smoothing factor (0.0 = off). Recommended: 0.05-0.1 for noisy tasks.")
parser.add_argument("--lr_scheduler_type", type=str, default="linear",
choices=["linear", "cosine", "cosine_with_restarts", "polynomial", "constant",
"constant_with_warmup", "inverse_sqrt"],
help="LR scheduler. 'cosine' is generally more stable than 'linear' for long runs.")
parser.add_argument("--class_balancing", type=str,
choices=["none", "weighted", "sampler"], default="weighted",
help="Global default. Override per-model with 'class_balancing' in JSON config.")
parser.add_argument("--freeze_layers", type=int, default=0,
help="Number of encoder layers to freeze from the bottom. 0 = no freezing.")
# --- Distillation remedies ---
parser.add_argument("--mode", type=str,
choices=["generate", "process", "generate_and_process"],
default="generate_and_process")
parser.add_argument("--alpha_correct", type=float, default=0.95,
help="Weight of the model's probabilities when it predicts the correct class.")
parser.add_argument("--alpha_incorrect", type=float, default=0.10,
help="Weight of the model's probabilities when it predicts the wrong class.")
parser.add_argument("--temperature", type=float, default=1.0)
parser.add_argument("--entropy_threshold", type=float, default=None)
parser.add_argument("--use_f1_weights", action="store_true")
return parser.parse_args()
# =============================================================================
# UTILITIES & MATH
# =============================================================================
def batch_ordinal_encoding_to_labels(encodings: np.ndarray, threshold: float = 0.5) -> np.ndarray:
predictions = (encodings > threshold).astype(int)
return predictions.sum(axis=1)
def load_mapping(mapping_path: str) -> dict:
with open(mapping_path, "r", encoding="utf-8") as f:
return json.load(f)
def ordinal_logits_to_probabilities(logits: np.ndarray) -> np.ndarray:
cumulative_probs = 1.0 / (1.0 + np.exp(-logits))
batch_size, num_thresholds = cumulative_probs.shape
num_classes = num_thresholds + 1
exact_probs = np.zeros((batch_size, num_classes))
exact_probs[:, 0] = 1.0 - cumulative_probs[:, 0]
for i in range(1, num_thresholds):
exact_probs[:, i] = cumulative_probs[:, i-1] - cumulative_probs[:, i]
exact_probs[:, -1] = cumulative_probs[:, -1]
exact_probs = np.clip(exact_probs, 1e-7, 1.0)
return exact_probs / exact_probs.sum(axis=1, keepdims=True)
def compute_class_weights_from_labels(
labels: np.ndarray,
dampening: str | float = "none"
) -> torch.Tensor:
unique_classes = np.unique(labels)
class_weights = compute_class_weight(
class_weight="balanced", classes=unique_classes, y=labels)
if dampening == "none":
pass
elif dampening == "sqrt":
class_weights = np.sqrt(class_weights)
elif isinstance(dampening, (int, float)) and dampening != 1.0:
class_weights = np.power(class_weights, float(dampening))
else:
raise ValueError(f"class_weight_dampening must be 'none', 'sqrt', or a float. Got: {dampening}")
# Re-normalise so the mean weight stays ~1.0, preserving loss scale
class_weights = class_weights / class_weights.mean()
return torch.tensor(class_weights, dtype=torch.float32)
def compute_ordinal_pos_weights(labels: np.ndarray, num_thresholds: int,
dampening: str = "none") -> torch.Tensor:
"""
Compute per-threshold positive weights for BCEWithLogitsLoss.
For threshold i, the binary question is 'label > i?'.
pos_weight[i] = count(label <= i) / count(label > i)
dampening: 'none' = raw ratio, 'sqrt' = square-rooted, float = that power.
"""
pos_weights = []
for i in range(num_thresholds):
n_pos = np.sum(labels > i)
n_neg = np.sum(labels <= i)
if n_pos == 0:
pos_weights.append(1.0)
else:
w = n_neg / n_pos
if dampening == "sqrt":
w = np.sqrt(w)
elif dampening != "none":
w = w ** float(dampening)
pos_weights.append(w)
return torch.tensor(pos_weights, dtype=torch.float32)
class WeightWarmupCallback(TrainerCallback):
"""
Defers applying class weights to the loss until `warmup_steps` have passed.
Prevents the random head from ping-ponging between trivial single-class
solutions driven by large minority-class gradients in early training.
The trainer reference is injected after trainer construction.
"""
def __init__(self, class_weights: torch.Tensor, warmup_steps: int):
self.class_weights = class_weights
self.warmup_steps = warmup_steps
self.trainer = None # injected post-construction
self._activated = False
def on_step_end(self, args, state, control, **kwargs):
if (not self._activated
and self.trainer is not None
and state.global_step >= self.warmup_steps):
self.trainer.class_weights = self.class_weights
self._activated = True
print(f"\n -> [WeightWarmup] Class weights activated at step {state.global_step}")
def freeze_encoder_layers(model, num_layers: int):
"""
Freeze the bottom `num_layers` encoder layers of a transformer.
Useful to stabilise early training β frozen layers act as a fixed feature
extractor while only the top layers and head fine-tune.
"""
if num_layers <= 0:
return
# Works for BERT-family (encoder.layer), DeBERTa (encoder.layer), ELECTRA, etc.
encoder = None
for attr in ["encoder", "bert", "deberta", "electra", "roberta"]:
enc = getattr(model, attr, None)
if enc is not None:
encoder = getattr(enc, "layer", None)
if encoder is not None:
break
if encoder is None:
print(f" [WARNING] Could not find encoder layers to freeze β skipping.")
return
actual = min(num_layers, len(encoder))
for i in range(actual):
for param in encoder[i].parameters():
param.requires_grad = False
print(f" -> Froze {actual}/{len(encoder)} encoder layers.")
# =============================================================================
# CHECKPOINT HELPERS
# =============================================================================
def load_ensemble_configs(config_path: str) -> list:
with open(config_path, "r") as f:
return json.load(f)
def get_artifact_dir(artifacts_root: str, model_name: str) -> Path:
safe_name = model_name.replace("/", "__")
return Path(artifacts_root) / safe_name
def artifact_exists(artifacts_root: str, model_name: str) -> bool:
return (get_artifact_dir(artifacts_root, model_name) / "oof_probs.npy").exists()
def load_artifact_oof_probs(artifacts_root: str, model_name: str) -> tuple:
artifact_dir = get_artifact_dir(artifacts_root, model_name)
oof_probs = np.load(artifact_dir / "oof_probs.npy")
with open(artifact_dir / "metadata.json") as f:
meta = json.load(f)
return oof_probs, meta["oof_f1"]
def save_model_artifact_metadata(artifact_dir: Path, oof_f1: float, fold_f1s: list,
task_type: str, num_folds: int):
meta = {
"oof_f1": round(oof_f1, 6),
"fold_f1s": [round(f, 6) for f in fold_f1s],
"task_type": task_type,
"num_folds": num_folds,
"saved_at": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
}
with open(artifact_dir / "metadata.json", "w") as f:
json.dump(meta, f, indent=2)
# =============================================================================
# CONFIG HELPER β resolves per-model overrides against global defaults
# =============================================================================
# Complete list of every training arg that can live in the JSON config.
# Format: (json_key, args_attr, default_if_neither_set)
_TRAINING_ARG_SPECS = [
# Tokenisation
("max_length", "max_length", 256),
# Batch / gradient
("batch_size", "batch_size", 8),
("gradient_accumulation_steps", "gradient_accumulation_steps", 1),
# Optimiser
("learning_rate", "learning_rate", 2e-5),
("head_lr_multiplier", "head_lr_multiplier", 1.0),
("head_keywords", "head_keywords", []),
("weight_decay", "weight_decay", 0.01),
("adam_epsilon", "adam_epsilon", 1e-6),
# AMSGrad keeps an extra full-size optimizer state tensor (max_exp_avg_sq).
# On VRAM-tight GPUs with very large encoders (e.g. RemBERT ~576M params)
# this can be the difference between fitting and OOM. Set false per-model
# to drop it; the raised adam_epsilon remains the primary guard against
# second-moment underflow.
("use_amsgrad", "use_amsgrad", True),
("max_grad_norm", "max_grad_norm", 1.0),
("class_weight_dampening", "class_weight_dampening", "none"),
# Schedule
("warmup_steps", "warmup_steps", 0),
("lr_scheduler_type", "lr_scheduler_type", "linear"),
("class_weight_warmup_steps", "class_weight_warmup_steps", 0),
# Steps / patience
("max_steps", "max_steps", 10000),
("eval_steps", "eval_steps", 200),
("early_stopping_patience", "early_stopping_patience", 5),
# Regularisation
("label_smoothing", "label_smoothing", 0.0),
("freeze_layers", "freeze_layers", 0),
# Class imbalance
("class_balancing", "class_balancing", "weighted"),
# Precision / model flags
("use_bf16", "use_bf16", False),
("drop_token_type_ids", "drop_token_type_ids", None),
# Model identity
("tokenizer_name", "tokenizer_name", None), # resolved below
("other_cols", "other_cols", []),
("cat_cols", "cat_cols", []),
("cat_encoding", "cat_encoding", "ordinal"), # Options: ordinal, frequency, target
# Loss objective
# "ce" β standard cross-entropy against hard integer labels (default).
# "kl" β KL divergence against soft label distributions from a previous ensemble run.
# Requires --soft_label_path pointing to a processed ensemble parquet that
# contains final_logprob_<class> columns. Use a separate ensemble_config for
# this second-generation training.
("loss_type", "loss_type", "ce"),
# Prefix of soft-label columns in the soft_label_path parquet (default matches process output).
("soft_label_prefix", "soft_label_prefix", "final_logprob_"),
# KL temperature: soften/sharpen the teacher distribution before computing KL loss.
# Values > 1.0 soften (more uniform), < 1.0 sharpen. Usually 1.0β4.0.
("kl_temperature", "kl_temperature", 1.0),
]
def resolve_model_args(global_args, config: dict):
"""
Returns a namespace where every training arg is resolved with priority:
per-model JSON config > global CLI args > hardcoded default
"""
resolved = copy.deepcopy(global_args)
for json_key, attr, default in _TRAINING_ARG_SPECS:
if json_key in config:
setattr(resolved, attr, config[json_key])
elif not hasattr(resolved, attr) or getattr(resolved, attr) is None:
setattr(resolved, attr, default)
# tokenizer_name falls back to model_name if not explicitly set
if not getattr(resolved, "tokenizer_name", None):
resolved.tokenizer_name = config["model_name"]
resolved.model_name = config["model_name"]
return resolved
# =============================================================================
# FORMATTED EVAL CALLBACK
# =============================================================================
class FormattedEvalCallback(TrainerCallback):
def __init__(self, task_type: str, num_labels: int, idx_to_label: dict = None):
self.task_type = task_type
self.num_labels = num_labels
self.idx_to_label = idx_to_label
def on_evaluate(self, args, state, control, metrics=None, **kwargs):
if metrics is None:
return
print("\n" + "-" * 60)
print("Overall Metrics:")
for key in ["eval_loss", "eval_accuracy", "eval_f1", "eval_precision", "eval_recall",
"eval_mae", "eval_rmse", "eval_mse", "eval_r2", "eval_within_1_accuracy"]:
if key in metrics:
v = metrics[key]
name = key.replace("eval_", "")
print(f" {name:<20}: {v:.4f}" if isinstance(v, float) else f" {name:<20}: {v}")
if self.task_type in ["classification", "ordinal", "soft_label"]:
class_indices = sorted(
int(k.split("_")[-1])
for k in metrics if k.startswith("eval_precision_class_")
)
if class_indices:
has_kl = f"eval_kl_class_{class_indices[0]}" in metrics
header = f" {'Class':<8} {'Prec':<8} {'Recall':<8} {'F1':<8} {'Support':<8}"
if has_kl: header += f" {'KL Loss':<8}"
print(f"\n{header}")
print(" " + "-" * (len(header) - 2))
for i in class_indices:
label = f"{i}({self.idx_to_label[i]})" if self.idx_to_label else str(i)
row = (f" {label:<8} "
f"{metrics.get(f'eval_precision_class_{i}', 0):<8.4f} "
f"{metrics.get(f'eval_recall_class_{i}', 0):<8.4f} "
f"{metrics.get(f'eval_f1_class_{i}', 0):<8.4f} "
f"{metrics.get(f'eval_support_class_{i}', 0):<8}")
if has_kl:
row += f" {metrics.get(f'eval_kl_class_{i}', 0):<8.4f}"
print(row)
if self.task_type == "ordinal":
thresh_indices = sorted(
int(k.split("_")[2])
for k in metrics if k.startswith("eval_threshold_") and k.endswith("_acc")
)
if thresh_indices:
print(f"\n {'Thresh':<8} {'Question':<14} {'Acc':<8} {'Recall':<8}")
print(" " + "-" * 38)
for i in thresh_indices:
print(f" {i:<8} {'label > ' + str(i) + '?':<14} "
f"{metrics.get(f'eval_threshold_{i}_acc', 0):<8.4f} "
f"{metrics.get(f'eval_threshold_{i}_recall', 0):<8.4f}")
print("-" * 60)
# =============================================================================
# CUSTOM MODELS
# =============================================================================
class MultimodalClassificationModel(nn.Module):
def __init__(self, base_model, num_additional_features, num_labels,
class_weights=None, drop_token_type_ids=None, label_smoothing=0.0):
super().__init__()
self.base_model = base_model
self.num_additional_features = num_additional_features
self.num_labels = num_labels
self.class_weights = class_weights
self.drop_token_type_ids = drop_token_type_ids
self.label_smoothing = label_smoothing
self.config = base_model.config # required by HuggingFace Trainer
hidden_size = base_model.config.hidden_size
combined_size = hidden_size + num_additional_features
self.classifier = nn.Sequential(
nn.Linear(combined_size, hidden_size),
nn.ReLU(),
nn.Dropout(0.1),
nn.Linear(hidden_size, num_labels)
)
if hasattr(base_model, 'classifier'):
base_model.classifier = nn.Identity()
def forward(self, input_ids, attention_mask, additional_features=None, labels=None, **kwargs):
model_type = getattr(self.base_model.config, "model_type", "")
default_drop = ["xlm-roberta", "roberta", "camembert", "deberta-v2", "distilbert", "bart", "longformer"]
should_drop = self.drop_token_type_ids if self.drop_token_type_ids is not None else (model_type in default_drop)
if should_drop:
kwargs.pop("token_type_ids", None)
base_encoder = getattr(self.base_model, self.base_model.base_model_prefix, self.base_model)
outputs = base_encoder(input_ids=input_ids, attention_mask=attention_mask, **kwargs)
pooled = outputs.last_hidden_state[:, 0, :]
combined = torch.cat([pooled, additional_features], dim=1) if additional_features is not None else pooled
logits = self.classifier(combined)
loss = None
if labels is not None:
loss_fct = nn.CrossEntropyLoss(
weight=self.class_weights.to(logits.device) if self.class_weights is not None else None,
label_smoothing=self.label_smoothing,
)
loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
return {"loss": loss, "logits": logits}
class OrdinalRegressionModel(nn.Module):
def __init__(self, base_model, num_classes, num_additional_features=0,
drop_token_type_ids=None, pos_weight=None):
super().__init__()
self.base_model = base_model
self.num_classes = num_classes
self.num_thresholds = num_classes - 1
self.drop_token_type_ids = drop_token_type_ids
self.pos_weight = pos_weight # [num_thresholds] tensor or None
self.config = base_model.config # required by HuggingFace Trainer
hidden_size = base_model.config.hidden_size
combined_size = hidden_size + num_additional_features
self.feature_extractor = nn.Sequential(
nn.Linear(combined_size, hidden_size),
nn.ReLU(),
nn.Dropout(0.1),
)
self.ordinal_head = nn.Linear(hidden_size, self.num_thresholds)
def forward(self, input_ids, attention_mask, additional_features=None, labels=None, **kwargs):
model_type = getattr(self.base_model.config, "model_type", "")
default_drop = ["xlm-roberta", "roberta", "camembert", "deberta-v2", "distilbert", "bart", "longformer"]
should_drop = self.drop_token_type_ids if self.drop_token_type_ids is not None else (model_type in default_drop)
if should_drop:
kwargs.pop("token_type_ids", None)
outputs = self.base_model(input_ids=input_ids, attention_mask=attention_mask, **kwargs)
pooled = outputs.last_hidden_state[:, 0, :]
combined = torch.cat([pooled, additional_features], dim=1) if additional_features is not None else pooled
logits = self.ordinal_head(self.feature_extractor(combined))
loss = None
if labels is not None:
targets = torch.zeros(labels.size(0), self.num_thresholds, device=labels.device)
for i in range(self.num_thresholds):
targets[:, i] = (labels > i).float()
pw = self.pos_weight.to(logits.device) if self.pos_weight is not None else None
loss = nn.BCEWithLogitsLoss(pos_weight=pw)(logits, targets)
return {"loss": loss, "logits": logits}
# =============================================================================
# CUSTOM TRAINERS
# =============================================================================
class BalancedSamplerMixin:
def _get_train_sampler(self, dataset=None, **kwargs):
target_dataset = dataset if dataset is not None else self.train_dataset
labels = target_dataset["label"]
class_counts = np.bincount(labels)
class_weights = np.divide(1.0, class_counts,
out=np.zeros_like(class_counts, dtype=float),
where=class_counts != 0)
sample_weights = [class_weights[label] for label in labels]
return WeightedRandomSampler(weights=sample_weights,
num_samples=len(sample_weights), replacement=True)
class SamplerTrainer(BalancedSamplerMixin, Trainer): pass
class WeightedLossTrainer(Trainer):
"""Standard Trainer with a weighted CrossEntropyLoss to handle class imbalance.
Used for non-multimodal models (no additional_features) with class_balancing='weighted'.
"""
def __init__(self, *args, class_weights: torch.Tensor = None, **kwargs):
super().__init__(*args, **kwargs)
self.class_weights = class_weights
def compute_loss(self, model, inputs, return_outputs=False, **kwargs):
labels = inputs.get("labels")
outputs = model(**inputs)
logits = outputs.logits
if self.class_weights is not None:
loss_fct = nn.CrossEntropyLoss(
weight=self.class_weights.to(logits.device),
label_smoothing=self.args.label_smoothing_factor,
)
loss = loss_fct(logits.view(-1, self.model.config.num_labels), labels.view(-1))
else:
loss = outputs.loss
return (loss, outputs) if return_outputs else loss
class KLDivTrainer(Trainer):
"""Trains against soft label distributions using KL divergence loss.
Expects `soft_labels` tensor in the batch (shape: [batch, num_classes]).
`kl_temperature` softens/sharpens the teacher before computing loss.
"""
def __init__(self, *args, kl_temperature=1.0, **kwargs):
super().__init__(*args, **kwargs)
self.kl_temperature = kl_temperature
def _set_signature_columns_if_needed(self):
"""Tells the Hugging Face Trainer NOT to delete our custom soft_labels column."""
super()._set_signature_columns_if_needed()
if self._signature_columns is not None and "soft_labels" not in self._signature_columns:
self._signature_columns.append("soft_labels")
def compute_loss(self, model, inputs, return_outputs=False, **kwargs):
soft_labels = inputs.pop("soft_labels") # [B, C] float
_ = inputs.pop("labels", None) # Pop to prevent wasted CE loss computation
outputs = model(**inputs)
logits = outputs.logits # [B, C]
# Apply temperature to teacher distribution
if self.kl_temperature != 1.0:
teacher = torch.softmax(
torch.log(soft_labels.clamp(1e-7)) / self.kl_temperature, dim=-1)
else:
teacher = soft_labels
# KL(teacher || student) = sum(teacher * log(teacher / student))
# nn.KLDivLoss expects log-probs as input, probs as target
log_student = torch.nn.functional.log_softmax(logits, dim=-1)
loss = torch.nn.functional.kl_div(
log_student, teacher, reduction="batchmean")
return (loss, outputs) if return_outputs else loss
class KLDivMultimodalTrainer(KLDivTrainer):
"""KL divergence trainer for MultimodalClassificationModel."""
def compute_loss(self, model, inputs, return_outputs=False, **kwargs):
soft_labels = inputs.pop("soft_labels")
_ = inputs.pop("labels", None) # Pop to prevent wasted CE loss computation
additional_features = inputs.pop("additional_features", None)
outputs = model(**inputs, additional_features=additional_features, labels=None)
logits = outputs["logits"]
if self.kl_temperature != 1.0:
teacher = torch.softmax(
torch.log(soft_labels.clamp(1e-7)) / self.kl_temperature, dim=-1)
else:
teacher = soft_labels
log_student = torch.nn.functional.log_softmax(logits, dim=-1)
loss = torch.nn.functional.kl_div(
log_student, teacher, reduction="batchmean")
return (loss, outputs) if return_outputs else loss
class MultimodalTrainerOverride(Trainer):
def compute_loss(self, model, inputs, return_outputs=False, **kwargs):
labels = inputs.pop("labels", None)
additional_features = inputs.pop("additional_features", None)
outputs = model(**inputs, additional_features=additional_features, labels=labels)
return (outputs["loss"], outputs) if return_outputs else outputs["loss"]
class WeightedMultimodalTrainer(MultimodalTrainerOverride): pass
class SamplerMultimodalTrainer(BalancedSamplerMixin, MultimodalTrainerOverride): pass
class OrdinalRegressionTrainer(MultimodalTrainerOverride): pass
class OrdinalSamplerTrainer(BalancedSamplerMixin, MultimodalTrainerOverride):
"""Ordinal trainer with WeightedRandomSampler for class-imbalance correction.
Sampling is driven by the hard label so minority ordinal classes appear more
often, while the loss target remains the standard BCE ordinal objective.
"""
pass
class OrdinalWeightedTrainer(MultimodalTrainerOverride):
"""Ordinal trainer that passes per-threshold pos_weights into the model.
The pos_weight is baked into OrdinalRegressionModel at construction time
(compute_ordinal_pos_weights), so no extra compute_loss override is needed.
"""
pass
class KLOrdinalTrainer(MultimodalTrainerOverride):
"""
Distillation for ordinal students.
Teacher produces P(class=k) via ordinal_logits_to_probabilities.
We convert that to cumulative soft targets:
soft_cum[:, i] = sum(teacher_probs[:, i+1:]) β P(label > i)
Then apply BCEWithLogitsLoss against those soft targets,
optionally with pos_weight for threshold-level imbalance.
"""
def __init__(self, *args, kl_temperature=1.0, pos_weight=None, **kwargs):
super().__init__(*args, **kwargs)
self.kl_temperature = kl_temperature
self.pos_weight = pos_weight # [num_thresholds]
def _set_signature_columns_if_needed(self):
super()._set_signature_columns_if_needed()
if self._signature_columns and "soft_labels" not in self._signature_columns:
self._signature_columns.append("soft_labels")
def compute_loss(self, model, inputs, return_outputs=False, **kwargs):
soft_labels = inputs.pop("soft_labels") # [B, total_classes] incl. unknown
_ = inputs.pop("labels", None)
additional_features = inputs.pop("additional_features", None)
outputs = model(**inputs, additional_features=additional_features, labels=None)
logits = outputs["logits"] # [B, num_thresholds]
num_thresholds = logits.shape[1]
num_ord_classes = num_thresholds + 1
# Strip unknown class (last column) and renormalize to ordinal-only distribution.
# This matters for stage-2 where soft_labels has an extra unknown column.
# Relies on soft_label_cols being sorted by internal class index (guaranteed by
# the idx_to_name sort in generate_kfold_oof_predictions).
ordinal_soft = soft_labels[:, :num_ord_classes]
ordinal_soft = ordinal_soft / ordinal_soft.sum(dim=1, keepdim=True).clamp(min=1e-7)
if self.kl_temperature != 1.0:
log_soft = torch.log(ordinal_soft.clamp(1e-7)) / self.kl_temperature
ordinal_soft = torch.softmax(log_soft, dim=-1)
# Convert class probs β cumulative binary targets P(label > i)
soft_cum = torch.stack(
[ordinal_soft[:, i+1:].sum(dim=1) for i in range(num_thresholds)], dim=1
) # [B, num_thresholds]
pw = self.pos_weight.to(logits.device) if self.pos_weight is not None else None
loss = nn.BCEWithLogitsLoss(pos_weight=pw)(logits, soft_cum)
return (loss, outputs) if return_outputs else loss
# =============================================================================
# METRICS
# =============================================================================
def compute_classification_metrics(p):
logits = p.predictions[0] if isinstance(p.predictions, tuple) else p.predictions
preds = np.argmax(logits, axis=1)
labels = p.label_ids
num_labels = logits.shape[1]
precision, recall, f1, _ = precision_recall_fscore_support(labels, preds, average="macro", zero_division=0)
results = {"accuracy": accuracy_score(labels, preds), "f1": f1, "precision": precision, "recall": recall}
precision_pc, recall_pc, f1_pc, support_pc = precision_recall_fscore_support(
labels, preds, average=None, labels=list(range(num_labels)), zero_division=0)
for i in range(num_labels):
results[f"precision_class_{i}"] = precision_pc[i]
results[f"recall_class_{i}"] = recall_pc[i]
results[f"f1_class_{i}"] = f1_pc[i]
results[f"support_class_{i}"] = int(support_pc[i])
return results
def compute_ordinal_metrics(p):
logits = p.predictions[0] if isinstance(p.predictions, tuple) else p.predictions
probs = torch.sigmoid(torch.tensor(logits)).numpy()
preds = batch_ordinal_encoding_to_labels(probs)
labels = p.label_ids
num_classes = logits.shape[1] + 1
precision, recall, f1, _ = precision_recall_fscore_support(labels, preds, average="macro", zero_division=0)
results = {"accuracy": accuracy_score(labels, preds), "mae": mean_absolute_error(labels, preds), "f1": f1}
precision_pc, recall_pc, f1_pc, support_pc = precision_recall_fscore_support(
labels, preds, average=None, labels=list(range(num_classes)), zero_division=0)
for i in range(num_classes):
results[f"precision_class_{i}"] = precision_pc[i]
results[f"recall_class_{i}"] = recall_pc[i]
results[f"f1_class_{i}"] = f1_pc[i]
results[f"support_class_{i}"] = int(support_pc[i])
threshold_preds = (probs > 0.5).astype(int)
for i in range(num_classes - 1):
threshold_true = (labels > i).astype(int)
threshold_pred = threshold_preds[:, i]
results[f"threshold_{i}_acc"] = accuracy_score(threshold_true, threshold_pred)
n_true_pos = threshold_true.sum()
results[f"threshold_{i}_recall"] = (
threshold_pred[threshold_true == 1].sum() / n_true_pos if n_true_pos > 0 else 0.0
)
return results
# =============================================================================
# K-FOLD ENGINE β TRANSFORMER
# =============================================================================
def generate_kfold_oof_predictions(args, df, task_type, model_list, artifact_name=None, idx_to_name=None,
custom_splits=None, split_names=None):
"""
args here is already a *resolved* namespace β all per-model overrides applied.
artifact_name: override the folder name used for all disk I/O (oof_probs.npy,
fold_N/model/, metadata.json). When None, falls back to model_name.
This decouples the HuggingFace model identifier from the artifact path,
which is necessary for split-stage models that share the same base
model but need separate stage1 / stage2 artifact directories.
"""
kfold = StratifiedKFold(n_splits=args.ensemble_k_folds, shuffle=True, random_state=args.seed)
num_classes = int(df["label"].max()) + 1 if task_type == "classification" else args.ordinal_num_classes
final_oof_probs = np.zeros((len(df), num_classes))
for model_name in model_list:
# artifact_name drives all path operations; model_name drives from_pretrained
_artifact_name = artifact_name if artifact_name is not None else model_name
artifact_dir = get_artifact_dir(args.artifacts_dir, _artifact_name)
artifact_dir.mkdir(parents=True, exist_ok=True)
# --- Per-model resume: if oof_probs.npy already exists, skip all training ---
if (artifact_dir / "oof_probs.npy").exists():
with open(artifact_dir / "metadata.json") as f:
meta = json.load(f)
existing_probs = np.load(artifact_dir / "oof_probs.npy")
print(f"\n{'='*70}\nResuming K-Fold for: {model_name}\n{'='*70}")
print(f" -> Artifact directory: {artifact_dir}")
print(f" -> [Resume] Found existing oof_probs.npy β skipping all training.")
print(f" -> OOF Macro F1: {meta['oof_f1']:.4f} | Fold F1s: {meta.get('fold_f1s', [])}")
return existing_probs, meta["oof_f1"]
print(f"\n{'='*70}\nStarting K-Fold for: {model_name}\n{'='*70}")
print(f" -> Artifact directory: {artifact_dir}")
print(f" -> class_balancing={args.class_balancing} "
f"label_smoothing={args.label_smoothing} "
f"freeze_layers={args.freeze_layers} "
f"lr_scheduler={args.lr_scheduler_type} "
f"warmup_steps={args.warmup_steps}")
model_oof_probs = np.zeros_like(final_oof_probs)
fold_f1s = []
# custom_splits: list of (train_idx, val_idx). Used by --training_mode
# final to train ONE model on a stratified holdout split. split_names
# override the fold_N directory names (e.g. ["final"]).
_splits = (custom_splits if custom_splits is not None
else list(kfold.split(df, df["label"])))
for fold, (train_idx, val_idx) in enumerate(_splits):
fold_num = fold + 1
_dir_name = split_names[fold] if split_names else f"fold_{fold_num}"
fold_artifact_dir = artifact_dir / _dir_name
print(f"\n--- Split {_dir_name} ({fold_num}/{len(_splits)}) ---")
keep_cols = ["text", "label"]
if args.other_cols:
keep_cols.append("additional_features")
# KL training: include soft label columns so the Trainer can read them per-batch
soft_label_cols = []
if getattr(args, "loss_type", "ce") == "kl":
prefix = getattr(args, "soft_label_prefix", "final_logprob_")
raw_soft_cols = [c for c in df.columns if c.startswith(prefix)]
if not raw_soft_cols:
raise ValueError(
f"loss_type=kl but no '{prefix}*' columns found in df. "
"Did you pass --soft_label_path?")
# Sort columns by internal class index so the packed soft_labels tensor
# always has classes in order [0, 1, ..., ordinal_num_classes, unknown].
# Alphabetical sort is NOT safe here β e.g. mapping {"D":1,"C":2,"B":3,"A":4,"N":-1}
# would sort as A,B,C,D,N = internal indices 3,2,1,0,4, causing KLOrdinalTrainer
# to strip the wrong column when slicing [:, :num_ord_classes].
if idx_to_name:
name_to_idx = {v: k for k, v in idx_to_name.items()}
soft_label_cols = sorted(
raw_soft_cols,
key=lambda c: name_to_idx.get(c[len(prefix):], 999)
)
else:
soft_label_cols = raw_soft_cols # fallback: trust insertion order
keep_cols.extend(soft_label_cols)
train_df = df.iloc[train_idx][keep_cols].copy()
val_df = df.iloc[val_idx][keep_cols].copy()
tokenizer = AutoTokenizer.from_pretrained(args.tokenizer_name)
def tokenize_fn(examples):
toks = tokenizer(examples["text"], padding="max_length",
max_length=args.max_length, truncation=True)
if getattr(args, 'drop_token_type_ids', False) and "token_type_ids" in toks:
del toks["token_type_ids"]
if "additional_features" in examples:
toks["additional_features"] = examples["additional_features"]
# Pack soft label columns into a single float32 tensor per example
if soft_label_cols:
toks["soft_labels"] = [
[examples[c][i] for c in soft_label_cols]
for i in range(len(examples[soft_label_cols[0]]))
]
return toks
train_ds = (Dataset.from_pandas(train_df, preserve_index=False)
.map(tokenize_fn, batched=True).remove_columns(["text"]))
val_ds = (Dataset.from_pandas(val_df, preserve_index=False)
.map(tokenize_fn, batched=True).remove_columns(["text"]))
trainer_kwargs = {}
weight_warmup_cb = None
if task_type == "classification":
if args.class_balancing == "weighted":
class_weights = compute_class_weights_from_labels(
train_df["label"].values,
dampening=args.class_weight_dampening,
)
# If warmup requested, start with no weights and inject later
if args.class_weight_warmup_steps > 0:
print(f" [Fold {fold_num}] Class weight warmup: "
f"weights deferred until step {args.class_weight_warmup_steps} "
f"(dampening={args.class_weight_dampening})")
weight_warmup_cb = WeightWarmupCallback(
class_weights, args.class_weight_warmup_steps)
effective_weights = None # start unweighted
else:
print(f" [Fold {fold_num}] class_weight_dampening={args.class_weight_dampening}")
effective_weights = class_weights
else:
class_weights = None
effective_weights = None
_use_kl = getattr(args, "loss_type", "ce") == "kl"
if args.other_cols:
base_model = AutoModelForSequenceClassification.from_pretrained(
model_name, num_labels=num_classes,
use_safetensors=True, ignore_mismatched_sizes=True,
torch_dtype=torch.float32)
freeze_encoder_layers(base_model, args.freeze_layers)
model = MultimodalClassificationModel(
base_model, len(args.other_cols), num_classes,
class_weights, args.drop_token_type_ids, args.label_smoothing
).to("cuda")
if _use_kl:
TrainerClass = KLDivMultimodalTrainer
trainer_kwargs = {"kl_temperature": args.kl_temperature}
print(f" [Fold {fold_num}] KL divergence objective (temperature={args.kl_temperature})")
else:
TrainerClass = (SamplerMultimodalTrainer if args.class_balancing == "sampler"
else WeightedMultimodalTrainer)
else:
model = AutoModelForSequenceClassification.from_pretrained(
model_name, num_labels=num_classes,
use_safetensors=True, torch_dtype=torch.float32,
).to("cuda")
freeze_encoder_layers(model, args.freeze_layers)
if _use_kl:
TrainerClass = KLDivTrainer
trainer_kwargs = {"kl_temperature": args.kl_temperature}
print(f" [Fold {fold_num}] KL divergence objective (temperature={args.kl_temperature})")
elif args.class_balancing == "sampler":
TrainerClass = SamplerTrainer
elif effective_weights is not None or args.class_weight_warmup_steps > 0:
TrainerClass = WeightedLossTrainer
# Pass effective_weights (may be None during warmup β that's intentional)
trainer_kwargs = {"class_weights": effective_weights}
else:
TrainerClass = Trainer
compute_metrics_fn = compute_classification_metrics
metric_for_best = "eval_f1"
greater_is_better = True
elif task_type == "ordinal":
base_model = AutoModel.from_pretrained(
model_name, use_safetensors=True, ignore_mismatched_sizes=True,
torch_dtype=torch.float32)
freeze_encoder_layers(base_model, args.freeze_layers)
# Compute per-threshold pos_weights for weighted BCE
ordinal_pos_weight = None
if args.class_balancing == "weighted":
ordinal_pos_weight = compute_ordinal_pos_weights(
train_df["label"].values, num_classes - 1,
dampening=args.class_weight_dampening,
)
print(f" [Fold {fold_num}] class_balancing=weighted "
f"(BCEWithLogitsLoss pos_weight={[round(w,3) for w in ordinal_pos_weight.tolist()]})")
elif args.class_balancing == "sampler":
print(f" [Fold {fold_num}] class_balancing=sampler (WeightedRandomSampler)")
else:
print(f" [Fold {fold_num}] class_balancing=none")
model = OrdinalRegressionModel(
base_model, num_classes,
len(args.other_cols) if args.other_cols else 0,
args.drop_token_type_ids,
pos_weight=ordinal_pos_weight,
).to("cuda")
_use_kl = getattr(args, "loss_type", "ce") == "kl"
if _use_kl:
TrainerClass = KLOrdinalTrainer
trainer_kwargs = {
"kl_temperature": args.kl_temperature,
"pos_weight": ordinal_pos_weight, # still apply threshold balancing
}
elif args.class_balancing == "sampler":
TrainerClass = OrdinalSamplerTrainer
elif args.class_balancing == "weighted":
TrainerClass = OrdinalWeightedTrainer
else:
TrainerClass = OrdinalRegressionTrainer
compute_metrics_fn = compute_ordinal_metrics
metric_for_best = "eval_mae"
greater_is_better = False
if task_type == "classification":
if args.class_balancing == "sampler":
print(f" [Fold {fold_num}] class_balancing=sampler (WeightedRandomSampler)")
elif args.class_balancing == "weighted":
print(f" [Fold {fold_num}] class_balancing=weighted (CrossEntropyLoss weights)")
else:
print(f" [Fold {fold_num}] class_balancing=none")
training_args = TrainingArguments(
output_dir=str(fold_artifact_dir / "tmp_checkpoints"),
max_steps=args.max_steps,
learning_rate=args.learning_rate,
per_device_train_batch_size=args.batch_size,
per_device_eval_batch_size=args.batch_size,
gradient_accumulation_steps=args.gradient_accumulation_steps,
weight_decay=args.weight_decay,
adam_epsilon=args.adam_epsilon,
max_grad_norm=args.max_grad_norm,
warmup_steps=args.warmup_steps,
lr_scheduler_type=args.lr_scheduler_type,
label_smoothing_factor=args.label_smoothing,
eval_strategy="steps",
eval_steps=args.eval_steps,
save_steps=args.eval_steps,
load_best_model_at_end=True,
metric_for_best_model=metric_for_best,
greater_is_better=greater_is_better,
logging_strategy="steps",
logging_steps=args.eval_steps,
save_total_limit=1,
save_only_model=True, # skip optimizer/scheduler state β saves ~3GB per checkpoint
report_to="none",
bf16=args.use_bf16,
)
import torch.optim as optim
if args.head_lr_multiplier > 1.0:
print(f" [Fold {fold_num}] Using Differential LR: Head is learning {args.head_lr_multiplier}x faster than Base.")
base_head_keys = ["classifier", "ordinal_head", "feature_extractor", "score", "pooler"]
head_keywords = base_head_keys + args.head_keywords
# Remove duplicates just in case
head_keywords = list(set(head_keywords))
no_decay = ["bias", "LayerNorm.weight"]
optimizer_grouped_parameters = [
# Base Encoder (With Decay)
{"params": [p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay) and not any(hk in n for hk in head_keywords) and p.requires_grad],
"weight_decay": args.weight_decay, "lr": args.learning_rate},
# Base Encoder (No Decay)
{"params": [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay) and not any(hk in n for hk in head_keywords) and p.requires_grad],
"weight_decay": 0.0, "lr": args.learning_rate},
# Custom Head (With Decay, Multiplied LR)
{"params": [p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay) and any(hk in n for hk in head_keywords) and p.requires_grad],
"weight_decay": args.weight_decay, "lr": args.learning_rate * args.head_lr_multiplier},
# Custom Head (No Decay, Multiplied LR)
{"params": [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay) and any(hk in n for hk in head_keywords) and p.requires_grad],
"weight_decay": 0.0, "lr": args.learning_rate * args.head_lr_multiplier}
]
_use_ams = bool(getattr(args, "use_amsgrad", True))
if not _use_ams:
print(" [OPTIM] AMSGrad disabled for this model "
"(saves one full-size optimizer state tensor)")
custom_optimizer = optim.AdamW(
optimizer_grouped_parameters,
eps=args.adam_epsilon,
amsgrad=_use_ams, # running max of vΜ prevents second-moment decay toward zero
)
optimizers = (custom_optimizer, None)
else:
# No differential LR, but we still construct the optimizer explicitly
# so we can enable amsgrad=True. This prevents the second-moment vΜ from
# decaying toward zero when gradients stay near-zero for many steps
# (e.g. saturated ordinal BCE), which would otherwise cause enormous
# effective weight updates and a training loss blow-up.
no_decay = ["bias", "LayerNorm.weight"]
standard_grouped_parameters = [
{"params": [p for n, p in model.named_parameters()
if not any(nd in n for nd in no_decay) and p.requires_grad],
"weight_decay": args.weight_decay, "lr": args.learning_rate},
{"params": [p for n, p in model.named_parameters()
if any(nd in n for nd in no_decay) and p.requires_grad],
"weight_decay": 0.0, "lr": args.learning_rate},
]
_use_ams = bool(getattr(args, "use_amsgrad", True))
if not _use_ams:
print(" [OPTIM] AMSGrad disabled for this model")
fallback_optimizer = optim.AdamW(
standard_grouped_parameters,
eps=args.adam_epsilon,
amsgrad=_use_ams, # running max of vΜ β see comment above
)
optimizers = (fallback_optimizer, None)
trainer = TrainerClass(
model=model,
args=training_args,
train_dataset=train_ds,
eval_dataset=val_ds,
compute_metrics=compute_metrics_fn,
optimizers=optimizers,
callbacks=[
EarlyStoppingCallback(args.early_stopping_patience),
FormattedEvalCallback(task_type=task_type, num_labels=num_classes),
*([weight_warmup_cb] if weight_warmup_cb is not None else []),
],
**trainer_kwargs
)
# Give the warmup callback a handle to the trainer so it can
# set class_weights on it when the step threshold is reached
if weight_warmup_cb is not None:
weight_warmup_cb.trainer = trainer
trainer.train()
# --- Save best fold model permanently ---
fold_model_dir = fold_artifact_dir / "model"
fold_model_dir.mkdir(parents=True, exist_ok=True)
trainer.save_model(str(fold_model_dir))
tokenizer.save_pretrained(str(fold_model_dir))
print(f" [Fold {fold_num}] Saved best model β {fold_model_dir}")
tmp_ckpt_dir = fold_artifact_dir / "tmp_checkpoints"
if tmp_ckpt_dir.exists():
shutil.rmtree(tmp_ckpt_dir)
# --- OOF inference ---
oof_output = trainer.predict(val_ds)
logits = (oof_output.predictions[0]
if isinstance(oof_output.predictions, tuple)
else oof_output.predictions)
fold_probs = (torch.softmax(torch.tensor(logits), dim=1).numpy()
if task_type == "classification"
else ordinal_logits_to_probabilities(logits))
model_oof_probs[val_idx] = fold_probs
# For both task types, fold_probs contains per-class probabilities
# (softmax for classification, ordinal_logits_to_probabilities for ordinal).
# argmax is the correct decoder in both cases.
# NOTE: do NOT use batch_ordinal_encoding_to_labels here β that function
# expects sigmoid/cumulative probabilities (as used inside compute_ordinal_metrics),
# not the class-probability representation stored in fold_probs. Applying it to
# class probs causes virtually all predictions to be 0 (class probs rarely > 0.5),
# which produces a near-zero reported Val Macro F1 despite healthy training metrics.
fold_preds = np.argmax(fold_probs, axis=1)
fold_f1 = precision_recall_fscore_support(
df.iloc[val_idx]["label"].values, fold_preds,
average="macro", zero_division=0)[2]
fold_f1s.append(float(fold_f1))
print(f" [Fold {fold_num}] Val Macro F1: {fold_f1:.4f}")
del trainer, model
torch.cuda.empty_cache()
gc.collect()
final_oof_probs += model_oof_probs
final_oof_probs /= len(model_list)
# final_oof_probs holds per-class probabilities for every sample (both task types).
# argmax is the correct decoder. The previous ordinal branch
# `batch_ordinal_encoding_to_labels(final_oof_probs[:, :-1])` was wrong: it passed
# class probabilities (which rarely exceed 0.5) into a function that expects
# cumulative/sigmoid probabilities, collapsing nearly all predictions to class 0.
oof_preds = np.argmax(final_oof_probs, axis=1)
# Score only rows that actually received predictions: the union of all
# validation indices. In kfold mode this is every row (unchanged
# behaviour); in final mode it is the holdout, giving an honest score
# instead of one diluted by the untouched (all-zero) training rows.
_scored = np.zeros(len(df), dtype=bool)
for _tr, _va in _splits:
_scored[_va] = True
valid_mask = (df["label"].values >= 0) & _scored
_, _, oof_f1, _ = precision_recall_fscore_support(
df["label"].values[valid_mask], oof_preds[valid_mask],
average="macro", zero_division=0)
_tag = "Holdout" if (split_names and "final" in split_names) else "OOF"
print(f" -> Model {_tag} Macro F1: {oof_f1:.4f} "
f"({int(valid_mask.sum())} scored rows)")
np.save(artifact_dir / "oof_probs.npy", final_oof_probs)
save_model_artifact_metadata(artifact_dir, oof_f1, fold_f1s, task_type, args.ensemble_k_folds)
print(f" -> Saved oof_probs.npy + metadata.json β {artifact_dir}")
torch.cuda.empty_cache()
gc.collect()
return final_oof_probs, oof_f1
# =============================================================================
# K-FOLD ENGINE β LIGHTGBM
# =============================================================================
class LightGBMProgressCallback:
def __init__(self, fold: int, total_folds: int, log_every: int = 100):
self.fold = fold
self.total_folds = total_folds
self.log_every = log_every
def __call__(self, env):
if (env.iteration == 0
or (env.iteration + 1) % self.log_every == 0
or env.iteration + 1 == env.end_iteration):
metrics_str = " | ".join(
f"{ds}/{metric}: {value:.4f}"
for ds, metric, value, _ in (env.evaluation_result_list or []))
print(f" [Fold {self.fold}/{self.total_folds}] "
f"Round {env.iteration + 1:>4}/{env.end_iteration} | {metrics_str}")
sys.stdout.flush()
def predict_ordinal_folds_on_rows(current_args, df_rows, model_name,
artifact_name, num_classes, dir_names=None):
"""
Predict ordinal class probabilities for rows using the saved stage2 fold
checkpoints, averaged across folds.
Purpose: UNKNOWN rows are excluded from stage2 training, so their stage2
OOF slots used to be filled with a uniform distribution selected via the
ground-truth label mask. That leaked the label into the meta-learner's
features ("perfectly uniform known-class probs" existed only for UNKNOWN
rows) and cannot be reproduced at inference. Predicting these rows with
the trained fold models is leak-free β no fold ever saw them β and makes
training features match what inference computes.
"""
from safetensors.torch import load_file as _stload
artifact_dir = get_artifact_dir(current_args.artifacts_dir, artifact_name)
device = "cuda" if torch.cuda.is_available() else "cpu"
texts = df_rows["text"].fillna("").astype(str).tolist()
n = len(texts)
bs = int(getattr(current_args, "eval_batch_size", None) or 64)
add_feats = None
if getattr(current_args, "other_cols", None) and "additional_features" in df_rows.columns:
add_feats = np.stack(df_rows["additional_features"].values).astype(np.float32)
tok_name = getattr(current_args, "tokenizer_name", None) or model_name
tokenizer = AutoTokenizer.from_pretrained(tok_name)
max_len = int(getattr(current_args, "max_length", 256))
s_sum, cnt = None, 0
_names = dir_names or [f"fold_{i}" for i in range(1, current_args.ensemble_k_folds + 1)]
for fold_num, _dname in enumerate(_names, start=1):
model_dir = artifact_dir / _dname / "model"
st = model_dir / "model.safetensors"
if not st.exists():
st = model_dir / "pytorch_model.bin"
if not st.exists():
print(f" [WARN] stage2 fold {fold_num} checkpoint missing β skipped")
continue
base = AutoModel.from_pretrained(model_name)
n_add = len(current_args.other_cols) if getattr(current_args, "other_cols", None) else 0
model = OrdinalRegressionModel(base, num_classes, num_additional_features=n_add)
sd = (_stload(str(st)) if st.suffix == ".safetensors"
else torch.load(str(st), map_location="cpu", weights_only=True))
model.load_state_dict(sd, strict=False)
del sd
model.eval().to(device)
probs = np.zeros((n, num_classes))
with torch.no_grad():
for start in range(0, n, bs):
bt = texts[start:start + bs]
enc = tokenizer(bt, padding=True, truncation=True,
max_length=max_len, return_tensors="pt")
enc = {k: v.to(device) for k, v in enc.items()}
af = (torch.tensor(add_feats[start:start + bs], device=device)
if add_feats is not None else None)
logits = model(input_ids=enc["input_ids"],
attention_mask=enc["attention_mask"],
additional_features=af)["logits"]
cum = torch.sigmoid(logits)
p = torch.zeros(cum.shape[0], num_classes, device=device)
p[:, 0] = 1 - cum[:, 0]
for i in range(1, num_classes - 1):
p[:, i] = cum[:, i - 1] - cum[:, i]
p[:, -1] = cum[:, -1]
probs[start:start + bs] = p.clamp(min=0).cpu().numpy()
s_sum = probs if s_sum is None else s_sum + probs
cnt += 1
model.cpu(); del model, base
gc.collect()
if device == "cuda":
torch.cuda.empty_cache()
print(f" [stage2-on-unknown] fold {fold_num} done")
if cnt == 0:
raise RuntimeError("No stage2 fold checkpoints found for " + artifact_name)
avg = s_sum / cnt
return avg / np.clip(avg.sum(axis=1, keepdims=True), 1e-9, None)
def generate_kfold_oof_predictions_lgbm(args, df, total_classes):
artifact_dir = get_artifact_dir(args.artifacts_dir, "tfidf_lgbm")
artifact_dir.mkdir(parents=True, exist_ok=True)
print(f" -> Artifact directory: {artifact_dir}")
kfold = StratifiedKFold(n_splits=args.ensemble_k_folds, shuffle=True, random_state=args.seed)
final_oof_probs = np.zeros((len(df), total_classes))
texts = df["text"].fillna("").tolist()
labels = df["label"].values
use_tabular = "additional_features" in df.columns
if use_tabular:
tab_matrix = csr_matrix(np.vstack(df["additional_features"].values))
print(f"\n{'='*70}\nStarting K-Fold for: TF-IDF + LightGBM\n{'='*70}")
all_oof_preds = np.zeros(len(df), dtype=int)
fold_f1s = []
for fold, (train_idx, val_idx) in enumerate(kfold.split(df, labels)):
fold_num = fold + 1
fold_artifact_dir = artifact_dir / f"fold_{fold_num}"
fold_artifact_dir.mkdir(parents=True, exist_ok=True)
print(f"\n--- Fold {fold_num}/{args.ensemble_k_folds} ---")
train_texts = [texts[i] for i in train_idx]
val_texts = [texts[i] for i in val_idx]
train_labels = labels[train_idx]
val_labels = labels[val_idx]
print(f" [Fold {fold_num}] Fitting TF-IDF vectorizers on {len(train_texts):,} samples...")
word_tfidf = TfidfVectorizer(analyzer="word", ngram_range=(1, 2),
max_features=100_000, sublinear_tf=True, min_df=2)
char_tfidf = TfidfVectorizer(analyzer="char_wb", ngram_range=(3, 5),
max_features=100_000, sublinear_tf=True, min_df=3)
X_train_word = word_tfidf.fit_transform(train_texts)
X_val_word = word_tfidf.transform(val_texts)
print(f" [Fold {fold_num}] Word TF-IDF: {len(word_tfidf.vocabulary_):,} features")
X_train_char = char_tfidf.fit_transform(train_texts)
X_val_char = char_tfidf.transform(val_texts)
print(f" [Fold {fold_num}] Char TF-IDF: {len(char_tfidf.vocabulary_):,} features")
X_train = hstack([X_train_word, X_train_char])
X_val = hstack([X_val_word, X_val_char])
if use_tabular:
X_train = hstack([X_train, tab_matrix[train_idx]])
X_val = hstack([X_val, tab_matrix[val_idx]])
print(f" [Fold {fold_num}] Feature matrix: {X_train.shape[1]:,} total | "
f"train={X_train.shape[0]:,} val={X_val.shape[0]:,}")
lgbm_model = lgb.LGBMClassifier(
n_estimators=1000, learning_rate=0.05, num_leaves=63,
subsample=0.8, colsample_bytree=0.8, class_weight="balanced",
random_state=args.seed, n_jobs=-1, verbose=-1)
print(f" [Fold {fold_num}] Training LightGBM...")
lgbm_model.fit(
X_train, train_labels,
eval_set=[(X_val, val_labels)],
eval_metric="multi_logloss",
callbacks=[
lgb.early_stopping(stopping_rounds=50, verbose=False),
lgb.log_evaluation(period=-1),
LightGBMProgressCallback(fold_num, args.ensemble_k_folds, log_every=100),
])
print(f" [Fold {fold_num}] Best iteration: {lgbm_model.best_iteration_}")
print(f" [Fold {fold_num}] Fitting isotonic calibrator...")
calibrated_model = CalibratedClassifierCV(lgbm_model, method="isotonic", cv=3)
calibrated_model.fit(X_train, train_labels)
fold_pkl = fold_artifact_dir / "model.pkl"
with open(fold_pkl, "wb") as f:
pickle.dump({"calibrated_model": calibrated_model,
"word_tfidf": word_tfidf,
"char_tfidf": char_tfidf}, f, protocol=pickle.HIGHEST_PROTOCOL)
print(f" [Fold {fold_num}] Saved calibrated model β {fold_pkl}")
fold_probs = calibrated_model.predict_proba(X_val)
final_oof_probs[val_idx] = fold_probs
all_oof_preds[val_idx] = np.argmax(fold_probs, axis=1)
fold_f1 = precision_recall_fscore_support(
val_labels, all_oof_preds[val_idx], average="macro", zero_division=0)[2]
fold_f1s.append(float(fold_f1))
print(f" [Fold {fold_num}] Val Macro F1: {fold_f1:.4f}")
_, _, oof_f1, _ = precision_recall_fscore_support(
labels, all_oof_preds, average="macro", zero_division=0)
print(f"\n -> LightGBM OOF Macro F1: {oof_f1:.4f}")
np.save(artifact_dir / "oof_probs.npy", final_oof_probs)
save_model_artifact_metadata(artifact_dir, oof_f1, fold_f1s, "tfidf_lgbm", args.ensemble_k_folds)
print(f" -> Saved oof_probs.npy + metadata.json β {artifact_dir}")
return final_oof_probs, oof_f1
# =============================================================================
# PROCESS ENSEMBLE PREDICTIONS
# =============================================================================
def process_ensemble_predictions(df, args, model_names, f1_scores, total_classes, internal_idx_to_name):
print("\n" + "="*70)
print("APPLYING DISTILLATION REMEDIES")
print("="*70)
final_ensemble_probs = np.zeros((len(df), total_classes))
if args.use_f1_weights:
weights = np.array(f1_scores) / np.sum(f1_scores)
print(f" -> F1-Weighted Averaging: {np.round(weights, 3)}")
else:
weights = np.ones(len(model_names)) / len(model_names)
print(" -> Standard Averaging")
for idx, model_name in enumerate(model_names):
clean_name = model_name.split('/')[-1]
model_cols = [f"{clean_name}_logprob_{internal_idx_to_name.get(i, i)}"
for i in range(total_classes)]
raw_probs = df[model_cols].values
if args.temperature != 1.0:
pseudo_logits = np.log(np.clip(raw_probs, 1e-7, 1.0))
scaled = pseudo_logits / args.temperature
raw_probs = np.exp(scaled) / np.sum(np.exp(scaled), axis=1, keepdims=True)
final_ensemble_probs += raw_probs * weights[idx]
entropy = -np.sum(final_ensemble_probs * np.log(np.clip(final_ensemble_probs, 1e-7, 1.0)), axis=1)
df["ensemble_entropy"] = entropy
# 1. Update the condition to check the new explicit variables
if args.alpha_correct < 1.0 or args.alpha_incorrect < 1.0 or args.entropy_threshold is not None:
print(f" -> Blending with Ground Truth (Correct Alpha: {args.alpha_correct}, Incorrect Alpha: {args.alpha_incorrect})")
mapping = load_mapping(args.mapping_dict_path)
hard_labels = np.zeros((len(df), total_classes))
ensemble_argmax = np.argmax(final_ensemble_probs, axis=1)
true_argmax = np.full(len(df), -1, dtype=int)
for idx, row in df.iterrows():
orig_label = str(row[args.label_col])
internal_idx = (args.ordinal_num_classes
if mapping.get(orig_label) == -1
else mapping.get(orig_label) - args.ordinal_min_label)
if internal_idx is not None and 0 <= internal_idx < total_classes:
hard_labels[idx, internal_idx] = 1.0
true_argmax[idx] = internal_idx
# 2. Apply the explicit alphas
correct_mask = (ensemble_argmax == true_argmax) & (true_argmax >= 0)
incorrect_mask = (ensemble_argmax != true_argmax) & (true_argmax >= 0)
# Start with an array of 1.0s (no blending) to safely handle unmapped/unknown labels
dynamic_alphas = np.ones(len(df))
dynamic_alphas[correct_mask] = args.alpha_correct
dynamic_alphas[incorrect_mask] = args.alpha_incorrect
dynamic_alphas = dynamic_alphas[:, np.newaxis]
blended = (dynamic_alphas * final_ensemble_probs) + ((1.0 - dynamic_alphas) * hard_labels)
if args.entropy_threshold is not None:
high_entropy_mask = entropy > args.entropy_threshold
blended[high_entropy_mask] = hard_labels[high_entropy_mask]
df["is_high_entropy_flag"] = high_entropy_mask
print(f" -> Reverted {high_entropy_mask.sum()} high-entropy rows to hard labels.")
final_ensemble_probs = blended
for idx, col in enumerate(
[f"final_logprob_{internal_idx_to_name.get(i, i)}" for i in range(total_classes)]
):
df[col] = final_ensemble_probs[:, idx]
return df
# =============================================================================
# ANALYSIS
# =============================================================================
def analyze_ensemble_characteristics(df, args, model_names, f1_scores, total_classes):
print("\n" + "="*70)
print("ENSEMBLE DISTILLATION ANALYSIS & RECOMMENDATIONS")
print("="*70)
raw_ensemble_probs = np.zeros((len(df), total_classes))
clean_model_names = [name.split('/')[-1] for name in model_names]
for clean_name in clean_model_names:
model_cols = [col for col in df.columns if col.startswith(f"{clean_name}_logprob_")]
raw_ensemble_probs += df[model_cols].values
raw_ensemble_probs /= len(model_names)
max_f1, min_f1 = max(f1_scores), min(f1_scores)
f1_spread = max_f1 - min_f1
print(f"1. Model Disparity (F1 Spread): {f1_spread:.4f} (Max: {max_f1:.4f}, Min: {min_f1:.4f})")
print(" -> REC: USE `--use_f1_weights`." if f1_spread > 0.05
else " -> REC: Standard averaging is fine.")
max_probs = np.max(raw_ensemble_probs, axis=1)
avg_confidence = np.mean(max_probs)
print(f"\n2. Average Top-Choice Confidence: {avg_confidence:.2%}")
if avg_confidence > 0.90: print(" -> REC: Set `--temperature` > 1.0 (e.g., 1.5-2.0).")
elif avg_confidence < 0.60: print(" -> REC: Set `--temperature` < 1.0 (e.g., 0.5-0.8).")
else: print(" -> REC: Leave `--temperature` at 1.0.")
entropy = -np.sum(raw_ensemble_probs * np.log(np.clip(raw_ensemble_probs, 1e-7, 1.0)), axis=1)
p90_entropy = np.percentile(entropy, 90)
print(f"\n3. Entropy β Mean: {np.mean(entropy):.4f} | 90th Pct: {p90_entropy:.4f}")
print(f" -> REC: `--entropy_threshold {p90_entropy:.3f}`")
mapping = load_mapping(args.mapping_dict_path)
internal_idx_to_name = {
args.ordinal_num_classes if val == -1 else val - args.ordinal_min_label: name
for name, val in mapping.items()
}
ensemble_preds = np.argmax(raw_ensemble_probs, axis=1)
true_labels = []
for _, row in df.iterrows():
orig = str(row[args.label_col])
idx = (args.ordinal_num_classes if mapping.get(orig) == -1
else mapping.get(orig) - args.ordinal_min_label)
true_labels.append(idx if idx is not None and 0 <= idx < total_classes else -1)
true_labels = np.array(true_labels)
valid_mask = true_labels >= 0
agreement_rate = accuracy_score(true_labels[valid_mask], ensemble_preds[valid_mask])
print(f"\n4. Agreement with Ground Truth: {agreement_rate:.2%}")
if agreement_rate < 0.80:
print(" -> REC: `--alpha_incorrect 0.2` (Heavy penalty for errors)")
elif agreement_rate < 0.90:
print(" -> REC: `--alpha_incorrect 0.5` (Moderate penalty)")
else:
print(" -> REC: `--alpha_correct 1.0 --alpha_incorrect 1.0` (Trust the model entirely)")
print("="*70 + "\n")
print("Generating Deep Dive Analysis Plots...")
sns.set_theme(style="whitegrid")
fig, axes = plt.subplots(2, 2, figsize=(16, 12))
fig.suptitle('Ensemble Distillation Deep Dive Analysis', fontsize=18, y=0.98)
sns.barplot(x=clean_model_names, y=f1_scores, ax=axes[0, 0], palette="viridis")
axes[0, 0].set_title('OOF Macro F1 per Model', fontsize=14)
axes[0, 0].set_ylabel('F1 Score')
axes[0, 0].set_ylim(0, max(f1_scores) * 1.1)
for i, s in enumerate(f1_scores):
axes[0, 0].text(i, s + 0.01, f'{s:.3f}', ha='center', va='bottom', fontweight='bold')
sns.histplot(max_probs, bins=40, kde=True, ax=axes[0, 1], color="royalblue")
axes[0, 1].set_title('Ensemble Confidence Distribution', fontsize=14)
axes[0, 1].axvline(avg_confidence, color='red', linestyle='--', label=f'Mean: {avg_confidence:.2f}')
axes[0, 1].legend()
sns.histplot(entropy, bins=40, kde=True, ax=axes[1, 0], color="coral")
axes[1, 0].set_title('Ensemble Entropy Distribution', fontsize=14)
axes[1, 0].axvline(p90_entropy, color='red', linestyle='--', label=f'90th Pct: {p90_entropy:.2f}')
axes[1, 0].legend()
class_agreement, class_names = [], []
for i in range(total_classes):
mask = (true_labels == i)
if mask.sum() > 0:
class_agreement.append(accuracy_score(true_labels[mask], ensemble_preds[mask]))
class_names.append(internal_idx_to_name.get(i, str(i)))
sns.barplot(x=class_names, y=class_agreement, ax=axes[1, 1], palette="magma")
axes[1, 1].set_title('Agreement Rate by True Class', fontsize=14)
axes[1, 1].set_ylim(0, 1.05)
for i, acc in enumerate(class_agreement):
axes[1, 1].text(i, acc + 0.02, f'{acc:.1%}', ha='center', va='bottom', fontweight='bold')
plt.tight_layout()
output_dir = Path(args.ensemble_output_path).parent
plot_path = output_dir / "ensemble_analysis_dashboard.png"
plt.savefig(plot_path, dpi=300, bbox_inches='tight')
plt.close()
print(f"-> Saved dashboard β {plot_path}")
# =============================================================================
# MAIN ORCHESTRATOR
# =============================================================================
def main():
args = parse_args()
torch.manual_seed(args.seed)
np.random.seed(args.seed)
if args.artifact_suffix:
s = args.artifact_suffix
args.artifacts_dir = f"{args.artifacts_dir}_{s}"
stem, ext = args.metadata_path.rsplit(".", 1)
args.metadata_path = f"{stem}_{s}.{ext}"
stem, ext = args.ensemble_output_path.rsplit(".", 1)
args.ensemble_output_path = f"{stem}_{s}.{ext}"
Path(args.artifacts_dir).mkdir(parents=True, exist_ok=True)
# Move the log file (created at module level in cwd) into artifacts_dir
# so all run outputs are co-located. Use flush+rename to avoid data loss.
global log_filename
dest_log = Path(args.artifacts_dir) / Path(log_filename).name
sys.stdout.log.flush()
sys.stdout.log.close()
if Path(log_filename).exists() and not dest_log.exists():
shutil.move(log_filename, dest_log)
sys.stdout.log = open(dest_log, "a")
sys.stderr = sys.stdout
log_filename = str(dest_log)
print(f" -> Log file: {dest_log}")
# --- SNAPSHOT RUN CONTEXT ---
# Save a frozen snapshot of the input config as run_config.json.
# This is the canonical record of what was run β it never gets mutated.
# The original config file stays clean and can be reused for other runs.
print(f"\nSnapshotting run context to {args.artifacts_dir}/")
run_config_path = Path(args.artifacts_dir) / "run_config.json"
with open(args.ensemble_config_path) as f:
input_config = json.load(f)
run_snapshot = {
"config_source": args.ensemble_config_path,
"data_path": args.data_path,
"mapping_dict_path": args.mapping_dict_path,
"soft_label_path": args.soft_label_path,
"cli_args": vars(args),
"started_at": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
"models": input_config,
}
with open(run_config_path, "w") as f:
json.dump(run_snapshot, f, indent=2)
print(f" -> run_config.json saved (input config snapshot + CLI args)")
# Backup the generator script itself for full reproducibility
shutil.copy2(__file__, Path(args.artifacts_dir) / Path(__file__).name)
print(f" -> {Path(__file__).name} backed up")
# Backup mapping (small, useful to have co-located with artifacts)
if args.mapping_dict_path and Path(args.mapping_dict_path).exists():
shutil.copy2(args.mapping_dict_path,
Path(args.artifacts_dir) / Path(args.mapping_dict_path).name)
print(f" -> {Path(args.mapping_dict_path).name} backed up")
print(f"\nLoading data from: {args.data_path}")
df = (pd.read_parquet(args.data_path)
if args.data_path.endswith('.parquet')
else pd.read_csv(args.data_path))
# Merge soft label columns from a previous ensemble run when provided.
# These will be used by models with loss_type="kl" in their config.
if args.soft_label_path:
print(f"Loading soft labels from: {args.soft_label_path}")
soft_df = pd.read_parquet(args.soft_label_path)
soft_cols = [c for c in soft_df.columns if c.startswith("final_logprob_")]
if not soft_cols:
raise ValueError(f"No final_logprob_* columns found in {args.soft_label_path}. "
"Run --mode process first to generate soft labels.")
# Align on index β both parquets must come from the same source data
df = df.join(soft_df[soft_cols], how="left")
print(f" -> Merged {len(soft_cols)} soft label columns: {soft_cols}")
with open(args.ensemble_config_path, "r") as f:
ensemble_configs = json.load(f)
ensemble_configs = [c for c in ensemble_configs if c.get("use", True)]
# 1. Load the mapping first so we can inspect its contents
mapping = load_mapping(args.mapping_dict_path)
# 2. Dynamically check if an Unknown category (-1) is active in this task
has_unknown_class = any(val == -1 for val in mapping.values())
total_classes = args.ordinal_num_classes + 1 if has_unknown_class else args.ordinal_num_classes
# ββ FINAL training mode: one global stratified holdout, shared by every
# model and stage so the honest-evaluation rows are identical across the
# whole ensemble (required for meta-learner fitting on those rows).
final_splits = None
if getattr(args, "training_mode", "kfold") == "final":
_rng = np.random.RandomState(args.seed)
_lbls = df[args.label_col].astype(str).values
_val = []
for _cls in np.unique(_lbls):
_cidx = np.where(_lbls == _cls)[0]
_take = min(args.val_rows_per_class, max(1, len(_cidx) // 2))
_val.extend(_rng.choice(_cidx, size=_take, replace=False))
_val = np.sort(np.array(_val))
_train = np.setdiff1d(np.arange(len(df)), _val)
final_splits = [(_train, _val)]
df["__is_holdout"] = np.isin(np.arange(len(df)), _val)
print(f"\n[FINAL MODE] Stratified holdout: {len(_val)} rows "
f"(target {args.val_rows_per_class}/class) | train: {len(_train)}")
print(f"[FINAL MODE] Each model trains ONCE; checkpoint saved under "
f"<artifact>/final/model/. F1 is holdout-honest. Fit the meta-"
f"learner on rows where __is_holdout is True.")
# 3. Safely build internal index mapping
internal_idx_to_name = {
args.ordinal_num_classes if val == -1 else val - args.ordinal_min_label: name
for name, val in mapping.items()
}
model_names = []
f1_scores = []
# -------------------------------------------------------------------------
# INTERRUPT HANDLER
# -------------------------------------------------------------------------
_interrupted = {"flag": False}
def _emergency_save(signum=None, frame=None):
if _interrupted["flag"]:
return
_interrupted["flag"] = True
sig_name = f"signal {signum}" if signum else "exit"
print(f"\n\n[INTERRUPT] Caught {sig_name}.")
if model_names:
with open(args.metadata_path, "w") as f:
json.dump({"model_names": model_names, "f1_scores": f1_scores}, f, indent=2)
print(f" -> Metadata saved β {args.metadata_path}")
print(f" -> Artifacts safe in: {args.artifacts_dir}/")
print(f" -> Re-run with the same command to resume.")
else:
print(" -> No models completed yet.")
if signum is not None:
sys.exit(1)
signal.signal(signal.SIGINT, _emergency_save)
signal.signal(signal.SIGTERM, _emergency_save)
atexit.register(_emergency_save)
# =========================================================================
# GENERATION PHASE
# =========================================================================
if args.mode in ["generate", "generate_and_process"]:
print("\n" + "="*70)
print(f"INITIATING HETEROGENEOUS ENSEMBLE DISTILLATION ({len(ensemble_configs)} Models)")
print(f"Artifacts root: {args.artifacts_dir}")
print("="*70)
for idx, config in enumerate(ensemble_configs):
model_name = config["model_name"]
lgbm_artifact_name = "tfidf_lgbm" if config.get("task_type") == "tfidf_lgbm" else model_name
# --- RESUME: filesystem is the source of truth ---
if artifact_exists(args.artifacts_dir, lgbm_artifact_name):
oof_probs, oof_f1 = load_artifact_oof_probs(args.artifacts_dir, lgbm_artifact_name)
artifact_dir = get_artifact_dir(args.artifacts_dir, lgbm_artifact_name)
with open(artifact_dir / "metadata.json") as f:
meta = json.load(f)
print(f"\n\n{'*'*70}")
print(f"LOADING FROM ARTIFACT {idx+1}/{len(ensemble_configs)}: {model_name}")
print(f" -> Saved at: {meta.get('saved_at','?')} | OOF F1: {oof_f1:.4f}")
print(f" -> Fold F1s: {meta.get('fold_f1s', [])}")
print(f"{'*'*70}")
model_names.append(model_name)
f1_scores.append(float(oof_f1))
clean_name = model_name.split('/')[-1]
for i in range(total_classes):
df[f"{clean_name}_logprob_{internal_idx_to_name.get(i, i)}"] = oof_probs[:, i]
continue
print(f"\n\n{'*'*70}")
print(f"RUNNING ENSEMBLE MODEL {idx+1}/{len(ensemble_configs)}: {model_name}")
print(f"{'*'*70}")
# Resolve all per-model overrides against global defaults
current_args = resolve_model_args(args, config)
df_model = df.copy()
# =========================================================================
# --- ADDITION: CATEGORICAL ENCODING LOGIC ---
# =========================================================================
if current_args.cat_cols:
if current_args.cat_encoding == "target":
# Temporarily map labels to numeric to calculate target means
temp_num_target = df_model[args.label_col].map(mapping)
temp_num_target = np.where(
temp_num_target == -1, args.ordinal_num_classes,
temp_num_target - args.ordinal_min_label
)
global_mean = temp_num_target.mean()
for col in current_args.cat_cols:
if current_args.cat_encoding == "frequency":
freq = df_model[col].value_counts()
df_model[col + "_encoded"] = df_model[col].map(freq)
elif current_args.cat_encoding == "target":
# Smoothed Target Encoding to prevent overfitting rare provinces
agg = pd.DataFrame({'target': temp_num_target, 'cat': df_model[col]}).groupby('cat')['target'].agg(['mean', 'count'])
smoothing = 10
smooth_mean = (agg['count'] * agg['mean'] + smoothing * global_mean) / (agg['count'] + smoothing)
df_model[col + "_encoded"] = df_model[col].map(smooth_mean).fillna(global_mean)
else: # Default: "ordinal"
df_model[col + "_encoded"] = df_model[col].astype('category').cat.codes
# Append encoded columns to other_cols so they get bundled into additional_features
encoded_cols = [c + "_encoded" for c in current_args.cat_cols]
current_args.other_cols = list(current_args.other_cols) + encoded_cols
# =========================================================================
if current_args.other_cols:
df_model[current_args.other_cols] = df_model[current_args.other_cols].fillna(0)
df_model["additional_features"] = list(
StandardScaler().fit_transform(df_model[current_args.other_cols].values))
# --- DISPATCH: TF-IDF + LightGBM ---
if config.get("task_type") == "tfidf_lgbm":
df_model["label"] = df_model[args.label_col].astype(str).map(mapping)
df_model["label"] = np.where(
df_model["label"] == -1, args.ordinal_num_classes,
df_model["label"] - args.ordinal_min_label)
df_model["label"] = df_model["label"].astype(int)
df_model["text"] = df_model[args.text_col]
model_probs, oof_f1 = generate_kfold_oof_predictions_lgbm(
current_args, df_model, total_classes)
clean_name = model_name.split('/')[-1]
model_names.append(model_name)
f1_scores.append(float(oof_f1))
for i in range(total_classes):
df[f"{clean_name}_logprob_{internal_idx_to_name.get(i, i)}"] = model_probs[:, i]
continue
# --- DISPATCH: Transformer (2-Stage or 1-Stage) ---
if config.get("split_unknown_stage", False):
df_stage1 = df_model.copy()
df_stage1["label"] = np.where(
df_stage1[args.label_col].astype(str) == args.unknown_label_value, 1, 0)
# When using KL/mixed objective, collapse multi-class soft labels to binary.
# P(unknown) = final_logprob_<unknown_label_value>
# P(known) = sum of all other final_logprob_* columns
# Fail loudly if the expected unknown column is missing β a silent CE
# fallback here would mask a misconfigured unknown_label_value.
_use_kl = getattr(current_args, "loss_type", "ce") in ("kl", "mixed_kl_ce")
if _use_kl:
prefix = getattr(current_args, "soft_label_prefix", "final_logprob_")
unknown_col = f"{prefix}{args.unknown_label_value}"
all_soft = [c for c in df_stage1.columns if c.startswith(prefix)]
known_cols = [c for c in all_soft if c != unknown_col]
if unknown_col not in df_stage1.columns:
raise ValueError(
f"loss_type='{current_args.loss_type}' with split_unknown_stage=True "
f"requires a soft label column '{unknown_col}', not found.\n"
f"Available soft label columns: {all_soft}\n"
f"--unknown_label_value is '{args.unknown_label_value}' β it must "
f"exactly match the class name used when generating the soft labels."
)
if not known_cols:
raise ValueError(
f"loss_type='{current_args.loss_type}' with split_unknown_stage=True "
f"found '{unknown_col}' but no other soft label columns for P(known). "
f"Available: {all_soft}"
)
df_stage1["__soft_known"] = df_stage1[known_cols].sum(axis=1)
df_stage1["__soft_unknown"] = df_stage1[unknown_col]
total = (df_stage1["__soft_known"] + df_stage1["__soft_unknown"]).clip(lower=1e-7)
df_stage1["__soft_known"] /= total
df_stage1["__soft_unknown"] /= total
df_stage1 = df_stage1.drop(columns=all_soft).rename(columns={
"__soft_known": f"{prefix}known",
"__soft_unknown": f"{prefix}unknown",
})
print(f" -> [Stage 1] Collapsed {len(all_soft)}-class soft labels "
f"to binary (P_known, P_unknown) for {current_args.loss_type} training")
print(f" -> [Stage 1] Unknown vs Rest Classification")
stage1_probs, _ = generate_kfold_oof_predictions(
current_args, df_stage1, "classification", [model_name],
artifact_name=model_name + "__stage1",
idx_to_name=internal_idx_to_name,
custom_splits=final_splits,
split_names=["final"] if final_splits else None)
# Release stage1 model/optimizer memory before stage2 trains β
# on tight GPUs the leftover allocations plus fragmentation
# from dynamic-padding batches cause mid-training OOM.
gc.collect()
if torch.cuda.is_available():
torch.cuda.empty_cache()
p_known, p_unknown = stage1_probs[:, 0], stage1_probs[:, 1]
odds_unknown = p_unknown / np.clip(p_known, 1e-7, 1.0)
adjusted_odds_unknown = odds_unknown / args.ordinal_num_classes
p_unknown_calibrated = adjusted_odds_unknown / (1.0 + adjusted_odds_unknown)
p_known_calibrated = 1.0 - p_unknown_calibrated
df_stage2 = df_model.copy()
known_mask = df_stage2[args.label_col].astype(str) != args.unknown_label_value
df_stage2["label"] = df_stage2[args.label_col].map(mapping)
df_stage2.loc[known_mask, "label"] = (
df_stage2.loc[known_mask, "label"].astype(int) - args.ordinal_min_label)
df_stage2.loc[~known_mask, "label"] = 0
train_df_stage2 = df_stage2[known_mask].reset_index(drop=True)
print(f" -> [Stage 2] Ordinal Regression on Knowns")
# In final mode, restrict the global holdout to the known-rows
# subset that stage2 actually trains on (positions re-indexed).
_s2_splits = _s2_names = None
if final_splits is not None:
_hold = np.zeros(len(df), dtype=bool)
_hold[final_splits[0][1]] = True
_known_pos = np.where(known_mask.values)[0]
_sub_hold = _hold[_known_pos]
_s2_splits = [(np.where(~_sub_hold)[0], np.where(_sub_hold)[0])]
_s2_names = ["final"]
stage2_probs_known, oof_f1 = generate_kfold_oof_predictions(
current_args, train_df_stage2, "ordinal", [model_name],
artifact_name=model_name + "__stage2",
idx_to_name=internal_idx_to_name,
custom_splits=_s2_splits, split_names=_s2_names)
gc.collect()
if torch.cuda.is_available():
torch.cuda.empty_cache()
# LEAK FIX: unknown rows were previously filled with a uniform
# distribution selected via the ground-truth mask, giving the
# meta-learner a label fingerprint that cannot exist at inference.
# Predict them with the trained stage2 folds instead (leak-free:
# no fold ever trained on these rows).
stage2_full = np.zeros((len(df), args.ordinal_num_classes))
stage2_full[known_mask] = stage2_probs_known
if (~known_mask).any():
print(f" -> [Stage 2] Predicting {(~known_mask).sum()} UNKNOWN "
f"rows with fold models (leak-free fill)")
stage2_full[~known_mask] = predict_ordinal_folds_on_rows(
current_args, df_stage2[~known_mask],
model_name, model_name + "__stage2",
args.ordinal_num_classes,
dir_names=["final"] if final_splits is not None else None)
model_probs = np.zeros((len(df), total_classes))
for i in range(args.ordinal_num_classes):
model_probs[:, i] = p_known_calibrated * stage2_full[:, i]
model_probs[:, -1] = p_unknown_calibrated
else:
print(f" -> [Standard] Classification")
df_model["label"] = df_model[args.label_col].astype(str).map(mapping)
df_model["label"] = np.where(
df_model["label"] == -1, args.ordinal_num_classes,
df_model["label"] - args.ordinal_min_label)
df_model["label"] = df_model["label"].astype(int)
model_probs, oof_f1 = generate_kfold_oof_predictions(
current_args, df_model, "classification", [model_name],
idx_to_name=internal_idx_to_name,
custom_splits=final_splits,
split_names=["final"] if final_splits else None)
clean_name = model_name.split('/')[-1]
model_names.append(model_name)
f1_scores.append(float(oof_f1))
for i in range(total_classes):
df[f"{clean_name}_logprob_{internal_idx_to_name.get(i, i)}"] = model_probs[:, i]
with open(args.metadata_path, "w") as f:
json.dump({"model_names": model_names, "f1_scores": f1_scores}, f, indent=2)
if final_splits is not None:
# FINAL MODE: model prob columns are only populated on the holdout
# rows (__is_holdout). Ensemble analysis and distillation remedies
# operate over all rows and exist to craft KL soft-label targets β
# both are meaningless/garbage on a 300-row honest set, so skip.
df.to_parquet(args.ensemble_output_path)
print("\n[FINAL MODE] Analysis & distillation remedies skipped "
"(only holdout rows carry predictions).")
print("[FINAL MODE] Use rows where __is_holdout is True for "
"meta-learner fitting. For KL soft-label targets, use a "
"kfold-mode run.")
print(f"\n[SUCCESS] Final-mode predictions saved β "
f"{args.ensemble_output_path}")
return
analyze_ensemble_characteristics(df, args, model_names, f1_scores, total_classes)
if args.mode == "generate":
df.to_parquet(args.ensemble_output_path)
print(f"\n[SUCCESS] Raw Generation saved β {args.ensemble_output_path}")
return
# =========================================================================
# PROCESSING PHASE
# =========================================================================
if args.mode in ["process", "generate_and_process"]:
if args.mode == "process":
with open(args.metadata_path, "r") as f:
metadata = json.load(f)
model_names, f1_scores = metadata["model_names"], metadata["f1_scores"]
# In standalone process mode, df must come from the previously generated
# soft-labels parquet (which has the model logprob columns), not from
# the original data_path which has none of those columns.
df = pd.read_parquet(args.ensemble_output_path)
df = process_ensemble_predictions(
df, args, model_names, f1_scores, total_classes, internal_idx_to_name)
df.to_parquet(args.ensemble_output_path)
print("\n" + "="*70)
print(f"[SUCCESS] Final Distilled Parquet saved β {args.ensemble_output_path}")
print("="*70)
outputs_to_backup = [args.metadata_path, args.ensemble_output_path]
for fpath in outputs_to_backup:
if fpath and Path(fpath).exists():
shutil.copy2(fpath, Path(args.artifacts_dir) / Path(fpath).name)
print(f" -> Backed up final outputs to {args.artifacts_dir}/")
if __name__ == "__main__":
main() |