Datasets:
File size: 74,093 Bytes
148072e | 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 | #!/usr/bin/env python3
# -----------------------------------------------------------------------------
# Ablation-study evaluator for LoRA fine-tuned adapters (custom inference path).
#
# Typical workflow:
# 1) Fine-tune adapters for multiple (task, perc) splits with VLM_finetune.
# 2) Use THIS script to evaluate each adapter on its matching test split.
#
# What this script discovers and evaluates:
# - Dataset splits live under: <splits-root>/task_*/perc_*/test/*.json
# - LoRA adapters live under: <adapter-root>/task_*/perc_*/
#
# Outputs (written into each split's results directory):
# - <base>.jsonl per-sample records (prompt/gt/pred/scoring + metadata)
# - <base>_summary.json per-split aggregate metrics + args
# - <base>_accuracy_summary.txt human-readable per-circuit + global accuracy
#
# Notes:
# - This is a "custom" evaluator: it loads the base model + adapter via Transformers/PEFT and
# runs the model's chat-style inference (not lmdeploy).
# - Task types differ:
# - choice tasks (a1/b1/c1) are scored by extracting A-F letters from model output
# - box tasks (b2/c2) are scored by parsing coordinate tuples / bounding boxes
# -----------------------------------------------------------------------------
import argparse
import datetime as _dt
import json
import os
import random
import re
from typing import Any, Dict, List, Optional, Sequence, Tuple
# ---- Minimal evaluation utilities ----
# The regexes below are deliberately conservative: many VLMs produce verbose text and we
# want to avoid accidentally extracting choice letters from unrelated prose.
# Some datasets use A-D, others (base circuits) can use A-F.
# NOTE: Don't use a naive "\bA\b" match for predictions; many models emit prose
# containing standalone 'A' tokens (e.g. 'A breakdown...'), which would create
# false positives. We keep a strict token matcher and add higher-priority patterns.
CHOICE_TOKEN_RE = re.compile(r"\b([A-F])\s*(?:[\.,\)])")
CHOICE_LABEL_RE = re.compile(
r"(?i)(?:^|\b)(?:final\s*answer|final|answer|choice)\s*[:\-]?\s*([A-F])\s*(?:[\.,\)]|\b)"
)
CHOICE_CORRECT_RE = re.compile(r"(?i)(?:the\s+)?correct\s+answer\s+is\s*([A-F])\s*(?:[\.,\)]|\b)")
CHOICE_LINE_RE = re.compile(r"^\s*([A-F])\s*(?:[\.,\)]\s*)?$")
CHOICE_COORDS_LINE_RE = re.compile(r"^\s*([A-F])\s*,\s*(?:coordinates?|bbox|boxes?)\b", re.IGNORECASE)
BOX_RE = re.compile(r"\(\s*(-?\d+)\s*,\s*(-?\d+)\s*\)\s*-\s*\(\s*(-?\d+)\s*,\s*(-?\d+)\s*\)")
INT_RE = re.compile(r"-?\d+")
def _now_tag() -> str:
return _dt.datetime.now().strftime("%Y%m%d_%H%M%S")
def _assert_deps() -> None:
missing: List[str] = []
for name in ["torch", "transformers", "peft", "PIL"]:
try:
__import__(name)
except Exception:
missing.append(name)
if missing:
raise SystemExit(
"Missing required packages: "
+ ", ".join(missing)
+ "\nActivate your environment first, e.g.:\n"
+ " source mydata/<USER>/conda/anaconda3/etc/profile.d/conda.sh\n"
+ " conda activate VLM-ft\n"
)
def _parse_csv(value: str | None) -> list[str] | None:
if value is None:
return None
items = [v.strip() for v in value.split(",") if v.strip()]
return items or None
def _normalize_task_token(token: str) -> str:
t = token.strip()
if not t:
raise ValueError("Empty task token")
if t.startswith("task_"):
return t
return f"task_{t}"
def _normalize_perc_token(token: str) -> str:
t = token.strip()
if not t:
raise ValueError("Empty perc token")
if t.startswith("perc_"):
return t
if t.isdigit():
return f"perc_{int(t):03d}"
raise ValueError(f"Unrecognized perc token: {token!r} (expected e.g. 25 or perc_025)")
def _perc_key(name: str) -> int:
m = re.search(r"perc_(\d+)", name)
return int(m.group(1)) if m else 10**9
def _task_short(task_dir: str) -> str:
return task_dir[len("task_") :] if task_dir.startswith("task_") else task_dir
def _iter_random_items(items: Sequence[Dict[str, Any]], n: int, seed: int) -> List[Dict[str, Any]]:
rng = random.Random(seed)
idxs = list(range(len(items)))
rng.shuffle(idxs)
if n < 0 or n >= len(items):
selected = idxs
else:
selected = idxs[:n]
return [items[i] for i in selected]
def _find_single_json(dir_path: str) -> str:
if not os.path.isdir(dir_path):
raise FileNotFoundError(f"Missing directory: {dir_path}")
cands = [os.path.join(dir_path, f) for f in os.listdir(dir_path) if f.endswith(".json")]
cands = [p for p in cands if os.path.isfile(p)]
cands.sort()
if len(cands) != 1:
raise RuntimeError(f"Expected exactly 1 .json in {dir_path}, found {len(cands)}: {cands}")
return cands[0]
def discover_ablation_runs(
*,
splits_root: str,
adapter_root: str,
tasks_filter: Optional[List[str]],
percs_filter: Optional[List[str]],
) -> List[Dict[str, str]]:
"""Discover runs under ablation_splits/task_*/perc_*.
Returns dicts with keys: task_dir, perc_dir, task, perc, test_path, adapter_path, results_dir.
"""
# Each discovered run corresponds to one (task, perc) split.
# We compute the matching adapter and results directory paths by convention.
if not os.path.isdir(splits_root):
raise FileNotFoundError(f"splits_root not found: {splits_root}")
runs: List[Dict[str, str]] = []
for task_dir in sorted(
d
for d in os.listdir(splits_root)
if os.path.isdir(os.path.join(splits_root, d)) and d.startswith("task_")
):
if tasks_filter is not None and task_dir not in tasks_filter:
continue
task = _task_short(task_dir)
task_path = os.path.join(splits_root, task_dir)
perc_dirs = sorted(
(
d
for d in os.listdir(task_path)
if os.path.isdir(os.path.join(task_path, d)) and d.startswith("perc_")
),
key=_perc_key,
)
for perc_dir in perc_dirs:
if percs_filter is not None and perc_dir not in percs_filter:
continue
m = re.search(r"perc_(\d+)", perc_dir)
perc = m.group(1) if m else perc_dir
test_path = _find_single_json(os.path.join(task_path, perc_dir, "test"))
adapter_path = os.path.join(adapter_root, task_dir, perc_dir)
results_dir = os.path.join(task_path, perc_dir, "results")
runs.append(
{
"task_dir": task_dir,
"perc_dir": perc_dir,
"task": task,
"perc": perc,
"test_path": test_path,
"adapter_path": adapter_path,
"results_dir": results_dir,
}
)
return runs
def load_json(path: str) -> List[Dict[str, Any]]:
with open(path, "r", encoding="utf-8") as f:
data = json.load(f)
if not isinstance(data, list):
raise ValueError(f"Expected list in {path}, got {type(data)}")
return data
def ensure_dir(path: str) -> None:
os.makedirs(path, exist_ok=True)
def pick_unique_result_base(results_dir: str, base_name: str) -> str:
"""Return a base name that won't overwrite existing result files.
We treat a run as a trio of files:
- <base>.jsonl
- <base>_summary.json
- <base>_accuracy_summary.txt
If any of those already exist, append a suffix: <base>_r2, <base>_r3, ...
"""
# This avoids overwriting results when re-running with the same run tag or settings.
def exists_for(stem: str) -> bool:
return any(
os.path.exists(os.path.join(results_dir, stem + ext))
for ext in (".jsonl", "_summary.json", "_accuracy_summary.txt")
)
if not exists_for(base_name):
return base_name
for k in range(2, 10_000):
cand = f"{base_name}_r{k}"
if not exists_for(cand):
return cand
raise RuntimeError(f"Could not find an available output name in {results_dir} for base={base_name}")
def write_split_accuracy_summary_txt(*, summary: Dict[str, Any], out_path: str) -> None:
"""Write a human-readable accuracy summary for ONE evaluated split.
The split is identified by (task, perc) and contains a per-circuit breakdown.
"""
lines: List[str] = []
lines.append(f"Task: {summary.get('task')}")
lines.append(f"Split: {summary.get('perc')}")
lines.append(f"Test: {summary.get('test_file')}")
lines.append(f"Adapter: {summary.get('adapter')}")
lines.append(f"Effective adapter: {summary.get('effective_adapter')}")
lines.append(f"Seed: {summary.get('seed')}")
lines.append("")
num_selected = int(summary.get("num_selected") or 0)
num_scored = int(summary.get("num_scored") or 0)
num_errors = int(summary.get("num_errors") or 0)
correct = int(summary.get("correct") or 0)
wrong = int(summary.get("wrong") or 0)
acc = summary.get("accuracy")
lines.append(f"Counts: selected={num_selected} scored={num_scored} errors={num_errors}")
if acc is None:
lines.append("GLOBAL: n_scored=0")
else:
lines.append(f"GLOBAL: acc={float(acc):.4f} ({correct}/{max(num_scored, 1)}), wrong={wrong}")
lines.append("")
lines.append("BY_CIRCUIT:")
by_circuit = summary.get("by_circuit") or {}
if not isinstance(by_circuit, dict) or not by_circuit:
lines.append("- (none)")
else:
for circuit in sorted(by_circuit.keys()):
v = by_circuit.get(circuit) or {}
c_correct = int(v.get("correct") or 0)
c_scored = int(v.get("scored") or 0)
c_errors = int(v.get("errors") or 0)
c_acc = v.get("accuracy")
if c_acc is None and c_scored:
c_acc = c_correct / c_scored
if c_acc is None:
lines.append(f"- {circuit}: n_scored=0, errors={c_errors}")
else:
lines.append(f"- {circuit}: acc={float(c_acc):.4f} ({c_correct}/{c_scored}), errors={c_errors}")
with open(out_path, "w", encoding="utf-8") as f:
f.write("\n".join(lines) + "\n")
def extract_prompt(item: Dict[str, Any]) -> str:
conversations = item.get("conversations") or []
if not conversations:
return ""
user_turn = conversations[0]
prompt = str(user_turn.get("value", ""))
prompt = prompt.replace("<ImageHere>", "").strip()
prompt = re.sub(r"\s+", " ", prompt).strip()
return prompt
def extract_ground_truth(item: Dict[str, Any]) -> str:
conversations = item.get("conversations") or []
if len(conversations) < 2:
return ""
return str(conversations[-1].get("value", "")).strip()
def parse_choice_letter(text: str) -> Optional[str]:
if not text:
return None
t = str(text).strip()
if not t:
return None
# 1) Highest confidence: explicitly labeled answer.
for rx in (CHOICE_LABEL_RE, CHOICE_CORRECT_RE):
m = rx.search(t)
if m:
return m.group(1).upper()
# 2) Next: check last/first non-empty lines for a bare "A" or "A.".
lines = [ln.strip() for ln in t.splitlines() if ln.strip()]
for ln in reversed(lines[-8:]):
m = CHOICE_COORDS_LINE_RE.match(ln)
if m:
return m.group(1).upper()
m = CHOICE_LINE_RE.match(ln.upper())
if m:
return m.group(1).upper()
for ln in lines[:8]:
m = CHOICE_COORDS_LINE_RE.match(ln)
if m:
return m.group(1).upper()
m = CHOICE_LINE_RE.match(ln.upper())
if m:
return m.group(1).upper()
# 3) Fallback: find the last strict token like "A." or "A," and ignore
# likely option-list echoes (e.g., "A. ... B. ... C. ...").
tu = t.upper()
matches = list(CHOICE_TOKEN_RE.finditer(tu))
for m in reversed(matches):
letter = m.group(1).upper()
start = m.start()
window = tu[start : start + 120]
if any(x in window for x in (" B.", " C.", " D.", " E.", " F.")):
continue
return letter
return None
def infer_allowed_choice_letters(prompt: str) -> str:
"""Infer allowed choice letters from the prompt.
Heuristic:
- If prompt mentions options up to E/F (e.g., "E." or "F."), allow A-F.
- Otherwise default to A-D.
This keeps a1-like tasks constrained to A-D while allowing circuit-ID prompts (A-F).
"""
p = (prompt or "").upper()
if "F." in p or " F " in p:
return "ABCDEF"
if "E." in p or " E " in p:
return "ABCDEF"
return "ABCD"
def _choice_token_id_candidates(tokenizer: Any, letters: str) -> List[int]:
"""Return token ids that can represent a single-letter answer.
We try a small set of common string forms and only accept those that encode
into exactly one token.
"""
out: List[int] = []
seen: set[int] = set()
for ch in letters:
for s in (ch, f" {ch}", f"\n{ch}"):
try:
ids = tokenizer.encode(s, add_special_tokens=False)
except Exception:
continue
if isinstance(ids, list) and len(ids) == 1:
tid = int(ids[0])
if tid not in seen:
seen.add(tid)
out.append(tid)
return out
def infer_custom_chat_constrained_choice(
*,
model: Any,
tokenizer: Any,
prompt: str,
image_path: str,
hd_num: int,
allowed_letters: str,
max_new_tokens: int = 1,
) -> str:
"""Force the model to output exactly one token from allowed letter tokens.
This is a last-resort fallback for choice tasks when the model keeps producing
whitespace-only outputs (e.g. "\n") and immediately ending.
"""
allowed_token_ids = _choice_token_id_candidates(tokenizer, allowed_letters)
if not allowed_token_ids:
# Can't constrain safely; fall back to normal inference.
return infer_custom_chat(
model=model,
tokenizer=tokenizer,
prompt=prompt,
image_path=image_path,
hd_num=hd_num,
max_new_tokens=max_new_tokens,
do_sample=False,
num_beams=1,
)
def prefix_allowed_tokens_fn(batch_id: int, input_ids: Any) -> List[int]:
# Only allow the letter tokens as the *next* generated token.
return allowed_token_ids
# Ensure we generate exactly one token and don't early-stop on EOS.
try:
return infer_custom_chat(
model=model,
tokenizer=tokenizer,
prompt=prompt,
image_path=image_path,
hd_num=hd_num,
max_new_tokens=int(max_new_tokens),
do_sample=False,
num_beams=1,
# These are forwarded through model.chat(..., **kwargs) to generate().
prefix_allowed_tokens_fn=prefix_allowed_tokens_fn,
min_new_tokens=1,
)
except TypeError:
# If the underlying generate/chat doesn't accept these kwargs, fall back.
return infer_custom_chat(
model=model,
tokenizer=tokenizer,
prompt=prompt,
image_path=image_path,
hd_num=hd_num,
max_new_tokens=int(max_new_tokens),
do_sample=False,
num_beams=1,
)
def parse_boxes(text: str) -> List[Tuple[int, int, int, int]]:
if not text:
return []
boxes: List[Tuple[int, int, int, int]] = []
for m in BOX_RE.finditer(text):
boxes.append((int(m.group(1)), int(m.group(2)), int(m.group(3)), int(m.group(4))))
if not boxes:
ints = [int(x) for x in INT_RE.findall(text)]
if len(ints) >= 4 and len(ints) % 4 == 0:
boxes = [tuple(ints[i : i + 4]) for i in range(0, len(ints), 4)] # type: ignore[misc]
return boxes
def circuit_from_image_path(image_path: str) -> Optional[str]:
parts = image_path.strip().split("?")[0].strip("/").split("/")
if "dataset_tasks_mc" in parts:
i = parts.index("dataset_tasks_mc")
if i + 1 < len(parts):
return parts[i + 1]
if len(parts) >= 3:
return parts[-3]
return None
def task_mode(task: str) -> str:
task = task.lower()
if task in {"a1", "b1", "c1"}:
return "choice"
if task in {"b2", "c2"}:
return "boxes"
raise ValueError(f"Unknown task: {task}")
def validate_task_circuit(task: str, circuit: str) -> None:
task = task.lower()
if task in {"c1", "c2"} and circuit != "mixed":
raise SystemExit("For tasks c1/c2 the circuit must be 'mixed'.")
def iter_selected_items(items: Sequence[Dict[str, Any]], circuit: str, n: int, seed: int) -> List[Dict[str, Any]]:
filtered = []
for it in items:
img = (it.get("image") or [None])[0]
if not isinstance(img, str):
continue
c = circuit_from_image_path(img)
if c == circuit:
filtered.append(it)
rng = random.Random(seed)
rng.shuffle(filtered)
if n < 0 or n >= len(filtered):
return filtered
return filtered[:n]
def score_item(task: str, gt: str, pred: str) -> Dict[str, Any]:
mode = task_mode(task)
if mode == "choice":
gt_letter = parse_choice_letter(gt)
pred_letter = parse_choice_letter(pred)
correct = (gt_letter is not None) and (pred_letter == gt_letter)
return {
"mode": mode,
"gt_letter": gt_letter,
"pred_letter": pred_letter,
"correct": bool(correct),
}
if mode == "boxes":
# b2/c2 are evaluated primarily as localization tasks.
# Some legacy datasets may also include a choice letter, so we parse it for diagnostics,
# but correctness is based on boxes.
gt_letter = parse_choice_letter(gt)
pred_letter = parse_choice_letter(pred)
gt_boxes = parse_boxes(gt)
pred_boxes = parse_boxes(pred)
gt_boxes_sorted = sorted(gt_boxes)
pred_boxes_sorted = sorted(pred_boxes)
boxes_ok = bool(gt_boxes) and (pred_boxes == gt_boxes)
boxes_unordered_ok = bool(gt_boxes) and (pred_boxes_sorted == gt_boxes_sorted)
# Main metric: order-insensitive exact match of all boxes.
# (If you later want IoU/tolerance, this is the place to change it.)
correct = boxes_unordered_ok
return {
"mode": mode,
"gt_letter": gt_letter,
"pred_letter": pred_letter,
"gt_boxes": gt_boxes,
"pred_boxes": pred_boxes,
"gt_boxes_sorted": gt_boxes_sorted,
"pred_boxes_sorted": pred_boxes_sorted,
"correct": bool(correct),
"boxes_exact_correct": bool(boxes_ok),
"boxes_unordered_correct": bool(boxes_unordered_ok),
}
raise RuntimeError("Unhandled mode")
def _apply_hf_cache_dir(cache_dir: Optional[str]) -> None:
"""Best-effort: route HF downloads/caches to a user-specified directory.
Transformers/huggingface_hub honor these env vars.
"""
if not cache_dir:
return
os.makedirs(cache_dir, exist_ok=True)
os.environ["HF_HOME"] = cache_dir
os.environ["HF_HUB_CACHE"] = cache_dir
# Common additional cache env vars used by transformers/datasets.
os.environ["TRANSFORMERS_CACHE"] = cache_dir
os.environ["HF_DATASETS_CACHE"] = os.path.join(cache_dir, "datasets")
def resolve_test_json_path(dataset_dir: str, *, circuit: str, task: str) -> str:
"""Resolve test set JSON for either the old or reorganized dataset layout.
Old layout:
<dataset_dir>/vlm_conversations_task_<task>_test.json
New layout:
<dataset_dir>/<circuit>/vlm_conversations_task_<task>_test.json
"""
fname = f"vlm_conversations_task_{task}_test.json"
# Prefer new layout if it exists.
cand_new = os.path.join(dataset_dir, circuit, fname)
if os.path.exists(cand_new):
return cand_new
cand_old = os.path.join(dataset_dir, fname)
if os.path.exists(cand_old):
return cand_old
# Provide a helpful error message.
raise FileNotFoundError(
"Could not find test JSON. Tried:\n"
f"- {cand_new}\n"
f"- {cand_old}\n"
"If you are using the reorganized test sets, pass the parent directory (the one that contains circuit folders)."
)
_TEST_JSON_RE = re.compile(r"^vlm_conversations_task_(a1|b1|b2|c1|c2)_test\.json$")
def discover_test_sets(dataset_dir: str) -> List[Dict[str, str]]:
"""Discover available test sets in the reorganized layout.
Expected layout:
<dataset_dir>/<circuit>/vlm_conversations_task_<task>_test.json
Returns a list of dicts with keys: circuit, task, path.
"""
out: List[Dict[str, str]] = []
try:
circuits = sorted(
d
for d in os.listdir(dataset_dir)
if os.path.isdir(os.path.join(dataset_dir, d)) and not d.startswith(".")
)
except FileNotFoundError:
return out
for circuit in circuits:
cdir = os.path.join(dataset_dir, circuit)
try:
files = os.listdir(cdir)
except Exception:
continue
for fname in files:
m = _TEST_JSON_RE.match(fname)
if not m:
continue
task = m.group(1)
out.append({"circuit": circuit, "task": task, "path": os.path.join(cdir, fname)})
# Sort in a stable, human-friendly order.
task_order = {"a1": 0, "b1": 1, "b2": 2, "c1": 3, "c2": 4}
out.sort(key=lambda d: (d["circuit"], task_order.get(d["task"], 999)))
return out
def extract_prompt_custom(item: Dict[str, Any]) -> str:
"""Prompt for InternLM-XComposer2 `model.chat()`.
Unlike the lmdeploy evaluator, we must preserve/add the '<ImageHere>' token.
"""
conversations = item.get("conversations") or []
if not conversations:
return "<ImageHere>"
user_turn = conversations[0]
prompt = str(user_turn.get("value", "")).strip()
prompt = re.sub(r"\s+", " ", prompt).strip()
if "<ImageHere>" not in prompt:
prompt = "<ImageHere> " + prompt
return prompt
def _is_adapter_folder(path: str) -> bool:
return os.path.exists(os.path.join(path, "adapter_config.json"))
def _has_adapter_weights(path: str) -> bool:
return any(
os.path.exists(os.path.join(path, fname))
for fname in ("adapter_model.safetensors", "adapter_model.bin")
)
def _try_parse_checkpoint_step(name: str) -> Optional[int]:
# checkpoint-2999 -> 2999
if not name.startswith("checkpoint-"):
return None
tail = name[len("checkpoint-") :]
try:
return int(tail)
except Exception:
return None
def resolve_adapter_path(path: str) -> str:
"""Resolve a user-provided adapter path to the folder that contains adapter weights.
Some training runs save a top-level adapters directory containing checkpoint-* subfolders
where the actual adapter weights live.
"""
if not _is_adapter_folder(path):
raise ValueError(f"Adapter path must contain adapter_config.json. Got: {path}")
if _has_adapter_weights(path):
return path
# Search for the latest checkpoint-* that has adapter weights.
best_step: Optional[int] = None
best_path: Optional[str] = None
try:
for entry in os.listdir(path):
step = _try_parse_checkpoint_step(entry)
if step is None:
continue
cand = os.path.join(path, entry)
if not os.path.isdir(cand):
continue
if not _is_adapter_folder(cand):
continue
if not _has_adapter_weights(cand):
continue
if best_step is None or step > best_step:
best_step = step
best_path = cand
except FileNotFoundError:
pass
if best_path is None:
raise ValueError(
"Adapter folder does not contain adapter weights (adapter_model.*), "
"and no checkpoint-* subfolder with weights was found. "
f"Path: {path}"
)
return best_path
def resolve_user_adapter_arg(adapter: Optional[str], *, adapter_root: str) -> Optional[str]:
"""Resolve --adapter, allowing relative paths under --adapter-root."""
if not adapter:
return None
adapter = os.path.expanduser(adapter)
if not os.path.isabs(adapter):
adapter = os.path.join(adapter_root, adapter)
return adapter
def build_custom_chat_model(
*,
model_path: str,
adapter_path: Optional[str],
tokenizer_path: str,
max_length: int,
cache_dir: Optional[str],
disable_vit_post_layernorm: bool,
):
import torch
from transformers import AutoModel, AutoTokenizer
from types import MethodType
from peft import PeftModel
torch.set_grad_enabled(False)
# transformers>=4.57 deprecates torch_dtype in favor of dtype.
# Keep a compatibility fallback for older installs.
try:
base = AutoModel.from_pretrained(
model_path,
cache_dir=cache_dir,
dtype=torch.bfloat16,
trust_remote_code=True,
).cuda().eval()
except TypeError:
base = AutoModel.from_pretrained(
model_path,
cache_dir=cache_dir,
torch_dtype=torch.bfloat16,
trust_remote_code=True,
).cuda().eval()
# If provided, apply LoRA adapters in-memory (no merge/save to disk).
# IMPORTANT: we merge the adapter into the base weights (merge_and_unload)
# so the resulting object remains the original model class with a stable
# `.chat()` implementation.
if adapter_path:
adapter_path = resolve_adapter_path(adapter_path)
model = PeftModel.from_pretrained(base, adapter_path).merge_and_unload().cuda().eval()
else:
model = base
# Mitigation for the base-model warning:
# Some HF snapshots load with missing vision post_layernorm weights, which then
# get randomly initialized. If you want deterministic behavior that avoids
# depending on those random init weights, you can disable the module.
if disable_vit_post_layernorm:
try:
pln = model.vit.vision_tower.vision_model.post_layernorm # type: ignore[attr-defined]
if pln is not None:
model.vit.vision_tower.vision_model.post_layernorm = torch.nn.Identity() # type: ignore[attr-defined]
except Exception:
pass
# Inference-time settings (from your Cell 15C).
model.max_length = max_length
model.config.max_length = max_length
model.config.use_cache = False
if hasattr(model, "generation_config") and model.generation_config is not None:
model.generation_config.max_length = max_length
model.generation_config.use_cache = False
def _safe_prepare_inputs_for_generation(self,
input_ids,
past_key_values=None,
attention_mask=None,
inputs_embeds=None,
im_mask=None,
infer_mode='base',
**kwargs):
pkv = past_key_values
if pkv is not None and hasattr(pkv, 'to_legacy_cache'):
try:
pkv = pkv.to_legacy_cache()
except Exception:
pass
if isinstance(pkv, (list, tuple)):
all_none = True
for layer in pkv:
if layer is None:
continue
if isinstance(layer, (list, tuple)):
for state in layer:
if state is not None:
all_none = False
break
if not all_none:
break
else:
all_none = False
break
if all_none:
pkv = None
if isinstance(pkv, list):
pkv = tuple(tuple(x for x in layer) if isinstance(layer, (list, tuple)) else layer for layer in pkv)
elif isinstance(pkv, tuple):
pkv = tuple(tuple(x for x in layer) if isinstance(layer, (list, tuple)) else layer for layer in pkv)
past_length = 0
if isinstance(pkv, (list, tuple)):
first_valid_state = None
for layer in pkv:
if not isinstance(layer, (list, tuple)):
continue
for state in layer:
if state is not None and hasattr(state, 'shape') and len(state.shape) >= 3:
first_valid_state = state
break
if first_valid_state is not None:
break
if first_valid_state is not None and first_valid_state.shape[2] > 0:
past_length = int(first_valid_state.shape[2])
if past_length > 0:
if input_ids.shape[1] > past_length:
remove_prefix_length = past_length
else:
remove_prefix_length = max(input_ids.shape[1] - 1, 0)
if remove_prefix_length:
input_ids = input_ids[:, remove_prefix_length:]
position_ids = kwargs.get('position_ids', None)
if attention_mask is not None and position_ids is None:
position_ids = attention_mask.long().cumsum(-1) - 1
position_ids.masked_fill_(attention_mask == 0, 1)
if pkv is not None:
position_ids = position_ids[:, -input_ids.shape[1]:]
if inputs_embeds is not None and (pkv is None or past_length == 0):
model_inputs = {'inputs_embeds': inputs_embeds}
else:
model_inputs = {'input_ids': input_ids}
model_inputs.update({
'position_ids': position_ids,
'past_key_values': pkv,
'use_cache': kwargs.get('use_cache'),
'attention_mask': attention_mask,
'im_mask': im_mask,
'infer_mode': infer_mode,
})
return model_inputs
model.prepare_inputs_for_generation = MethodType(_safe_prepare_inputs_for_generation, model)
tokenizer = AutoTokenizer.from_pretrained(tokenizer_path, trust_remote_code=True, cache_dir=cache_dir)
# IMPORTANT:
# Do NOT auto-add a new "[PAD]" token at inference time.
# For this model, adding a new special token forces a resize with random init.
# We observed the model emitting that token inside answers (e.g. between coordinates),
# and since we decode with skip_special_tokens=True, it gets stripped, appearing as
# "truncation".
#
# Instead, keep the tokenizer as-is and (if needed) set pad_token_id to eos_token_id.
# For batch=1 generation this is typically fine.
try:
if getattr(tokenizer, "pad_token_id", None) is None and getattr(tokenizer, "eos_token_id", None) is not None:
tokenizer.pad_token = tokenizer.eos_token
except Exception:
pass
# Keep generation config consistent with tokenizer.
try:
if hasattr(model, "generation_config") and model.generation_config is not None:
model.generation_config.pad_token_id = getattr(tokenizer, "pad_token_id", None)
model.generation_config.eos_token_id = getattr(tokenizer, "eos_token_id", None)
# Reduce noisy warnings about unused sampling params when do_sample=False.
if hasattr(model.generation_config, "top_p"):
model.generation_config.top_p = None
if hasattr(model.generation_config, "temperature"):
model.generation_config.temperature = None
except Exception:
pass
return model, tokenizer
def infer_custom_chat(
*,
model: Any,
tokenizer: Any,
prompt: str,
image_path: str,
hd_num: int,
max_new_tokens: int = 16384,
do_sample: bool = False,
num_beams: int = 1,
temperature: Optional[float] = None,
top_p: Optional[float] = None,
) -> str:
import torch
# Prefer the non-deprecated autocast API when available.
try:
autocast = torch.amp.autocast # type: ignore[attr-defined]
with autocast("cuda", dtype=torch.bfloat16):
try:
out = model.chat(
tokenizer,
query=prompt,
image=image_path,
hd_num=hd_num,
history=[],
do_sample=bool(do_sample),
num_beams=int(num_beams),
use_cache=False,
max_new_tokens=max_new_tokens,
temperature=(float(temperature) if temperature is not None else 1.0),
top_p=(float(top_p) if top_p is not None else 0.8),
)
except TypeError:
# Some InternLM-XComposer chat() variants don't accept max_new_tokens.
# Best-effort: set generation_config, then call chat() again.
if max_new_tokens is not None and hasattr(model, "generation_config") and model.generation_config is not None:
try:
model.generation_config.max_new_tokens = int(max_new_tokens)
except Exception:
pass
out = model.chat(
tokenizer,
query=prompt,
image=image_path,
hd_num=hd_num,
history=[],
do_sample=bool(do_sample),
num_beams=int(num_beams),
use_cache=False,
)
except Exception:
try:
out = model.chat(
tokenizer,
query=prompt,
image=image_path,
hd_num=hd_num,
history=[],
do_sample=bool(do_sample),
num_beams=int(num_beams),
use_cache=False,
max_new_tokens=max_new_tokens,
temperature=(float(temperature) if temperature is not None else 1.0),
top_p=(float(top_p) if top_p is not None else 0.8),
)
except TypeError:
if max_new_tokens is not None and hasattr(model, "generation_config") and model.generation_config is not None:
try:
model.generation_config.max_new_tokens = int(max_new_tokens)
except Exception:
pass
out = model.chat(
tokenizer,
query=prompt,
image=image_path,
hd_num=hd_num,
history=[],
do_sample=bool(do_sample),
num_beams=int(num_beams),
use_cache=False,
)
# Some chat() implementations return (resp, history), others return resp.
resp: Any
if isinstance(out, tuple) and len(out) >= 1:
resp = out[0]
else:
resp = out
if resp is None:
raise RuntimeError("model.chat() returned None")
return str(resp)
def _safe_int(x: Any) -> Optional[int]:
try:
return int(x)
except Exception:
return None
def debug_generate_custom_chat(
*,
model: Any,
tokenizer: Any,
prompt: str,
image_path: Optional[str],
hd_num: int,
max_new_tokens: int,
do_sample: bool,
num_beams: int,
temperature: Optional[float],
top_p: Optional[float],
repetition_penalty: Optional[float] = None,
) -> tuple[str, Dict[str, Any]]:
"""Run a generate() call similar to model.chat(), but return deep debug info.
This helps diagnose early stopping (EOS), max-length clamping, and tokenization issues.
"""
import torch
dbg: Dict[str, Any] = {}
dbg["max_new_tokens"] = int(max_new_tokens)
dbg["do_sample"] = bool(do_sample)
dbg["num_beams"] = int(num_beams)
dbg["temperature"] = float(temperature) if temperature is not None else None
dbg["top_p"] = float(top_p) if top_p is not None else None
dbg["hd_num"] = int(hd_num)
eos_id = getattr(tokenizer, "eos_token_id", None)
pad_id = getattr(tokenizer, "pad_token_id", None)
dbg["tokenizer"] = {
"eos_token_id": _safe_int(eos_id),
"pad_token_id": _safe_int(pad_id),
"pad_equals_eos": (pad_id is not None and eos_id is not None and int(pad_id) == int(eos_id)),
}
# InternLM-XComposer2 chat() adds [UNUSED_TOKEN_145] as an EOS to stop at end-of-assistant.
unused_145_id: Optional[int] = None
try:
unused_145_id = int(tokenizer.convert_tokens_to_ids(["[UNUSED_TOKEN_145]"])[0])
except Exception:
unused_145_id = None
dbg["unused_token_145_id"] = unused_145_id
# Build model inputs similarly to model.chat(), but keep the whole vision path
# under autocast to avoid dtype mismatches (Float vs BFloat16).
history: list[tuple[str, str]] = []
meta_instruction: Optional[str] = None
autocast = torch.amp.autocast # type: ignore[attr-defined]
with autocast("cuda", dtype=torch.bfloat16):
if image_path:
# Use the model's own helpers to ensure im_mask and image embeddings match its expectations.
img = model.encode_img(image_path, hd_num=int(hd_num))
inputs, im_mask = model.interleav_wrap_chat(tokenizer, prompt, img, history, meta_instruction)
dbg["mode"] = "image"
else:
inputs = model.build_inputs(tokenizer, prompt, history, meta_instruction)
im_mask = torch.zeros(inputs["input_ids"].shape[:2]).cuda().bool()
dbg["mode"] = "text"
# Move to device
inputs = {k: v.to(model.device) for k, v in inputs.items() if torch.is_tensor(v)}
input_ids = inputs.get("input_ids")
attention_mask = inputs.get("attention_mask")
dbg["input"] = {
"input_ids_len": int(input_ids.shape[1]) if input_ids is not None else None,
"has_attention_mask": attention_mask is not None,
"attention_mask_sum": int(attention_mask.sum().item()) if attention_mask is not None else None,
"im_mask_sum": int(im_mask.sum().item()) if im_mask is not None else None,
}
# Effective length controls (best-effort introspection)
dbg["model_lengths"] = {
"model_max_length_attr": _safe_int(getattr(model, "max_length", None)),
"config_max_length": _safe_int(getattr(getattr(model, "config", None), "max_length", None)),
"config_max_position_embeddings": _safe_int(getattr(getattr(model, "config", None), "max_position_embeddings", None)),
"generation_config_max_length": _safe_int(getattr(getattr(model, "generation_config", None), "max_length", None)),
"generation_config_max_new_tokens": _safe_int(getattr(getattr(model, "generation_config", None), "max_new_tokens", None)),
}
eos_token_id = [eos_id] if eos_id is not None else []
if unused_145_id is not None:
eos_token_id.append(unused_145_id)
dbg["eos_token_id"] = [int(x) for x in eos_token_id if x is not None]
gen_kwargs: Dict[str, Any] = {
"max_new_tokens": int(max_new_tokens),
"num_beams": int(num_beams),
"do_sample": bool(do_sample),
"temperature": float(temperature) if temperature is not None else 1.0,
"top_p": float(top_p) if top_p is not None else 0.8,
"eos_token_id": eos_token_id,
"im_mask": im_mask,
"return_dict_in_generate": True,
"output_scores": True,
}
if repetition_penalty is not None:
gen_kwargs["repetition_penalty"] = float(repetition_penalty)
out = model.generate(**inputs, **gen_kwargs)
sequences = out.sequences
seq0 = sequences[0].detach().cpu().tolist()
dbg["output"] = {
"sequences_len": int(sequences.shape[1]),
"first_token_ids": seq0[: min(48, len(seq0))],
"last_token_ids": seq0[max(len(seq0) - 48, 0) :],
}
# Locate early-stop tokens in the produced sequence.
stop_positions: Dict[str, Optional[int]] = {}
if eos_id is not None:
try:
stop_positions["eos_token_id_pos"] = seq0.index(int(eos_id))
except ValueError:
stop_positions["eos_token_id_pos"] = None
if unused_145_id is not None:
try:
stop_positions["unused_145_pos"] = seq0.index(int(unused_145_id))
except ValueError:
stop_positions["unused_145_pos"] = None
dbg["stop_positions"] = stop_positions
# Decode a window around the end to spot what got emitted right before stopping.
try:
tail_ids = seq0[max(len(seq0) - 80, 0) :]
dbg["decoded_tail"] = tokenizer.decode(tail_ids, skip_special_tokens=False)
except Exception:
dbg["decoded_tail"] = None
# Produce a response string in the same spirit as chat(): strip at end-of-assistant token.
decoded = tokenizer.decode(seq0, skip_special_tokens=True)
if "[UNUSED_TOKEN_145]" in decoded:
decoded = decoded.split("[UNUSED_TOKEN_145]")[0]
return str(decoded), dbg
def main() -> int:
_assert_deps()
# CLI entrypoint:
# - selects which (task, perc) combinations to evaluate
# - builds the base model + optional adapter
# - runs inference for each item and writes JSONL + summaries
ap = argparse.ArgumentParser(
description=(
"Run inference+evaluation for ablation-study fine-tuned LoRA adapters saved under an adapter root, "
"evaluated on the corresponding ablation_splits/<task>/<perc>/test JSON files."
)
)
ap.add_argument(
"--splits-root",
default="/users/<USER>/ablation_study_dataset_c1/ablation_splits",
help="Root of ablation splits (contains task_*/perc_*).",
)
ap.add_argument(
"--adapter-root",
default="mydata/ablation_study_outputs/finetune_lora",
help="Root directory where LoRA adapters are saved (contains task_*/perc_*).",
)
# Selection: tasks + percentages
# These flags filter which folders are visited under <splits-root>/task_*/perc_*.
ap.add_argument(
"--task",
action="append",
default=None,
help="Task short-name or folder name (e.g. a1 or task_a1). Can be repeated.",
)
ap.add_argument(
"--tasks",
type=str,
default=None,
help="Comma-separated tasks (e.g. a1,b1 or task_a1,task_b1). Default: all.",
)
ap.add_argument(
"--perc",
action="append",
default=None,
help="Dataset percentage (e.g. 25 or perc_025). Can be repeated.",
)
ap.add_argument(
"--percs",
type=str,
default=None,
help="Comma-separated percentages (e.g. 25,50,75 or perc_025,perc_050). Default: all.",
)
ap.add_argument(
"--num-samples",
type=int,
default=-1,
help="How many samples to run from each test file (-1 = all). Default: -1 (all)",
)
ap.add_argument("--seed", type=int, default=1337)
ap.add_argument(
"--skip-missing-adapter",
action="store_true",
help="If set, skip runs where the adapter folder does not exist.",
)
ap.add_argument(
"--cache-dir",
default="mydata/VLM_cache",
help=(
"Cache directory for Transformers/HuggingFace downloads (base model + tokenizer). "
"If set, also exports HF_HOME/HF_HUB_CACHE/TRANSFORMERS_CACHE to this value for the process."
),
)
# Fine-tuned model sources
# - original-base-model is the HF id used during LoRA training (tokenizer defaults to this).
# - adapter allows evaluating exactly one adapter path.
ap.add_argument(
"--original-base-model",
default="internlm/internlm-xcomposer2-4khd-7b",
help="HF model id/path for the ORIGINAL base model used for LoRA training (used for merging + tokenizer by default).",
)
ap.add_argument(
"--adapter",
default=None,
help=(
"Optional override: evaluate a single adapter path (contains adapter_config.json). "
"If set, task/perc selection is ignored and only this adapter is evaluated using the matching test split."
),
)
ap.add_argument(
"--no-adapter",
action="store_true",
help=(
"Disable LoRA adapter loading and run inference on the base model only. "
"This ignores --adapter and does not require adapter folders to exist."
),
)
# NOTE: This script is custom-only. It does not merge/save models, and does not use lmdeploy.
# custom chat settings
# These control the InternLM-XComposer2 "custom chat" inference path.
ap.add_argument("--tokenizer", default=None, help="Tokenizer path/id for custom chat (default: --original-base-model).")
ap.add_argument("--max-length", type=int, default=16384, help="custom chat model max_length")
ap.add_argument("--hd-num", type=int, default=6, help="custom chat hd_num")
ap.add_argument(
"--max-new-tokens-choice",
type=int,
default=1024,
help="Generation budget for choice-only tasks (a1/b1/c1).",
)
# Robustness helpers for choice tasks:
# - retry_empty_choice: rerun inference when output contains no parsable A-F letter
# - force_choice_letter_fallback: last-resort constrained decode to get a single letter
ap.add_argument(
"--retry-empty-choice",
type=int,
default=0,
help=(
"If >0, retry inference up to N times for choice tasks when the model output contains no parsable choice letter. "
"This is useful when the model sometimes returns an empty/newline-only response (e.g., '\\n'). Default: 0 (disabled)."
),
)
ap.add_argument(
"--retry-empty-choice-max-new-tokens",
type=int,
default=None,
help=(
"Optional override: max_new_tokens to use for retry attempts on choice tasks. "
"If not set, uses max(--max-new-tokens-choice, 16)."
),
)
ap.add_argument(
"--force-choice-letter-fallback",
action="store_true",
help=(
"If set, and a choice-task prediction still has no parsable letter after retries, "
"run a final constrained 1-token decode restricted to the allowed option letters. "
"This prevents whitespace-only outputs like '\\n'."
),
)
# Box-task decoding controls. Box tasks tend to require longer generations.
ap.add_argument(
"--max-new-tokens-boxes",
type=int,
default=16384,
help="Generation budget for box tasks (b2/c2).",
)
ap.add_argument(
"--boxes-do-sample",
action="store_true",
help="Enable sampling for box tasks (b2/c2). Useful to test greedy early-stopping.",
)
ap.add_argument(
"--boxes-temperature",
type=float,
default=0.7,
help="Sampling temperature for box tasks when --boxes-do-sample is set.",
)
ap.add_argument(
"--boxes-top-p",
type=float,
default=0.9,
help="Top-p for box tasks when --boxes-do-sample is set.",
)
ap.add_argument(
"--boxes-num-beams",
type=int,
default=1,
help="Beam count for box tasks (b2/c2). Set >1 to try beam search (do_sample stays False unless --boxes-do-sample).",
)
ap.add_argument(
"--disable-vit-post-layernorm",
action="store_true",
help=(
"Set vision_tower.vision_model.post_layernorm = Identity after loading. "
"Useful if the base snapshot reports missing post_layernorm weights and you want to avoid random-init impact."
),
)
ap.add_argument("--run-tag", default=None)
ap.add_argument("--dry-run", action="store_true")
# Debugging:
# If enabled, attach extra generate()-level diagnostics to the first items.
ap.add_argument(
"--debug-generate",
action="store_true",
help=(
"If set, run an additional low-level generate() pass for the first few samples of each split and store "
"detailed token/EOS diagnostics under rec['debug_generation']."
),
)
ap.add_argument(
"--debug-generate-max-items",
type=int,
default=3,
help="Max number of items per split to attach debug_generation info for (default: 3).",
)
args = ap.parse_args()
run_tag = args.run_tag or _now_tag()
# Normalize selection filters.
task_inputs: list[str] | None = None
if args.task:
task_inputs = list(args.task)
if args.tasks:
task_inputs = (task_inputs or []) + [args.tasks]
perc_inputs: list[str] | None = None
if args.perc:
perc_inputs = list(args.perc)
if args.percs:
perc_inputs = (perc_inputs or []) + [args.percs]
tasks_filter: Optional[List[str]] = None
if task_inputs:
toks: List[str] = []
for v in task_inputs:
for piece in v.split(","):
piece = piece.strip()
if piece:
toks.append(_normalize_task_token(piece))
tasks_filter = sorted(set(toks)) or None
percs_filter: Optional[List[str]] = None
if perc_inputs:
toks2: List[str] = []
for v in perc_inputs:
for piece in v.split(","):
piece = piece.strip()
if piece:
toks2.append(_normalize_perc_token(piece))
percs_filter = sorted(set(toks2), key=_perc_key) or None
# Optional single-adapter override.
adapter_override: Optional[str] = None
if bool(args.no_adapter) and args.adapter:
raise SystemExit("--no-adapter cannot be used together with --adapter")
if args.adapter:
adapter_override = resolve_user_adapter_arg(str(args.adapter), adapter_root=str(args.adapter_root))
if adapter_override is None:
raise SystemExit("--adapter was provided but could not be resolved")
# If task/perc not explicitly selected, try to infer from the adapter path.
if tasks_filter is None or percs_filter is None:
m_task = re.search(r"(?:^|/)(task_[^/]+)(?:/|$)", adapter_override)
m_perc = re.search(r"(?:^|/)(perc_\d+)(?:/|$)", adapter_override)
if (tasks_filter is None and m_task is None) or (percs_filter is None and m_perc is None):
raise SystemExit(
"When using --adapter, also pass --task/--perc (or include task_*/perc_* in the adapter path)."
)
if tasks_filter is None and m_task is not None:
tasks_filter = [m_task.group(1)]
if percs_filter is None and m_perc is not None:
percs_filter = [m_perc.group(1)]
if tasks_filter is None or percs_filter is None or len(tasks_filter) != 1 or len(percs_filter) != 1:
raise SystemExit("--adapter override requires selecting exactly one task and one perc")
# Discover which ablation runs to execute.
runs = discover_ablation_runs(
splits_root=str(args.splits_root),
adapter_root=str(args.adapter_root),
tasks_filter=tasks_filter,
percs_filter=percs_filter,
)
if not runs:
raise SystemExit("No ablation runs matched your selection (task/perc filters).")
if adapter_override is not None:
# Replace adapter path for the single selected run.
runs = runs[:1]
runs[0]["adapter_path"] = adapter_override
if bool(args.no_adapter):
# Evaluate the base model only (no LoRA merge). Keep split discovery the same.
for r in runs:
r["adapter_path"] = None # type: ignore[assignment]
print(f"Planned ablation runs: {len(runs)}")
for i, r in enumerate(runs, start=1):
print(f"[{i}/{len(runs)}] {r['task_dir']}/{r['perc_dir']}")
print(f" test: {r['test_path']}")
print(f" adapter: {r.get('adapter_path') or '(none)'}")
print(f" results: {r['results_dir']}")
if args.dry_run:
shown = 0
for r in runs:
items = load_json(r["test_path"])
selected = _iter_random_items(items, n=min(args.num_samples, 5), seed=args.seed)
print(f"- Split: task={r['task']} perc={r['perc']} file={r['test_path']}")
for it in selected[: min(5, len(selected))]:
img = (it.get("image") or [None])[0]
print(" ", it.get("id"), img, extract_prompt(it)[:120])
shown += 1
if shown >= 10:
break
if shown >= 10:
break
print("Dry-run complete.")
return 0
_apply_hf_cache_dir(args.cache_dir)
# capture versions for reproducibility
try:
import transformers # type: ignore
transformers_version = getattr(transformers, "__version__", None)
except Exception:
transformers_version = None
try:
import peft # type: ignore
peft_version = getattr(peft, "__version__", None)
except Exception:
peft_version = None
try:
import torch # type: ignore
torch_version = getattr(torch, "__version__", None)
except Exception:
torch_version = None
model_path = str(args.original_base_model)
tok_path = str(args.tokenizer or args.original_base_model)
# Aggregate accuracy across percs for each task
# Structure:
# agg_by_task[task] = {
# correct, scored, errors,
# by_circuit: {circuit: {correct, scored, errors}},
# by_perc: {perc_dir: {correct, scored, errors, by_circuit: {...}}}
# }
agg_by_task: Dict[str, Dict[str, Any]] = {}
for run_idx, r in enumerate(runs, start=1):
task = r["task"]
perc_dir = r["perc_dir"]
test_path = r["test_path"]
adapter_path = r.get("adapter_path")
results_dir = r["results_dir"]
effective_adapter: Optional[str] = None
if not bool(args.no_adapter):
if not isinstance(adapter_path, str) or not adapter_path:
raise SystemExit("Internal error: adapter_path missing for a run (expected a string)")
if not os.path.isdir(adapter_path):
msg = f"Missing adapter folder: {adapter_path}"
if args.skip_missing_adapter:
print(f"[SKIP] {msg}")
continue
raise SystemExit(msg)
effective_adapter = resolve_adapter_path(adapter_path)
ensure_dir(results_dir)
# Keep filenames stable and avoid duplication like 'perc-perc_025'.
perc_label = perc_dir
if perc_label.startswith("perc_"):
perc_label = perc_label[len("perc_") :]
base_name = f"{run_tag}_eval_task-{task}_perc-{perc_label}_impl-custom" + ("_base" if bool(args.no_adapter) else "")
base_name = pick_unique_result_base(results_dir, base_name)
out_jsonl = os.path.join(results_dir, base_name + ".jsonl")
out_summary = os.path.join(results_dir, base_name + "_summary.json")
out_acc_txt = os.path.join(results_dir, base_name + "_accuracy_summary.txt")
print(f"\n[{run_idx}/{len(runs)}] Evaluating task={task} perc={perc_dir}")
print(f"Test: {test_path}")
print(f"Adapter: {adapter_path or '(none)'}")
print(f"Out: {out_jsonl}")
custom_model, custom_tokenizer = build_custom_chat_model(
model_path=model_path,
adapter_path=effective_adapter,
tokenizer_path=tok_path,
max_length=int(args.max_length),
cache_dir=str(args.cache_dir) if args.cache_dir else None,
disable_vit_post_layernorm=bool(args.disable_vit_post_layernorm),
)
items = load_json(test_path)
selected = _iter_random_items(items, n=int(args.num_samples), seed=int(args.seed))
correct = 0
wrong = 0
errors: List[Dict[str, Any]] = []
by_circuit: Dict[str, Dict[str, int]] = {}
# JSONL output schema:
# - one line per evaluated item
# - includes metadata (task/perc/circuit, model/adapter, versions)
# - includes prompt+gt+prediction and a scoring object
with open(out_jsonl, "w", encoding="utf-8") as f:
for idx, it in enumerate(selected, start=1):
img_path = (it.get("image") or [None])[0]
circuit = circuit_from_image_path(img_path) if isinstance(img_path, str) else None
circuit = circuit or "unknown"
# rec is the canonical per-item record written to JSONL.
rec: Dict[str, Any] = {
"task": task,
"perc": perc_dir,
"circuit": circuit,
"index": idx,
"id": it.get("id"),
"inference_impl": "custom",
"base_model": args.original_base_model,
"adapter": adapter_path,
"effective_adapter": effective_adapter,
"cache_dir": args.cache_dir,
"versions": {
"transformers": transformers_version,
"peft": peft_version,
"torch": torch_version,
},
"disable_vit_post_layernorm": bool(args.disable_vit_post_layernorm),
}
if not isinstance(img_path, str):
rec["error"] = "missing_image_path"
errors.append(rec)
f.write(json.dumps(rec, ensure_ascii=False) + "\n")
continue
prompt = extract_prompt(it)
prompt_for_model = extract_prompt_custom(it)
gt = extract_ground_truth(it)
rec.update(
{"image": img_path, "prompt": prompt, "prompt_for_model": prompt_for_model, "ground_truth": gt}
)
# Inference+scoring:
# - infer_custom_chat produces raw model text
# - score_item parses and scores depending on task mode (choice vs boxes)
try:
gen_budget = (
int(args.max_new_tokens_choice)
if task_mode(task) == "choice"
else int(args.max_new_tokens_boxes)
)
boxes_mode = task_mode(task) == "boxes"
pred_text = infer_custom_chat(
model=custom_model,
tokenizer=custom_tokenizer,
prompt=prompt_for_model,
image_path=img_path,
hd_num=int(args.hd_num),
max_new_tokens=gen_budget,
do_sample=bool(args.boxes_do_sample and boxes_mode),
num_beams=int(args.boxes_num_beams) if boxes_mode else 1,
temperature=(args.boxes_temperature if (boxes_mode and args.boxes_do_sample) else None),
top_p=(args.boxes_top_p if (boxes_mode and args.boxes_do_sample) else None),
)
if bool(args.debug_generate) and idx <= int(args.debug_generate_max_items):
try:
dbg_pred, dbg = debug_generate_custom_chat(
model=custom_model,
tokenizer=custom_tokenizer,
prompt=prompt_for_model,
image_path=img_path,
hd_num=int(args.hd_num),
max_new_tokens=int(gen_budget),
do_sample=bool(args.boxes_do_sample and boxes_mode),
num_beams=int(args.boxes_num_beams) if boxes_mode else 1,
temperature=(args.boxes_temperature if (boxes_mode and args.boxes_do_sample) else None),
top_p=(args.boxes_top_p if (boxes_mode and args.boxes_do_sample) else None),
)
rec["debug_generation"] = {
"debug_pred": dbg_pred,
"debug": dbg,
}
except Exception as e:
rec["debug_generation"] = {
"error": f"debug_generate_failed: {type(e).__name__}: {e}",
}
# Optional robustness: if we cannot parse a choice letter at all, retry with a stricter instruction.
# This helps when the model occasionally returns a whitespace-only answer.
if task_mode(task) == "choice":
pred_letter = parse_choice_letter(pred_text)
if pred_letter is None and int(args.retry_empty_choice) > 0:
attempts: List[Dict[str, Any]] = []
retry_budget = (
int(args.retry_empty_choice_max_new_tokens)
if args.retry_empty_choice_max_new_tokens is not None
else max(int(gen_budget), 16)
)
for attempt_idx in range(1, int(args.retry_empty_choice) + 1):
strict_prompt = (
f"{prompt_for_model}\n\n"
"Return ONLY the letter (A, B, C, or D). No other text."
)
retry_text = infer_custom_chat(
model=custom_model,
tokenizer=custom_tokenizer,
prompt=strict_prompt,
image_path=img_path,
hd_num=int(args.hd_num),
max_new_tokens=retry_budget,
do_sample=False,
num_beams=1,
)
attempts.append(
{
"attempt": attempt_idx,
"max_new_tokens": retry_budget,
"prediction": retry_text,
}
)
if parse_choice_letter(retry_text) is not None:
pred_text = retry_text
break
if attempts:
rec["retry_empty_choice_attempts"] = attempts
# If still no parsable letter, optionally force a single-token choice.
if (
parse_choice_letter(pred_text) is None
and bool(args.force_choice_letter_fallback)
):
allowed_letters = infer_allowed_choice_letters(prompt_for_model)
forced = infer_custom_chat_constrained_choice(
model=custom_model,
tokenizer=custom_tokenizer,
prompt=strict_prompt,
image_path=img_path,
hd_num=int(args.hd_num),
allowed_letters=allowed_letters,
max_new_tokens=1,
)
rec["force_choice_letter_fallback"] = {
"allowed_letters": allowed_letters,
"prediction": forced,
}
pred_text = forced
rec["prediction"] = pred_text
scoring = score_item(task, gt=gt, pred=pred_text)
rec["scoring"] = scoring
by_circuit.setdefault(circuit, {"correct": 0, "wrong": 0, "errors": 0})
if scoring.get("correct"):
correct += 1
by_circuit[circuit]["correct"] += 1
else:
wrong += 1
by_circuit[circuit]["wrong"] += 1
except Exception as e:
rec["error"] = f"inference_failed: {type(e).__name__}: {e}"
errors.append(rec)
by_circuit.setdefault(circuit, {"correct": 0, "wrong": 0, "errors": 0})
by_circuit[circuit]["errors"] += 1
f.write(json.dumps(rec, ensure_ascii=False) + "\n")
if idx % 50 == 0:
print(f"Progress: {idx}/{len(selected)}")
scored = correct + wrong
run_summary: Dict[str, Any] = {
"mode": "ablation",
"task": task,
"perc": perc_dir,
"test_file": test_path,
"adapter": adapter_path,
"effective_adapter": effective_adapter,
"cache_dir": args.cache_dir,
"seed": args.seed,
"num_selected": len(selected),
"num_scored": scored,
"num_errors": len(errors),
"correct": correct,
"wrong": wrong,
"accuracy": (correct / scored) if scored else None,
"by_circuit": {
c: {
**v,
"scored": int(v["correct"] + v["wrong"]),
"accuracy": (v["correct"] / (v["correct"] + v["wrong"]))
if (v["correct"] + v["wrong"]) else None,
}
for c, v in sorted(by_circuit.items())
},
"output_jsonl": out_jsonl,
"args": {
"max_length": int(args.max_length),
"hd_num": int(args.hd_num),
"max_new_tokens_choice": int(args.max_new_tokens_choice),
"max_new_tokens_boxes": int(args.max_new_tokens_boxes),
"boxes_do_sample": bool(args.boxes_do_sample),
"boxes_temperature": float(args.boxes_temperature),
"boxes_top_p": float(args.boxes_top_p),
"boxes_num_beams": int(args.boxes_num_beams),
"retry_empty_choice": int(args.retry_empty_choice),
"retry_empty_choice_max_new_tokens": (
int(args.retry_empty_choice_max_new_tokens)
if args.retry_empty_choice_max_new_tokens is not None
else None
),
"force_choice_letter_fallback": bool(args.force_choice_letter_fallback),
"debug_generate": bool(args.debug_generate),
"debug_generate_max_items": int(args.debug_generate_max_items),
},
}
with open(out_summary, "w", encoding="utf-8") as fsum:
json.dump(run_summary, fsum, ensure_ascii=False, indent=2)
write_split_accuracy_summary_txt(summary=run_summary, out_path=out_acc_txt)
print(f"Done split: acc={run_summary['accuracy']} (correct={correct}, wrong={wrong}, errors={len(errors)})")
print(f"Summary: {out_summary}")
print(f"Accuracy summary: {out_acc_txt}")
# Update per-task aggregation
bucket = agg_by_task.setdefault(
task,
{"correct": 0, "scored": 0, "errors": 0, "by_circuit": {}, "by_perc": {}},
)
bucket["correct"] += int(correct)
bucket["scored"] += int(scored)
bucket["errors"] += int(len(errors))
perc_bucket = bucket["by_perc"].setdefault(
perc_dir,
{"correct": 0, "scored": 0, "errors": 0, "by_circuit": {}},
)
perc_bucket["correct"] += int(correct)
perc_bucket["scored"] += int(scored)
perc_bucket["errors"] += int(len(errors))
for c, v in by_circuit.items():
cb = bucket["by_circuit"].setdefault(c, {"correct": 0, "scored": 0, "errors": 0})
cb["correct"] += int(v.get("correct", 0))
cb["scored"] += int(v.get("correct", 0) + v.get("wrong", 0))
cb["errors"] += int(v.get("errors", 0))
pcb = perc_bucket["by_circuit"].setdefault(c, {"correct": 0, "scored": 0, "errors": 0})
pcb["correct"] += int(v.get("correct", 0))
pcb["scored"] += int(v.get("correct", 0) + v.get("wrong", 0))
pcb["errors"] += int(v.get("errors", 0))
# Print/write accuracy summary per task
for task, b in sorted(agg_by_task.items()):
scored = int(b["scored"])
correct2 = int(b["correct"])
acc = (correct2 / scored) if scored else None
print(f"\nTASK SUMMARY: {task}")
if acc is None:
print("- global: n_scored=0")
else:
print(f"- global: acc={acc:.4f} ({correct2}/{scored}), errors={int(b['errors'])}")
print("- by_circuit:")
for c, cv in sorted(b["by_circuit"].items()):
s2 = int(cv["scored"])
c2 = int(cv["correct"])
a2 = (c2 / s2) if s2 else None
if a2 is None:
print(f" - {c}: n_scored=0")
else:
print(f" - {c}: acc={a2:.4f} ({c2}/{s2}), errors={int(cv['errors'])}")
# Also show per-perc breakdown so it's clear where errors come from.
by_perc = b.get("by_perc") or {}
if isinstance(by_perc, dict) and by_perc:
print("- by_perc:")
for perc_dir in sorted(by_perc.keys(), key=_perc_key):
pv = by_perc.get(perc_dir) or {}
ps = int(pv.get("scored") or 0)
pc = int(pv.get("correct") or 0)
pe = int(pv.get("errors") or 0)
pa = (pc / ps) if ps else None
if pa is None:
print(f" - {perc_dir}: n_scored=0, errors={pe}")
else:
print(f" - {perc_dir}: acc={pa:.4f} ({pc}/{ps}), errors={pe}")
# Save the same summary into each task folder (once per task)
task_dir = os.path.join(str(args.splits_root), f"task_{task}")
task_results_dir = os.path.join(task_dir, "results")
ensure_dir(task_results_dir)
out_txt = os.path.join(task_results_dir, f"{run_tag}_accuracy_summary_task-{task}.txt")
lines: List[str] = []
lines.append(f"Task: {task}")
lines.append(f"Run tag: {run_tag}")
lines.append(f"Splits root: {args.splits_root}")
lines.append(f"Adapter root: {args.adapter_root}")
lines.append(f"Cache dir: {args.cache_dir}")
lines.append("")
if acc is None:
lines.append("GLOBAL: n_scored=0")
else:
lines.append(f"GLOBAL: acc={acc:.4f} ({correct2}/{scored}), errors={int(b['errors'])}")
lines.append("")
lines.append("BY_CIRCUIT:")
for c, cv in sorted(b["by_circuit"].items()):
s2 = int(cv["scored"])
c2 = int(cv["correct"])
a2 = (c2 / s2) if s2 else None
if a2 is None:
lines.append(f"- {c}: n_scored=0")
else:
lines.append(f"- {c}: acc={a2:.4f} ({c2}/{s2}), errors={int(cv['errors'])}")
by_perc = b.get("by_perc") or {}
if isinstance(by_perc, dict) and by_perc:
lines.append("")
lines.append("BY_PERC:")
for perc_dir in sorted(by_perc.keys(), key=_perc_key):
pv = by_perc.get(perc_dir) or {}
ps = int(pv.get("scored") or 0)
pc = int(pv.get("correct") or 0)
pe = int(pv.get("errors") or 0)
pa = (pc / ps) if ps else None
if pa is None:
lines.append(f"- {perc_dir}: n_scored=0, errors={pe}")
else:
lines.append(f"- {perc_dir}: acc={pa:.4f} ({pc}/{ps}), errors={pe}")
# Detailed per-circuit for this perc.
pbc = pv.get("by_circuit") or {}
if isinstance(pbc, dict) and pbc:
for circuit in sorted(pbc.keys()):
cv = pbc.get(circuit) or {}
s2 = int(cv.get("scored") or 0)
c2 = int(cv.get("correct") or 0)
e2 = int(cv.get("errors") or 0)
a2 = (c2 / s2) if s2 else None
if a2 is None:
lines.append(f" - {circuit}: n_scored=0, errors={e2}")
else:
lines.append(f" - {circuit}: acc={a2:.4f} ({c2}/{s2}), errors={e2}")
with open(out_txt, "w", encoding="utf-8") as ftxt:
ftxt.write("\n".join(lines) + "\n")
print(f"Saved: {out_txt}")
return 0
if __name__ == "__main__":
raise SystemExit(main())
|