File size: 78,502 Bytes
cb9715e | 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 | import os
import argparse
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from matplotlib.lines import Line2D
import warnings
# 경고 메시지 숨김
warnings.simplefilter("ignore", UserWarning)
def main():
# 1. Argument parsing
parser = argparse.ArgumentParser(description='Generate Spatial Representation Figures')
parser.add_argument('--data_path', type=str, required=True, help='Path to the input CSV file')
args = parser.parse_args()
# 2. Load Data
df = pd.read_csv(args.data_path)
# 3. Preprocessing
rename_dict = {
'EmbSpatial (con)': 'EmbSpatial Acc (con)',
'EmbSpatial (ctr)': 'EmbSpatial Acc (ctr)',
'CVBench3D (con)': 'CVBench3D Acc (con)',
'CVBench3D (ctr)': 'CVBench3D Acc (ctr)',
'Layer Horiz SC Layer': 'Layer Horiz SC',
'Layer Vert SC Layer': 'Layer Vert SC',
'Layer Dist SC Layer': 'Layer Dist SC',
'Entanglement': 'VD-Entanglement'
}
df.rename(columns=rename_dict, inplace=True)
cols_to_convert = ['EmbSpatial Acc (con)', 'EmbSpatial Acc (ctr)', 'CVBench3D Acc (con)', 'CVBench3D Acc (ctr)']
for col in cols_to_convert:
if col in df.columns:
df[col] = df[col].astype(str).str.replace('%', '', regex=False).replace('N/A', np.nan).astype(float)
# Add group and scale labels
def get_base(name):
name_upper = str(name).upper()
if 'MOLMO' in name_upper: return 'Molmo'
if 'NVILA-ST' in name_upper or 'NVILA ST' in name_upper: return 'NVILA-ST'
if 'ROBOREFER' in name_upper: return 'RoboRefer'
if 'NVILA' in name_upper: return 'NVILA'
if 'QWEN3' in name_upper: return 'Qwen3'
if 'QWEN' in name_upper: return 'Qwen'
return 'Other'
def get_scale(name):
name_lower = str(name).lower()
if 'vanilla' in name_lower: return 'vanilla'
if '80k' in name_lower: return '80k'
if '400k' in name_lower: return '400k'
if '800k' in name_lower: return '800k'
if '2m' in name_lower: return '2M'
return 'Special'
df['Base'] = df['Model'].apply(get_base)
df['Scale'] = df['Model'].apply(get_scale)
# 4. Filter out Qwen3
df = df[df['Base'] != 'Qwen3']
# 5. Output directory & Settings
output_dir = "evaluation_figures_final"
os.makedirs(output_dir, exist_ok=True)
sns.set_theme(style="whitegrid")
# Colors & Orders
colors = {
'Molmo': '#1f77b4',
'NVILA': '#ff7f0e',
'NVILA-ST': '#cc5500',
'Qwen': '#2ca02c',
'RoboRefer': '#d62728'
}
scale_order = ['vanilla', '80k', '400k', '800k', '2M']
st_scale_order = ['80k', '400k', '800k']
custom_lines_global = [
Line2D([0], [0], marker='o', color='w', markerfacecolor=colors['Molmo'], markersize=10, label='Molmo'),
Line2D([0], [0], marker='o', color='w', markerfacecolor=colors['NVILA'], markersize=10, label='NVILA-Lite-2B'),
Line2D([0], [0], marker='o', color='w', markerfacecolor=colors['NVILA-ST'], markeredgecolor='black', markersize=11, label='NVILA-ST'),
Line2D([0], [0], marker='o', color='w', markerfacecolor=colors['Qwen'], markersize=10, label='Qwen'),
Line2D([0], [0], marker='*', color='w', markerfacecolor=colors['RoboRefer'], markeredgecolor='black', markersize=18, label='RoboRefer-2B-SFT'),
]
# 공통 사용 RoboRefer 데이터프레임
df_robo = df[df['Base'] == 'RoboRefer']
# -----------------------------------------------------------------------------
# Figure 1: The Two Paths (Scatter with Trajectories and Labels)
# -----------------------------------------------------------------------------
plt.figure(figsize=(12, 9))
df_bases = df[df['Base'] != 'RoboRefer']
sns.scatterplot(data=df_bases, x='VD-Entanglement', y='Layer Dist SC', hue='Base', palette=colors, s=100, alpha=0.8, edgecolor='black', legend=False)
for i, row in df_bases.iterrows():
model_name = str(row['Model'])
is_st = row['Base'] == 'NVILA-ST'
is_pct = 'pct' in model_name.lower()
if is_st or is_pct:
plt.annotate(model_name, (row['VD-Entanglement'], row['Layer Dist SC']),
xytext=(6, 6), textcoords='offset points',
fontsize=9, color=colors[row['Base']], fontweight='bold', alpha=0.9)
for base in ['Molmo', 'NVILA', 'Qwen', 'NVILA-ST']:
current_order = st_scale_order if base == 'NVILA-ST' else scale_order
base_df = df[(df['Base'] == base) & (df['Scale'].isin(current_order))]
base_df = base_df.drop_duplicates(subset=['Scale']).set_index('Scale').reindex(current_order).dropna(subset=['VD-Entanglement', 'Layer Dist SC'])
if len(base_df) > 1:
for i in range(len(base_df)-1):
x1, y1 = base_df.iloc[i]['VD-Entanglement'], base_df.iloc[i]['Layer Dist SC']
x2, y2 = base_df.iloc[i+1]['VD-Entanglement'], base_df.iloc[i+1]['Layer Dist SC']
ls = '--' if base == 'NVILA-ST' else '-'
plt.annotate('', xy=(x2, y2), xytext=(x1, y1),
arrowprops=dict(arrowstyle="->", color=colors[base], alpha=0.6, lw=1.8, ls=ls))
if not df_robo.empty:
sns.scatterplot(data=df_robo, x='VD-Entanglement', y='Layer Dist SC', hue='Base',
palette=colors, s=400, marker='*', edgecolor='black', zorder=5, legend=False)
for i, row in df_robo.iterrows():
plt.annotate('RoboRefer-2B-SFT', (row['VD-Entanglement'], row['Layer Dist SC']),
xytext=(10, -5), textcoords='offset points',
fontsize=11, color=colors['RoboRefer'], fontweight='bold')
plt.legend(handles=custom_lines_global, title='Model Group', loc='upper right')
plt.title('Figure 1: The Two Paths of Spatial Representation\n(Naive Scaling vs. Genuine Understanding)', fontsize=14, fontweight='bold')
plt.xlabel('VD-Entanglement Shortcut [Lower is Better]', fontsize=12)
plt.ylabel('Distance Representation (Layer Dist SC) [Higher is Better]', fontsize=12)
plt.text(0.6, 0.05, "Mechanism 1:\nNaive Scaling\n(More Data = More Entanglement)",
fontsize=12, bbox=dict(facecolor='white', alpha=0.8, edgecolor='gray'))
plt.text(0.1, 0.20, "Mechanism 2:\nGenuine Understanding\n(Break the Shortcut)",
fontsize=12, bbox=dict(facecolor='white', alpha=0.8, edgecolor='gray'))
plt.tight_layout()
plt.savefig(os.path.join(output_dir, 'figure1_two_paths_trajectory.png'), dpi=300)
plt.close()
# -----------------------------------------------------------------------------
# Figure 1-1: NVILA and RoboRefer Only
# -----------------------------------------------------------------------------
plt.figure(figsize=(10, 8))
df_nvila_fig1_1 = df[(df['Base'] == 'NVILA') & (df['Scale'].isin(scale_order))]
sns.scatterplot(data=df_nvila_fig1_1, x='VD-Entanglement', y='Layer Dist SC', color=colors['NVILA'],
s=150, alpha=0.9, edgecolor='black', zorder=4, legend=False)
base_df = df_nvila_fig1_1.drop_duplicates(subset=['Scale']).set_index('Scale').reindex(scale_order).dropna(subset=['VD-Entanglement', 'Layer Dist SC'])
if len(base_df) > 1:
for i in range(len(base_df)-1):
x1, y1 = base_df.iloc[i]['VD-Entanglement'], base_df.iloc[i]['Layer Dist SC']
x2, y2 = base_df.iloc[i+1]['VD-Entanglement'], base_df.iloc[i+1]['Layer Dist SC']
plt.annotate('', xy=(x2, y2), xytext=(x1, y1),
arrowprops=dict(arrowstyle="-|>", color=colors['NVILA'], alpha=0.7, lw=2.5, mutation_scale=15))
for scale_val, row in base_df.iterrows():
# if scale_val == 'vanilla':
# plt.annotate('base model', (row['VD-Entanglement'], row['Layer Dist SC']),
# xytext=(10, 10), textcoords='offset points',
# fontsize=15, color=colors['NVILA'], fontweight='bold', alpha=1.0)
if scale_val in ['80k', '400k', '800k', '2M']:
plt.annotate(scale_val, (row['VD-Entanglement'], row['Layer Dist SC']),
xytext=(10, 10), textcoords='offset points',
fontsize=15, color=colors['NVILA'], fontweight='bold', alpha=1.0)
if not df_robo.empty:
sns.scatterplot(data=df_robo, x='VD-Entanglement', y='Layer Dist SC', color=colors['RoboRefer'],
s=200, marker='o', edgecolor='black', zorder=5, legend=False)
# for i, row in df_robo.iterrows():
# plt.annotate('RoboRefer-2B-SFT', (row['VD-Entanglement'], row['Layer Dist SC']),
# xytext=(10, 10), textcoords='offset points',
# fontsize=15, color=colors['RoboRefer'], fontweight='bold', alpha=1.0)
custom_lines_fig1_1 = [
Line2D([0], [0], marker='o', color='w', markerfacecolor=colors['NVILA'], markeredgecolor='black', markersize=12, label='NVILA-Lite-2B'),
Line2D([0], [0], marker='o', color='w', markerfacecolor=colors['RoboRefer'], markeredgecolor='black', markersize=12, label='RoboRefer-2B-SFT')
]
plt.legend(handles=custom_lines_fig1_1, title='Model Group', loc='upper right', fontsize=14, title_fontsize=16)
plt.xlabel('VD-Entanglement Index (VD-EI)', fontsize=16, fontweight='bold')
plt.ylabel(r'Distance Coherence ($\mathrm{Coh}_{\mathrm{D}}$)', fontsize=16, fontweight='bold')
plt.xticks(fontsize=14)
plt.yticks(fontsize=14)
plt.tight_layout()
plt.savefig(os.path.join(output_dir, 'figure1_1_nvila_roborefer_only.png'), dpi=300)
plt.close()
# -----------------------------------------------------------------------------
# Figure 1-2: NVILA and RoboRefer Only (1x3 Subplots: Horiz, Vert, Dist)
# -----------------------------------------------------------------------------
fig, axes = plt.subplots(1, 3, figsize=(24, 8))
coherence_metrics = [
('Layer Horiz SC', 'Horizontal Coherence'),
('Layer Vert SC', 'Vertical Coherence'),
('Layer Dist SC', r'Distance Coherence ($\mathrm{Coh}_{\mathrm{D}}$)')
]
for ax, (col, ylabel) in zip(axes, coherence_metrics):
if col not in df.columns:
continue
df_nvila_fig1_2 = df[(df['Base'] == 'NVILA') & (df['Scale'].isin(scale_order))]
sns.scatterplot(data=df_nvila_fig1_2, x='VD-Entanglement', y=col, color=colors['NVILA'],
s=150, alpha=0.9, edgecolor='black', zorder=4, ax=ax, legend=False)
base_df = df_nvila_fig1_2.drop_duplicates(subset=['Scale']).set_index('Scale').reindex(scale_order).dropna(subset=['VD-Entanglement', col])
if len(base_df) > 1:
for i in range(len(base_df)-1):
x1, y1 = base_df.iloc[i]['VD-Entanglement'], base_df.iloc[i][col]
x2, y2 = base_df.iloc[i+1]['VD-Entanglement'], base_df.iloc[i+1][col]
ax.annotate('', xy=(x2, y2), xytext=(x1, y1),
arrowprops=dict(arrowstyle="-|>", color=colors['NVILA'], alpha=0.7, lw=2.5, mutation_scale=15))
for scale_val, row in base_df.iterrows():
if scale_val == 'vanilla':
ax.annotate('NVILA-Lite-2B', (row['VD-Entanglement'], row[col]),
xytext=(10, 10), textcoords='offset points',
fontsize=15, color=colors['NVILA'], fontweight='bold', alpha=1.0)
elif scale_val in ['80k', '400k', '800k', '2M']:
ax.annotate(scale_val, (row['VD-Entanglement'], row[col]),
xytext=(10, 10), textcoords='offset points',
fontsize=15, color=colors['NVILA'], fontweight='bold', alpha=1.0)
if not df_robo.empty and col in df_robo.columns:
sns.scatterplot(data=df_robo, x='VD-Entanglement', y=col, color=colors['RoboRefer'],
s=200, marker='o', edgecolor='black', zorder=5, ax=ax, legend=False)
for i, row in df_robo.iterrows():
ax.annotate('RoboRefer-2B-SFT', (row['VD-Entanglement'], row[col]),
xytext=(10, 10), textcoords='offset points',
fontsize=15, color=colors['RoboRefer'], fontweight='bold', alpha=1.0)
ax.set_xlabel('VD-Entanglement Index (VD-EI)', fontsize=16, fontweight='bold')
ax.set_ylabel(ylabel, fontsize=16, fontweight='bold')
ax.tick_params(axis='both', which='major', labelsize=13)
custom_lines_fig1_2 = [
Line2D([0], [0], marker='o', color='w', markerfacecolor=colors['NVILA'], markeredgecolor='black', markersize=12, label='NVILA-Lite-2B'),
Line2D([0], [0], marker='o', color='w', markerfacecolor=colors['RoboRefer'], markeredgecolor='black', markersize=12, label='RoboRefer-2B-SFT')
]
plt.tight_layout()
fig.subplots_adjust(bottom=0.2)
fig.legend(handles=custom_lines_fig1_2, title='Model Group', loc='upper center', ncol=2,
fontsize=14, title_fontsize=16, bbox_to_anchor=(0.5, 0.12))
plt.savefig(os.path.join(output_dir, 'figure1_2_nvila_roborefer_coherence_1x3.png'), dpi=300)
plt.close()
# -----------------------------------------------------------------------------
# Figure 2: Entanglement Paradox (Line Plot)
# -----------------------------------------------------------------------------
df_scale = df[df['Base'] != 'RoboRefer'].copy()
df_scale = df_scale[df_scale['Scale'].isin(scale_order)]
df_scale = df_scale.drop_duplicates(subset=['Base', 'Scale'])
df_scale['Scale'] = pd.Categorical(df_scale['Scale'], categories=scale_order, ordered=True)
plt.figure(figsize=(10, 6))
sns.lineplot(data=df_scale, x='Scale', y='VD-Entanglement', hue='Base', style='Base',
palette=colors, dashes={'Molmo':'', 'NVILA':'', 'Qwen':'', 'NVILA-ST':(4,2)},
marker='o', linewidth=2.5, markersize=8)
if not df_robo.empty:
robo_ent = df_robo['VD-Entanglement'].values[0]
plt.axhline(y=robo_ent, color=colors['RoboRefer'], linestyle='--', label=f'RoboRefer-2B-SFT ({robo_ent:.4f})')
plt.title('Figure 2: The Entanglement Paradox during Naive Scaling', fontsize=14, fontweight='bold')
plt.ylabel('VD-Entanglement Index (VD-EI)', fontsize=12)
plt.xlabel('Fine-tuning Data Scale', fontsize=12)
plt.legend(title='Model Group', bbox_to_anchor=(1.05, 1), loc='upper left')
plt.tight_layout()
plt.savefig(os.path.join(output_dir, 'figure2_entanglement_paradox.png'), dpi=300)
plt.close()
# -----------------------------------------------------------------------------
# Figure 3: Depth Independence Ratio (Bar Chart)
# -----------------------------------------------------------------------------
if 'Layer Dist SC' in df.columns and 'Layer Vert SC' in df.columns:
df['Depth Independence Ratio'] = df['Layer Dist SC'] / df['Layer Vert SC']
rep_models = ['Molmo vanilla', 'Molmo 2M', 'NVILA vanilla', 'NVILA 2M', 'Qwen vanilla', 'Qwen 2M', 'RoboRefer']
available_rep = [m for m in rep_models if m in df['Model'].values]
df_rep = df.set_index('Model').loc[available_rep]
plt.figure(figsize=(12, 6))
bar_colors = ['#aec7e8', '#1f77b4', '#ffbb78', '#ff7f0e', '#98df8a', '#2ca02c', '#d62728']
ax = df_rep['Depth Independence Ratio'].plot(kind='bar', color=bar_colors[:len(available_rep)], edgecolor='black')
plt.title('Figure 3: Depth Independence Ratio', fontsize=14, fontweight='bold')
plt.ylabel('Ratio', fontsize=12)
plt.xticks(rotation=45, ha='right')
plt.axhline(y=0.2, color='gray', linestyle=':', alpha=0.7)
plt.tight_layout()
plt.savefig(os.path.join(output_dir, 'figure3_depth_independence_ratio.png'), dpi=300)
plt.close()
# -----------------------------------------------------------------------------
# Figure 4: Behavioral Consequence - The Gap (Grouped Bar Chart)
# -----------------------------------------------------------------------------
df_acc = df.dropna(subset=['EmbSpatial Acc (con)', 'EmbSpatial Acc (ctr)']).copy()
available_acc_models = df_acc['Model'].tolist()
fig_width = max(12, len(available_acc_models) * 0.7)
x = np.arange(len(available_acc_models))
width = 0.35
fig, ax = plt.subplots(figsize=(fig_width, 6))
rects1 = ax.bar(x - width/2, df_acc['EmbSpatial Acc (con)'], width, label='Consistent (Shortcut Works)', color='#2b83ba')
rects2 = ax.bar(x + width/2, df_acc['EmbSpatial Acc (ctr)'], width, label='Counter (Shortcut Fails)', color='#d7191c')
for i in range(len(available_acc_models)):
con_val = df_acc['EmbSpatial Acc (con)'].iloc[i]
ctr_val = df_acc['EmbSpatial Acc (ctr)'].iloc[i]
gap = con_val - ctr_val
ax.plot([i - width/2, i + width/2], [con_val, ctr_val], color='black', linestyle='-', linewidth=1.5, alpha=0.5)
ax.text(i, max(con_val, ctr_val) + 2, f'Gap: {gap:.1f}%p', ha='center', fontsize=9, fontweight='bold')
ax.set_ylabel('Accuracy (%)', fontsize=12)
ax.set_title('Figure 4: The Consistent vs. Counter Performance Gap (All Valid Models)', fontsize=14, fontweight='bold')
ax.set_xticks(x)
display_acc_models = ['RoboRefer-2B-SFT' if m == 'RoboRefer' else m for m in available_acc_models]
ax.set_xticklabels(display_acc_models, rotation=45, ha='right')
ax.legend()
plt.tight_layout()
plt.savefig(os.path.join(output_dir, 'figure4_accuracy_gap.png'), dpi=300)
plt.close()
# -----------------------------------------------------------------------------
# Figure 5: Distance Coherence vs Counter Accuracy
# -----------------------------------------------------------------------------
custom_lines_fig5 = [
Line2D([0], [0], marker='o', color='w', markerfacecolor=colors['Molmo'], markeredgecolor='black', markersize=12, label='Molmo-7B-O-0924'),
Line2D([0], [0], marker='o', color='w', markerfacecolor=colors['NVILA'], markeredgecolor='black', markersize=12, label='NVILA-Lite-2B'),
Line2D([0], [0], marker='o', color='w', markerfacecolor=colors['Qwen'], markeredgecolor='black', markersize=12, label='Qwen2.5-VL-3B-Instruct'),
Line2D([0], [0], marker='o', color='w', markerfacecolor=colors['RoboRefer'], markeredgecolor='black', markersize=12, label='RoboRefer-2B-SFT'),
]
if 'Layer Dist SC' in df.columns and 'EmbSpatial Acc (ctr)' in df.columns:
plt.figure(figsize=(10, 8))
df_valid_acc = df.dropna(subset=['EmbSpatial Acc (ctr)', 'Layer Dist SC'])
# NVILA-ST 제외
df_bases_fig5 = df_valid_acc[(df_valid_acc['Base'] != 'RoboRefer') & (df_valid_acc['Base'] != 'NVILA-ST')]
sns.scatterplot(data=df_bases_fig5, x='Layer Dist SC', y='EmbSpatial Acc (ctr)', hue='Base',
palette=colors, s=200, edgecolor='black', alpha=0.9, legend=False)
# 궤적 그리기
for base in ['Molmo', 'NVILA', 'Qwen']:
base_df = df_valid_acc[(df_valid_acc['Base'] == base) & (df_valid_acc['Scale'].isin(scale_order))]
base_df = base_df.drop_duplicates(subset=['Scale']).set_index('Scale').reindex(scale_order).dropna(subset=['Layer Dist SC', 'EmbSpatial Acc (ctr)'])
if len(base_df) > 1:
for i in range(len(base_df)-1):
x1, y1 = base_df.iloc[i]['Layer Dist SC'], base_df.iloc[i]['EmbSpatial Acc (ctr)']
x2, y2 = base_df.iloc[i+1]['Layer Dist SC'], base_df.iloc[i+1]['EmbSpatial Acc (ctr)']
plt.annotate('', xy=(x2, y2), xytext=(x1, y1),
arrowprops=dict(arrowstyle="-|>", color=colors[base], alpha=0.8, lw=2.5, mutation_scale=20))
# 텍스트 라벨링 추가 (80k, 400k, 800k, 2M)
for scale_val, row in base_df.iterrows():
if scale_val in ['80k', '400k', '800k', '2M']:
plt.annotate(scale_val, (row['Layer Dist SC'], row['EmbSpatial Acc (ctr)']),
xytext=(10, 10), textcoords='offset points',
fontsize=15, color=colors[base], fontweight='bold', alpha=1.0)
# RoboRefer를 빨간색 큰 원으로 표시
df_robo_fig5 = df_valid_acc[df_valid_acc['Base'] == 'RoboRefer']
if not df_robo_fig5.empty:
sns.scatterplot(data=df_robo_fig5, x='Layer Dist SC', y='EmbSpatial Acc (ctr)', color=colors['RoboRefer'],
s=250, marker='o', edgecolor='black', zorder=5, legend=False)
plt.legend(handles=custom_lines_fig5, title='Model Group', loc='lower right', fontsize=14, title_fontsize=16)
plt.xlabel(r'Distance Coherence ($\mathrm{Coh}_{\mathrm{D}}$)', fontsize=16, fontweight='bold')
plt.ylabel('Embspatial-Bench (Counter) Accuracy (%)', fontsize=16, fontweight='bold')
plt.xticks(fontsize=14)
plt.yticks(fontsize=14)
plt.grid(True, linestyle='--', alpha=0.7)
plt.tight_layout()
plt.savefig(os.path.join(output_dir, 'figure5_distSC_vs_counterAcc.png'), dpi=300)
plt.close()
# -----------------------------------------------------------------------------
# Figure 5-1: Dist/Vert Coherence Ratio vs Counter Accuracy
# -----------------------------------------------------------------------------
if 'Layer Dist SC' in df.columns and 'Layer Vert SC' in df.columns and 'EmbSpatial Acc (ctr)' in df.columns:
df['Dist_Vert_Ratio'] = df['Layer Dist SC'] / df['Layer Vert SC']
plt.figure(figsize=(10, 8))
df_valid_ratio = df.dropna(subset=['EmbSpatial Acc (ctr)', 'Dist_Vert_Ratio'])
# NVILA-ST 제외
df_bases_ratio = df_valid_ratio[(df_valid_ratio['Base'] != 'RoboRefer') & (df_valid_ratio['Base'] != 'NVILA-ST')]
sns.scatterplot(data=df_bases_ratio, x='Dist_Vert_Ratio', y='EmbSpatial Acc (ctr)', hue='Base',
palette=colors, s=200, edgecolor='black', alpha=0.9, legend=False)
# 궤적 그리기
for base in ['Molmo', 'NVILA', 'Qwen']:
base_df = df_valid_ratio[(df_valid_ratio['Base'] == base) & (df_valid_ratio['Scale'].isin(scale_order))]
base_df = base_df.drop_duplicates(subset=['Scale']).set_index('Scale').reindex(scale_order).dropna(subset=['Dist_Vert_Ratio', 'EmbSpatial Acc (ctr)'])
if len(base_df) > 1:
for i in range(len(base_df)-1):
x1, y1 = base_df.iloc[i]['Dist_Vert_Ratio'], base_df.iloc[i]['EmbSpatial Acc (ctr)']
x2, y2 = base_df.iloc[i+1]['Dist_Vert_Ratio'], base_df.iloc[i+1]['EmbSpatial Acc (ctr)']
plt.annotate('', xy=(x2, y2), xytext=(x1, y1),
arrowprops=dict(arrowstyle="-|>", color=colors[base], alpha=0.8, lw=2.5, mutation_scale=20))
# 텍스트 라벨링 추가
for scale_val, row in base_df.iterrows():
if scale_val in ['80k', '400k', '800k', '2M']:
plt.annotate(scale_val, (row['Dist_Vert_Ratio'], row['EmbSpatial Acc (ctr)']),
xytext=(10, 10), textcoords='offset points',
fontsize=15, color=colors[base], fontweight='bold', alpha=1.0)
# RoboRefer
df_robo_ratio = df_valid_ratio[df_valid_ratio['Base'] == 'RoboRefer']
if not df_robo_ratio.empty:
sns.scatterplot(data=df_robo_ratio, x='Dist_Vert_Ratio', y='EmbSpatial Acc (ctr)', color=colors['RoboRefer'],
s=250, marker='o', edgecolor='black', zorder=5, legend=False)
plt.legend(handles=custom_lines_fig5, title='Model Group', loc='lower right', fontsize=14, title_fontsize=16)
plt.xlabel(r'Distance Coherence / Vertical Coherence ($\mathrm{Coh}_{\mathrm{D}} / \mathrm{Coh}_{\mathrm{V}}$)', fontsize=16, fontweight='bold')
plt.ylabel('Embspatial-Bench (Counter) Accuracy (%)', fontsize=16, fontweight='bold')
plt.xticks(fontsize=14)
plt.yticks(fontsize=14)
plt.grid(True, linestyle='--', alpha=0.7)
plt.tight_layout()
plt.savefig(os.path.join(output_dir, 'figure5_1_dist_vert_ratio_vs_counterAcc.png'), dpi=300)
plt.close()
# -----------------------------------------------------------------------------
# Figure 6: 3D Scatter (Layer Dist SC, Counter Acc, VD-Entanglement)
# -----------------------------------------------------------------------------
if 'Layer Dist SC' in df.columns and 'EmbSpatial Acc (ctr)' in df.columns:
fig = plt.figure(figsize=(12, 10))
ax = fig.add_subplot(111, projection='3d')
for base_name in df_valid_acc['Base'].unique():
subset = df_valid_acc[df_valid_acc['Base'] == base_name]
c = colors.get(base_name, 'gray')
if base_name == 'RoboRefer':
ax.scatter(subset['Layer Dist SC'], subset['VD-Entanglement'], subset['EmbSpatial Acc (ctr)'],
c=c, s=300, marker='*', edgecolors='k', alpha=0.9, zorder=5)
else:
ax.scatter(subset['Layer Dist SC'], subset['VD-Entanglement'], subset['EmbSpatial Acc (ctr)'],
c=c, s=120, edgecolors='k', alpha=0.8)
for base in ['Molmo', 'NVILA', 'Qwen', 'NVILA-ST']:
current_order = st_scale_order if base == 'NVILA-ST' else scale_order
base_df = df_valid_acc[(df_valid_acc['Base'] == base) & (df_valid_acc['Scale'].isin(current_order))]
base_df = base_df.drop_duplicates(subset=['Scale']).set_index('Scale').reindex(current_order).dropna(subset=['Layer Dist SC', 'VD-Entanglement', 'EmbSpatial Acc (ctr)'])
if len(base_df) > 1:
for i in range(len(base_df)-1):
x1, y1, z1 = base_df.iloc[i]['Layer Dist SC'], base_df.iloc[i]['VD-Entanglement'], base_df.iloc[i]['EmbSpatial Acc (ctr)']
x2, y2, z2 = base_df.iloc[i+1]['Layer Dist SC'], base_df.iloc[i+1]['VD-Entanglement'], base_df.iloc[i+1]['EmbSpatial Acc (ctr)']
ls = '--' if base == 'NVILA-ST' else '-'
ax.plot([x1, x2], [y1, y2], [z1, z2], color=colors[base], linestyle=ls, linewidth=2.5, alpha=0.7)
ax.set_xlabel('Layer Dist SC', labelpad=10, fontsize=11)
ax.set_ylabel('VD-Entanglement Index (VD-EI)', labelpad=10, fontsize=11)
ax.set_zlabel('Counter Accuracy (%)', labelpad=10, fontsize=11)
ax.set_title('Figure 6: Navigating the Representation Space', fontweight='bold', fontsize=14)
ax.view_init(elev=20, azim=135)
plt.legend(handles=custom_lines_global, title='Model Group', loc='upper left', bbox_to_anchor=(1.05, 1))
plt.tight_layout()
plt.savefig(os.path.join(output_dir, 'figure6_3d_distSC_ent_counterAcc.png'), dpi=300, bbox_inches='tight')
plt.close()
# -----------------------------------------------------------------------------
# Figure 7: Consistency vs. Norm (Scatter per dimension)
# -----------------------------------------------------------------------------
norm_cols = ['Norm Horiz', 'Norm Vert', 'Norm Dist']
sc_cols = ['Layer Horiz SC', 'Layer Vert SC', 'Layer Dist SC']
if all(c in df.columns for c in norm_cols + sc_cols):
fig, axes = plt.subplots(1, 3, figsize=(18, 6))
dims = [
('Layer Horiz SC', 'Norm Horiz', 'Horizontal Dimension'),
('Layer Vert SC', 'Norm Vert', 'Vertical Dimension'),
('Layer Dist SC', 'Norm Dist', 'Distance Dimension')
]
for ax, (sc_col, norm_col, title) in zip(axes, dims):
df_dim = df.dropna(subset=[sc_col, norm_col])
df_bases_dim = df_dim[df_dim['Base'] != 'RoboRefer']
sns.scatterplot(data=df_bases_dim, x=sc_col, y=norm_col, hue='Base', palette=colors,
s=100, edgecolor='black', alpha=0.8, ax=ax, legend=False)
for base in ['Molmo', 'NVILA', 'Qwen', 'NVILA-ST']:
current_order = st_scale_order if base == 'NVILA-ST' else scale_order
base_df = df_dim[(df_dim['Base'] == base) & (df_dim['Scale'].isin(current_order))]
base_df = base_df.drop_duplicates(subset=['Scale']).set_index('Scale').reindex(current_order).dropna(subset=[sc_col, norm_col])
if len(base_df) > 1:
for i in range(len(base_df)-1):
x1, y1 = base_df.iloc[i][sc_col], base_df.iloc[i][norm_col]
x2, y2 = base_df.iloc[i+1][sc_col], base_df.iloc[i+1][norm_col]
ls = '--' if base == 'NVILA-ST' else '-'
ax.annotate('', xy=(x2, y2), xytext=(x1, y1),
arrowprops=dict(arrowstyle="->", color=colors.get(base, 'gray'), alpha=0.6, lw=1.8, ls=ls))
df_robo_dim = df_dim[df_dim['Base'] == 'RoboRefer']
if not df_robo_dim.empty:
sns.scatterplot(data=df_robo_dim, x=sc_col, y=norm_col, hue='Base',
palette=colors, s=400, marker='*', edgecolor='black', zorder=5, ax=ax, legend=False)
for i, row in df_robo_dim.iterrows():
ax.annotate('RoboRefer-2B-SFT', (row[sc_col], row[norm_col]),
xytext=(10, -5), textcoords='offset points',
fontsize=11, color=colors['RoboRefer'], fontweight='bold')
for i, row in df_bases_dim.iterrows():
model_name = str(row['Model'])
if row['Base'] == 'NVILA-ST' or 'pct' in model_name.lower():
ax.annotate(model_name, (row[sc_col], row[norm_col]),
xytext=(6, 6), textcoords='offset points',
fontsize=9, color=colors[row['Base']], fontweight='bold', alpha=0.9)
if len(df_dim) > 1:
corr = np.corrcoef(df_dim[sc_col], df_dim[norm_col])[0, 1]
ax.set_title(f"{title}\n(r={corr:.2f})", fontsize=14, fontweight='bold')
else:
ax.set_title(title, fontsize=14, fontweight='bold')
ax.set_xlabel(f'Consistency ({sc_col})', fontsize=12)
ax.set_ylabel(f'Magnitude ({norm_col})', fontsize=12)
ax.grid(True, linestyle='--', alpha=0.7)
fig.legend(handles=custom_lines_global, title='Model Group', loc='center right', bbox_to_anchor=(0.99, 0.5))
fig.suptitle('Figure 7: Sign-Corrected Consistency vs. Vector Norm', fontsize=18, fontweight='bold', y=1.05)
plt.tight_layout(rect=[0, 0, 0.88, 1])
plt.savefig(os.path.join(output_dir, 'figure7_consistency_vs_norm.png'), dpi=300, bbox_inches='tight')
plt.close()
# -----------------------------------------------------------------------------
# Figure 8: Consistency Trajectory Across Scales (1x3 Line plots)
# -----------------------------------------------------------------------------
if all(c in df.columns for c in sc_cols):
fig, axes = plt.subplots(1, 3, figsize=(18, 6))
dims = [
('Layer Horiz SC', 'Horizontal Consistency'),
('Layer Vert SC', 'Vertical Consistency'),
('Layer Dist SC', 'Distance Consistency')
]
df_scale_fig8 = df[df['Base'] != 'RoboRefer'].copy()
df_scale_fig8 = df_scale_fig8[df_scale_fig8['Scale'].isin(scale_order)]
df_scale_fig8 = df_scale_fig8.drop_duplicates(subset=['Base', 'Scale'])
df_scale_fig8['Scale'] = pd.Categorical(df_scale_fig8['Scale'], categories=scale_order, ordered=True)
for ax, (col, title) in zip(axes, dims):
sns.lineplot(data=df_scale_fig8, x='Scale', y=col, hue='Base', style='Base',
palette=colors, dashes={'Molmo':'', 'NVILA':'', 'Qwen':'', 'NVILA-ST':(4,2)},
marker='o', linewidth=2.5, markersize=8, ax=ax, legend=False)
if not df_robo.empty and col in df_robo.columns:
robo_val = df_robo[col].values[0]
ax.axhline(y=robo_val, color=colors['RoboRefer'], linestyle='--', alpha=0.8, label='RoboRefer-2B-SFT')
ax.set_title(title, fontsize=14, fontweight='bold')
ax.set_xlabel('Fine-tuning Data Scale', fontsize=12)
ax.set_ylabel(col, fontsize=12)
ax.grid(True, linestyle='--', alpha=0.7)
fig.legend(handles=custom_lines_global, title='Model Group', loc='center right', bbox_to_anchor=(0.99, 0.5))
fig.suptitle('Figure 8: Sign-Corrected Consistency Trajectory Across Scales', fontsize=18, fontweight='bold', y=1.05)
plt.tight_layout(rect=[0, 0, 0.88, 1])
plt.savefig(os.path.join(output_dir, 'figure8_consistency_trajectory.png'), dpi=300, bbox_inches='tight')
plt.close()
print(f"Success! Evaluation figures have been saved to ./{output_dir}/")
if __name__ == "__main__":
main()
# import os
# import argparse
# import pandas as pd
# import numpy as np
# import matplotlib.pyplot as plt
# import seaborn as sns
# from matplotlib.lines import Line2D
# import warnings
# # 경고 메시지 숨김
# warnings.simplefilter("ignore", UserWarning)
# def main():
# # 1. Argument parsing
# parser = argparse.ArgumentParser(description='Generate Spatial Representation Figures')
# parser.add_argument('--data_path', type=str, required=True, help='Path to the input CSV file')
# args = parser.parse_args()
# # 2. Load Data
# df = pd.read_csv(args.data_path)
# # 3. Preprocessing
# rename_dict = {
# 'EmbSpatial (con)': 'EmbSpatial Acc (con)',
# 'EmbSpatial (ctr)': 'EmbSpatial Acc (ctr)',
# 'CVBench3D (con)': 'CVBench3D Acc (con)',
# 'CVBench3D (ctr)': 'CVBench3D Acc (ctr)'
# }
# df.rename(columns=rename_dict, inplace=True)
# cols_to_convert = ['EmbSpatial Acc (con)', 'EmbSpatial Acc (ctr)', 'CVBench3D Acc (con)', 'CVBench3D Acc (ctr)']
# for col in cols_to_convert:
# if col in df.columns:
# df[col] = df[col].astype(str).str.replace('%', '', regex=False).replace('N/A', np.nan).astype(float)
# # Add group and scale labels
# def get_base(name):
# name_upper = str(name).upper()
# if 'MOLMO' in name_upper: return 'Molmo'
# if 'NVILA-ST' in name_upper or 'NVILA ST' in name_upper: return 'NVILA-ST'
# if 'ROBOREFER' in name_upper: return 'RoboRefer'
# if 'NVILA' in name_upper: return 'NVILA'
# if 'QWEN3' in name_upper: return 'Qwen3'
# if 'QWEN' in name_upper: return 'Qwen'
# return 'Other'
# def get_scale(name):
# name_lower = str(name).lower()
# if 'vanilla' in name_lower: return 'vanilla'
# if '80k' in name_lower: return '80k'
# if '400k' in name_lower: return '400k'
# if '800k' in name_lower: return '800k'
# if '2m' in name_lower: return '2M'
# return 'Special'
# df['Base'] = df['Model'].apply(get_base)
# df['Scale'] = df['Model'].apply(get_scale)
# # 4. Filter out Qwen3
# df = df[df['Base'] != 'Qwen3']
# # 5. Output directory & Settings
# output_dir = "evaluation_figures_final"
# os.makedirs(output_dir, exist_ok=True)
# sns.set_theme(style="whitegrid")
# # Colors & Orders
# colors = {
# 'Molmo': '#1f77b4',
# 'NVILA': '#ff7f0e',
# 'NVILA-ST': '#cc5500',
# 'Qwen': '#2ca02c',
# 'RoboRefer': '#d62728'
# }
# scale_order = ['vanilla', '80k', '400k', '800k', '2M']
# st_scale_order = ['80k', '400k', '800k']
# custom_lines = [
# Line2D([0], [0], marker='o', color='w', markerfacecolor=colors['Molmo'], markersize=10, label='Molmo'),
# Line2D([0], [0], marker='o', color='w', markerfacecolor=colors['NVILA'], markersize=10, label='NVILA'),
# Line2D([0], [0], marker='o', color='w', markerfacecolor=colors['NVILA-ST'], markeredgecolor='black', markersize=11, label='NVILA-ST'),
# Line2D([0], [0], marker='o', color='w', markerfacecolor=colors['Qwen'], markersize=10, label='Qwen'),
# Line2D([0], [0], marker='*', color='w', markerfacecolor=colors['RoboRefer'], markeredgecolor='black', markersize=18, label='RoboRefer'),
# ]
# # -----------------------------------------------------------------------------
# # Figure 1: The Two Paths (Scatter with Trajectories and Labels)
# # -----------------------------------------------------------------------------
# plt.figure(figsize=(12, 9))
# # Scatter: RoboRefer를 제외한 모든 모델 (pct 모델들도 점으로 그려지게 포함됨)
# df_bases = df[df['Base'] != 'RoboRefer']
# sns.scatterplot(data=df_bases, x='Entanglement', y='Peak Dist', hue='Base', palette=colors, s=100, alpha=0.8, edgecolor='black', legend=False)
# # 텍스트 라벨링: NVILA-ST와 이름에 'pct'가 들어간 모델들만 표시
# for i, row in df_bases.iterrows():
# model_name = str(row['Model'])
# is_st = row['Base'] == 'NVILA Syn'
# is_pct = '%' in model_name.lower()
# if is_st or is_pct:
# plt.annotate(model_name, (row['Entanglement'], row['Peak Dist']),
# xytext=(6, 6), textcoords='offset points',
# fontsize=9, color=colors[row['Base']], fontweight='bold', alpha=0.9)
# # Trajectories (Arrows)
# for base in ['Molmo', 'NVILA', 'Qwen', 'NVILA-ST']:
# current_order = st_scale_order if base == 'NVILA-ST' else scale_order
# base_df = df[(df['Base'] == base) & (df['Scale'].isin(current_order))]
# base_df = base_df.drop_duplicates(subset=['Scale']).set_index('Scale').reindex(current_order).dropna(subset=['Entanglement', 'Peak Dist'])
# if len(base_df) > 1:
# for i in range(len(base_df)-1):
# x1, y1 = base_df.iloc[i]['Entanglement'], base_df.iloc[i]['Peak Dist']
# x2, y2 = base_df.iloc[i+1]['Entanglement'], base_df.iloc[i+1]['Peak Dist']
# ls = '--' if base == 'NVILA-ST' else '-'
# plt.annotate('', xy=(x2, y2), xytext=(x1, y1),
# arrowprops=dict(arrowstyle="->", color=colors[base], alpha=0.6, lw=1.8, ls=ls))
# # Scatter & Label: RoboRefer
# df_robo = df[df['Base'] == 'RoboRefer']
# if not df_robo.empty:
# sns.scatterplot(data=df_robo, x='Entanglement', y='Peak Dist', hue='Base',
# palette=colors, s=400, marker='*', edgecolor='black', zorder=5, legend=False)
# for i, row in df_robo.iterrows():
# plt.annotate(row['Model'], (row['Entanglement'], row['Peak Dist']),
# xytext=(10, -5), textcoords='offset points',
# fontsize=11, color=colors['RoboRefer'], fontweight='bold')
# plt.legend(handles=custom_lines, title='Model Group', loc='upper right')
# plt.title('Figure 1: The Two Paths of Spatial Representation', fontsize=14, fontweight='bold')
# plt.xlabel('Entanglement Shortcut [Lower is Better]', fontsize=12)
# plt.ylabel('Distance Representation (Dist SC) [Higher is Better]', fontsize=12)
# plt.text(0.6, 0.05, "Mechanism 1:\nNaive Scaling\n(More Data = More Entanglement)",
# fontsize=12, bbox=dict(facecolor='white', alpha=0.8, edgecolor='gray'))
# plt.text(0.1, 0.20, "Mechanism 2:\nGenuine Understanding\n(Break the Shortcut)",
# fontsize=12, bbox=dict(facecolor='white', alpha=0.8, edgecolor='gray'))
# plt.tight_layout()
# plt.savefig(os.path.join(output_dir, 'figure1_two_paths_trajectory.png'), dpi=300)
# plt.close()
# # -----------------------------------------------------------------------------
# # Figure 2: Entanglement Paradox (Line Plot)
# # -----------------------------------------------------------------------------
# df_scale = df[df['Base'] != 'RoboRefer'].copy()
# df_scale = df_scale[df_scale['Scale'].isin(scale_order)]
# df_scale = df_scale.drop_duplicates(subset=['Base', 'Scale'])
# df_scale['Scale'] = pd.Categorical(df_scale['Scale'], categories=scale_order, ordered=True)
# plt.figure(figsize=(10, 6))
# sns.lineplot(data=df_scale, x='Scale', y='Entanglement', hue='Base', style='Base',
# palette=colors, dashes={'Molmo':'', 'NVILA':'', 'Qwen':'', 'NVILA-ST':(4,2)},
# marker='o', linewidth=2.5, markersize=8)
# if not df_robo.empty:
# robo_ent = df_robo['Entanglement'].values[0]
# plt.axhline(y=robo_ent, color=colors['RoboRefer'], linestyle='--', label=f'RoboRefer ({robo_ent:.4f})')
# plt.title('Figure 2: The Entanglement Paradox during Naive Scaling', fontsize=14, fontweight='bold')
# plt.ylabel('Entanglement', fontsize=12)
# plt.xlabel('Fine-tuning Data Scale', fontsize=12)
# plt.legend(title='Models', bbox_to_anchor=(1.05, 1), loc='upper left')
# plt.tight_layout()
# plt.savefig(os.path.join(output_dir, 'figure2_entanglement_paradox.png'), dpi=300)
# plt.close()
# # -----------------------------------------------------------------------------
# # Figure 4: Behavioral Consequence - The Gap (Grouped Bar Chart)
# # -----------------------------------------------------------------------------
# df_acc = df.dropna(subset=['EmbSpatial Acc (con)', 'EmbSpatial Acc (ctr)']).copy()
# available_acc_models = df_acc['Model'].tolist()
# fig_width = max(12, len(available_acc_models) * 0.7)
# x = np.arange(len(available_acc_models))
# width = 0.35
# fig, ax = plt.subplots(figsize=(fig_width, 6))
# rects1 = ax.bar(x - width/2, df_acc['EmbSpatial Acc (con)'], width, label='Consistent (Shortcut Works)', color='#2b83ba')
# rects2 = ax.bar(x + width/2, df_acc['EmbSpatial Acc (ctr)'], width, label='Counter (Shortcut Fails)', color='#d7191c')
# for i in range(len(available_acc_models)):
# con_val = df_acc['EmbSpatial Acc (con)'].iloc[i]
# ctr_val = df_acc['EmbSpatial Acc (ctr)'].iloc[i]
# gap = con_val - ctr_val
# ax.plot([i - width/2, i + width/2], [con_val, ctr_val], color='black', linestyle='-', linewidth=1.5, alpha=0.5)
# ax.text(i, max(con_val, ctr_val) + 2, f'Gap: {gap:.1f}%p', ha='center', fontsize=9, fontweight='bold')
# ax.set_ylabel('Accuracy (%)', fontsize=12)
# ax.set_title('Figure 4: The Consistent vs. Counter Performance Gap (All Valid Models)', fontsize=14, fontweight='bold')
# ax.set_xticks(x)
# ax.set_xticklabels(available_acc_models, rotation=45, ha='right')
# ax.legend()
# plt.tight_layout()
# plt.savefig(os.path.join(output_dir, 'figure4_accuracy_gap.png'), dpi=300)
# plt.close()
# # -----------------------------------------------------------------------------
# # Figure 5: Distance Consistency vs Counter Accuracy
# # -----------------------------------------------------------------------------
# plt.figure(figsize=(10, 8))
# df_valid_acc = df.dropna(subset=['EmbSpatial Acc (ctr)', 'Peak Dist'])
# df_bases_fig5 = df_valid_acc[df_valid_acc['Base'] != 'RoboRefer']
# sns.scatterplot(data=df_bases_fig5, x='Peak Dist', y='EmbSpatial Acc (ctr)', hue='Base', palette=colors, s=150, edgecolor='black', alpha=0.8, legend=False)
# for base in ['Molmo', 'NVILA', 'Qwen', 'NVILA-ST']:
# current_order = st_scale_order if base == 'NVILA-ST' else scale_order
# base_df = df_valid_acc[(df_valid_acc['Base'] == base) & (df_valid_acc['Scale'].isin(current_order))]
# base_df = base_df.drop_duplicates(subset=['Scale']).set_index('Scale').reindex(current_order).dropna(subset=['Peak Dist', 'EmbSpatial Acc (ctr)'])
# if len(base_df) > 1:
# for i in range(len(base_df)-1):
# x1, y1 = base_df.iloc[i]['Peak Dist'], base_df.iloc[i]['EmbSpatial Acc (ctr)']
# x2, y2 = base_df.iloc[i+1]['Peak Dist'], base_df.iloc[i+1]['EmbSpatial Acc (ctr)']
# ls = '--' if base == 'NVILA-ST' else '-'
# plt.annotate('', xy=(x2, y2), xytext=(x1, y1),
# arrowprops=dict(arrowstyle="->", color=colors[base], alpha=0.6, lw=1.8, ls=ls))
# df_robo_fig5 = df_valid_acc[df_valid_acc['Base'] == 'RoboRefer']
# if not df_robo_fig5.empty:
# sns.scatterplot(data=df_robo_fig5, x='Peak Dist', y='EmbSpatial Acc (ctr)', hue='Base',
# palette=colors, s=400, marker='*', edgecolor='black', zorder=5, legend=False)
# if len(df_valid_acc) > 1:
# corr = np.corrcoef(df_valid_acc['Peak Dist'], df_valid_acc['EmbSpatial Acc (ctr)'])[0, 1]
# plt.text(0.05, 0.95, f"Pearson r = {corr:.2f}", transform=plt.gca().transAxes,
# fontsize=14, fontweight='bold', bbox=dict(facecolor='white', alpha=0.8, edgecolor='gray'))
# plt.legend(handles=custom_lines, title='Model Group', loc='lower right')
# plt.title('Figure 5: Distance SC is the strongest predictor of Counter Accuracy', fontsize=14, fontweight='bold')
# plt.xlabel('Distance Sign-Corrected Consistency (Peak Dist)', fontsize=12)
# plt.ylabel('EmbSpatial Counter Accuracy (%)', fontsize=12)
# plt.grid(True, linestyle='--', alpha=0.7)
# plt.tight_layout()
# plt.savefig(os.path.join(output_dir, 'figure5_distSC_vs_counterAcc.png'), dpi=300)
# plt.close()
# # -----------------------------------------------------------------------------
# # Figure 6: 3D Scatter (Peak Dist, Counter Acc, Entanglement)
# # -----------------------------------------------------------------------------
# fig = plt.figure(figsize=(12, 10))
# ax = fig.add_subplot(111, projection='3d')
# for base_name in df_valid_acc['Base'].unique():
# subset = df_valid_acc[df_valid_acc['Base'] == base_name]
# c = colors.get(base_name, 'gray')
# if base_name == 'RoboRefer':
# ax.scatter(subset['Peak Dist'], subset['Entanglement'], subset['EmbSpatial Acc (ctr)'],
# c=c, s=300, marker='*', edgecolors='k', alpha=0.9, zorder=5)
# else:
# ax.scatter(subset['Peak Dist'], subset['Entanglement'], subset['EmbSpatial Acc (ctr)'],
# c=c, s=120, edgecolors='k', alpha=0.8)
# for base in ['Molmo', 'NVILA', 'Qwen', 'NVILA-ST']:
# current_order = st_scale_order if base == 'NVILA-ST' else scale_order
# base_df = df_valid_acc[(df_valid_acc['Base'] == base) & (df_valid_acc['Scale'].isin(current_order))]
# base_df = base_df.drop_duplicates(subset=['Scale']).set_index('Scale').reindex(current_order).dropna(subset=['Peak Dist', 'Entanglement', 'EmbSpatial Acc (ctr)'])
# if len(base_df) > 1:
# for i in range(len(base_df)-1):
# x1, y1, z1 = base_df.iloc[i]['Peak Dist'], base_df.iloc[i]['Entanglement'], base_df.iloc[i]['EmbSpatial Acc (ctr)']
# x2, y2, z2 = base_df.iloc[i+1]['Peak Dist'], base_df.iloc[i+1]['Entanglement'], base_df.iloc[i+1]['EmbSpatial Acc (ctr)']
# ls = '--' if base == 'NVILA-ST' else '-'
# ax.plot([x1, x2], [y1, y2], [z1, z2], color=colors[base], linestyle=ls, linewidth=2.5, alpha=0.7)
# ax.set_xlabel('Peak Dist SC', labelpad=10, fontsize=11)
# ax.set_ylabel('Entanglement', labelpad=10, fontsize=11)
# ax.set_zlabel('Counter Accuracy (%)', labelpad=10, fontsize=11)
# ax.set_title('Figure 6: Navigating the Representation Space\n(Dist SC vs. Entanglement vs. Counter Acc)', fontweight='bold', fontsize=14)
# ax.view_init(elev=20, azim=135)
# plt.legend(handles=custom_lines, title='Model Group', loc='upper left', bbox_to_anchor=(1.05, 1))
# plt.tight_layout()
# plt.savefig(os.path.join(output_dir, 'figure6_3d_distSC_ent_counterAcc.png'), dpi=300, bbox_inches='tight')
# plt.close()
# print(f"Success! Evaluation figures have been saved to ./{output_dir}/")
# if __name__ == "__main__":
# main()
# import os
# import pandas as pd
# import numpy as np
# import matplotlib.pyplot as plt
# import seaborn as sns
# from io import StringIO
# import matplotlib.patches as patches
# # 1. Input data
# data = """Model,Peak Horiz,Peak Vert,Peak Dist,Peak cos(dv dd),Last cos(dv dd),EmbSpatial Acc (con),EmbSpatial Acc (ctr),CVBench3D Acc (con),CVBench3D Acc (ctr)
# Molmo vanilla,0.1427,0.2279,0.0749,0.3486,0.2367,63.5%,34.9%,93.1%,75.4%
# Molmo 80k,0.1224,0.3317,0.0718,0.5760,0.4397,60.6%,29.5%,80.2%,56.9%
# Molmo 400k,0.2355,0.5971,0.0961,0.7113,0.6151,62.7%,27.1%,89.5%,56.9%
# Molmo 800k,0.2468,0.5586,0.1073,0.8009,0.6150,65.2%,34.1%,88.7%,70.8%
# Molmo 2M,0.2390,0.5743,0.1122,0.7986,0.6543,65.3%,39.5%,90.6%,72.3%
# NVILA vanilla,0.3232,0.2890,0.0521,0.5609,0.2887,49.0%,27.1%,74.4%,40.0%
# RoboRefer,0.6490,0.8302,0.1824,0.5725,0.1117,87.0%,59.7%,98.9%,95.4%
# NVILA 80k,0.2946,0.4967,0.0701,0.7094,0.4125,57.7%,15.5%,71.6%,50.8%
# NVILA 400k,0.2415,0.5741,0.0949,0.8056,0.4197,61.1%,34.1%,81.3%,58.5%
# NVILA 800k,0.2779,0.4984,0.0885,0.8377,0.4133,63.2%,38.8%,84.6%,67.7%
# NVILA 2M,0.2409,0.5531,0.1039,0.8371,0.4267,60.7%,41.1%,97.2%,93.8%
# Qwen vanilla,0.3674,0.2925,0.0428,0.5047,0.2043,54.7%,32.6%,75.5%,55.4%
# Qwen 80k,0.3862,0.3148,0.0404,0.4553,0.1897,50.6%,30.2%,69.7%,60.0%
# Qwen 400k,0.4496,0.4522,0.0418,0.5112,0.2041,52.6%,27.1%,65.8%,58.5%
# Qwen 800k,0.4730,0.5376,0.0454,0.5429,0.2177,55.8%,26.4%,61.2%,58.5%
# Qwen 2M,0.4845,0.5858,0.0519,0.6049,0.2426,60.9%,24.0%,62.0%,53.8%
# Qwen3 235b,0.6610,0.6187,0.2285,0.5126,0.1783,N/A,N/A,N/A,N/A"""
# # Preprocessing
# df = pd.read_csv(StringIO(data))
# cols_to_convert = ['EmbSpatial Acc (con)', 'EmbSpatial Acc (ctr)', 'CVBench3D Acc (con)', 'CVBench3D Acc (ctr)']
# for col in cols_to_convert:
# df[col] = df[col].astype(str).str.replace('%', '').replace('N/A', np.nan).astype(float)
# # Add group and scale labels
# def get_base(name):
# if 'Molmo' in name: return 'Molmo'
# if 'NVILA' in name: return 'NVILA'
# if 'Qwen3' in name: return 'Genuine (Qwen3)'
# if 'Qwen' in name: return 'Qwen'
# if 'RoboRefer' in name: return 'Genuine (RoboRefer)'
# return 'Other'
# def get_scale(name):
# for s in ['vanilla', '80k', '400k', '800k', '2M']:
# if s in name: return s
# return 'Special'
# df['Base'] = df['Model'].apply(get_base)
# df['Scale'] = df['Model'].apply(get_scale)
# # Output directory
# output_dir = "evaluation_figures_v2"
# os.makedirs(output_dir, exist_ok=True)
# sns.set_theme(style="whitegrid")
# # -----------------------------------------------------------------------------
# # Figure 1: The Two Paths (Scatter with Trajectories)
# # -----------------------------------------------------------------------------
# plt.figure(figsize=(10, 8))
# # Define colors
# colors = {'Molmo': '#1f77b4', 'NVILA': '#ff7f0e', 'Qwen': '#2ca02c',
# 'Genuine (RoboRefer)': '#d62728', 'Genuine (Qwen3)': '#9467bd'}
# # Plot naive scaling models (with smaller dots)
# df_naive = df[df['Scale'] != 'Special']
# sns.scatterplot(data=df_naive, x='Last cos(dv dd)', y='Peak Dist', hue='Base', palette=colors, s=80, alpha=0.7)
# # Draw arrows to show trajectories (vanilla -> 2M)
# scale_order = ['vanilla', '80k', '400k', '800k', '2M']
# for base in ['Molmo', 'NVILA', 'Qwen']:
# base_df = df_naive[df_naive['Base'] == base].set_index('Scale').loc[scale_order]
# for i in range(len(scale_order)-1):
# x1, y1 = base_df.iloc[i]['Last cos(dv dd)'], base_df.iloc[i]['Peak Dist']
# x2, y2 = base_df.iloc[i+1]['Last cos(dv dd)'], base_df.iloc[i+1]['Peak Dist']
# plt.annotate('', xy=(x2, y2), xytext=(x1, y1),
# arrowprops=dict(arrowstyle="->", color=colors[base], alpha=0.5, lw=1.5))
# # Plot Genuine models (with big stars)
# df_genuine = df[df['Scale'] == 'Special']
# sns.scatterplot(data=df_genuine, x='Last cos(dv dd)', y='Peak Dist', hue='Base',
# palette=colors, s=400, marker='*', edgecolor='black', zorder=5)
# plt.title('Figure 1: The Two Paths of Spatial Representation\n(Naive Scaling vs. Genuine Understanding)', fontsize=14, fontweight='bold')
# plt.xlabel('Entanglement Shortcut: Last Layer cos(dv, dd) [Lower is Better]', fontsize=12)
# plt.ylabel('Distance Representation: Peak Dist [Higher is Better]', fontsize=12)
# # Add text annotations for clarity
# plt.text(0.6, 0.05, "Mechanism 1:\nNaive Scaling\n(More Data = More Entanglement)",
# fontsize=12, bbox=dict(facecolor='white', alpha=0.8, edgecolor='gray'))
# plt.text(0.1, 0.20, "Mechanism 2:\nGenuine Understanding\n(Break the Shortcut)",
# fontsize=12, bbox=dict(facecolor='white', alpha=0.8, edgecolor='gray'))
# plt.legend(title='Model Group')
# plt.tight_layout()
# plt.savefig(os.path.join(output_dir, 'figure1_two_paths_trajectory.png'), dpi=300)
# plt.close()
# # -----------------------------------------------------------------------------
# # Figure 2: Entanglement Paradox (Line Plot)
# # -----------------------------------------------------------------------------
# df_scale = df[df['Scale'] != 'Special'].copy()
# df_scale['Scale'] = pd.Categorical(df_scale['Scale'], categories=scale_order, ordered=True)
# plt.figure(figsize=(10, 6))
# sns.lineplot(data=df_scale, x='Scale', y='Last cos(dv dd)', hue='Base', marker='o', linewidth=2.5, markersize=8)
# # Add baselines for Genuine Models
# robo_ent = df[df['Model'] == 'RoboRefer']['Last cos(dv dd)'].values[0]
# qwen3_ent = df[df['Model'] == 'Qwen3 235b']['Last cos(dv dd)'].values[0]
# plt.axhline(y=qwen3_ent, color=colors['Genuine (Qwen3)'], linestyle='--', label=f'Qwen3 235b ({qwen3_ent:.4f})')
# plt.axhline(y=robo_ent, color=colors['Genuine (RoboRefer)'], linestyle='--', label=f'RoboRefer ({robo_ent:.4f})')
# plt.title('Figure 2: The Entanglement Paradox during Naive Scaling', fontsize=14, fontweight='bold')
# plt.ylabel('Entanglement (Last Layer cos(dv, dd))', fontsize=12)
# plt.xlabel('Fine-tuning Data Scale', fontsize=12)
# plt.legend(title='Models', bbox_to_anchor=(1.05, 1), loc='upper left')
# plt.tight_layout()
# plt.savefig(os.path.join(output_dir, 'figure2_entanglement_paradox.png'), dpi=300)
# plt.close()
# # -----------------------------------------------------------------------------
# # Figure 3: Depth Independence Ratio (Bar Chart)
# # -----------------------------------------------------------------------------
# # Calculate ratio: Peak Dist / Peak Vert
# df['Depth Independence Ratio'] = df['Peak Dist'] / df['Peak Vert']
# # Select representative models
# rep_models = ['Molmo vanilla', 'Molmo 2M', 'NVILA vanilla', 'NVILA 2M', 'Qwen vanilla', 'Qwen 2M', 'RoboRefer', 'Qwen3 235b']
# df_rep = df.set_index('Model').loc[rep_models]
# plt.figure(figsize=(12, 6))
# # Color scheme: Naive (blue/orange/green) vs Genuine (Red/Purple)
# bar_colors = ['#aec7e8', '#1f77b4', '#ffbb78', '#ff7f0e', '#98df8a', '#2ca02c', '#d62728', '#9467bd']
# ax = df_rep['Depth Independence Ratio'].plot(kind='bar', color=bar_colors, edgecolor='black')
# plt.title('Figure 3: Depth Independence Ratio (Peak Dist / Peak Vert)', fontsize=14, fontweight='bold')
# plt.ylabel('Ratio (Higher = Less dependent on vertical shortcut)', fontsize=12)
# plt.xticks(rotation=45, ha='right')
# # Add horizontal line to show the "Genuine" threshold
# plt.axhline(y=0.2, color='gray', linestyle=':', alpha=0.7)
# plt.text(-0.5, 0.22, "Genuine Understanding Threshold", color='gray', fontstyle='italic')
# plt.tight_layout()
# plt.savefig(os.path.join(output_dir, 'figure3_depth_independence_ratio.png'), dpi=300)
# plt.close()
# # -----------------------------------------------------------------------------
# # Figure 4: Behavioral Consequence - The Gap (Grouped Bar Chart)
# # -----------------------------------------------------------------------------
# acc_models = ['Molmo vanilla', 'Molmo 2M', 'NVILA vanilla', 'NVILA 2M', 'Qwen vanilla', 'Qwen 2M', 'RoboRefer']
# df_acc = df.set_index('Model').loc[acc_models]
# # We focus on EmbSpatial as it clearly shows the counter gap
# x = np.arange(len(acc_models))
# width = 0.35
# fig, ax = plt.subplots(figsize=(12, 6))
# rects1 = ax.bar(x - width/2, df_acc['EmbSpatial Acc (con)'], width, label='Consistent (Shortcut Works)', color='#2b83ba')
# rects2 = ax.bar(x + width/2, df_acc['EmbSpatial Acc (ctr)'], width, label='Counter (Shortcut Fails)', color='#d7191c')
# # Draw gap lines
# for i in range(len(acc_models)):
# con_val = df_acc['EmbSpatial Acc (con)'].iloc[i]
# ctr_val = df_acc['EmbSpatial Acc (ctr)'].iloc[i]
# gap = con_val - ctr_val
# # Plot an error bar-like line connecting the two tops
# ax.plot([i - width/2, i + width/2], [con_val, ctr_val], color='black', linestyle='-', linewidth=1.5, alpha=0.5)
# ax.text(i, max(con_val, ctr_val) + 2, f'Gap: {gap:.1f}%p', ha='center', fontsize=9, fontweight='bold')
# ax.set_ylabel('Accuracy (%)', fontsize=12)
# ax.set_title('Figure 4: The Consistent vs. Counter Performance Gap', fontsize=14, fontweight='bold')
# ax.set_xticks(x)
# ax.set_xticklabels(acc_models, rotation=45, ha='right')
# ax.legend()
# plt.tight_layout()
# plt.savefig(os.path.join(output_dir, 'figure4_accuracy_gap.png'), dpi=300)
# plt.close()
# print(f"Success! 4 figures supporting 'Naive Scaling vs Genuine Understanding' have been saved to ./{output_dir}/")
# import os
# import pandas as pd
# import numpy as np
# import matplotlib.pyplot as plt
# import seaborn as sns
# from io import StringIO
# import matplotlib.patches as patches
# # 1. Input data (Updated with new Entanglement values)
# data = """Model,Peak Horiz,Peak Vert,Peak Dist,Entanglement Layer,Entanglement,EmbSpatial Acc (con),EmbSpatial Acc (ctr),CVBench3D Acc (con),CVBench3D Acc (ctr)
# Molmo vanilla,0.1427,0.2279,0.0749,23,0.2791,63.5%,34.9%,93.1%,75.4%
# Molmo 80k,0.1224,0.3317,0.0718,23,0.3879,60.6%,29.5%,80.2%,56.9%
# Molmo 400k,0.2355,0.5971,0.0961,23,0.4586,62.7%,27.1%,89.5%,56.9%
# Molmo 800k,0.2468,0.5586,0.1073,23,0.5142,65.2%,34.1%,88.7%,70.8%
# Molmo 2M,0.2390,0.5743,0.1122,23,0.4744,65.3%,39.5%,90.6%,72.3%
# NVILA vanilla,0.3232,0.2890,0.0521,20,0.5387,15.3%,7.8%,74.4%,40.0%
# RoboRefer,0.6490,0.8302,0.1824,20,0.3619,87.0%,59.7%,98.9%,95.4%
# NVILA 80k,0.2946,0.4967,0.0701,20,0.6061,57.7%,15.5%,71.6%,50.8%
# NVILA 400k,0.2415,0.5741,0.0949,20,0.5889,61.1%,34.1%,81.3%,58.5%
# NVILA 800k,0.2779,0.4984,0.0885,20,0.5914,63.2%,38.8%,84.6%,67.7%
# NVILA 2M,0.2409,0.5531,0.1039,20,0.5501,60.7%,41.1%,97.2%,93.8%
# NVILA 10pct,0.4141,0.8469,0.1106,20,0.6028,N/A,N/A,N/A,N/A
# NVILA 20pct,0.4329,0.8179,0.0881,20,0.6871,N/A,N/A,N/A,N/A
# NVILA 30pct,0.4687,0.7497,0.0670,20,0.6669,N/A,N/A,N/A,N/A
# Qwen vanilla,0.3674,0.2925,0.0428,27,0.4568,54.7%,32.6%,75.5%,55.4%
# Qwen 80k,0.3862,0.3148,0.0404,27,0.4563,50.6%,30.2%,69.7%,60.0%
# Qwen 400k,0.4496,0.4522,0.0418,27,0.4514,52.6%,27.1%,65.8%,58.5%
# Qwen 800k,0.4730,0.5376,0.0454,27,0.4287,55.8%,26.4%,61.2%,58.5%
# Qwen 2M,0.4845,0.5858,0.0519,27,0.4720,60.9%,24.0%,62.0%,53.8%
# Qwen3-235B,0.6610,0.6187,0.2285,87,0.1169,70.5%,39.5%,N/A,N/A"""
# # Preprocessing
# df = pd.read_csv(StringIO(data))
# cols_to_convert = ['EmbSpatial Acc (con)', 'EmbSpatial Acc (ctr)', 'CVBench3D Acc (con)', 'CVBench3D Acc (ctr)']
# for col in cols_to_convert:
# df[col] = df[col].astype(str).str.replace('%', '').replace('N/A', np.nan).astype(float)
# # Add group and scale labels
# def get_base(name):
# if 'Molmo' in name: return 'Molmo'
# if 'NVILA' in name: return 'NVILA'
# if 'Qwen3' in name: return 'Qwen3' # Genuine 텍스트 제거
# if 'Qwen' in name: return 'Qwen'
# if 'RoboRefer' in name: return 'RoboRefer' # Genuine 텍스트 제거
# return 'Other'
# def get_scale(name):
# for s in ['vanilla', '80k', '400k', '800k', '2M']:
# if s in name: return s
# return 'Special'
# df['Base'] = df['Model'].apply(get_base)
# df['Scale'] = df['Model'].apply(get_scale)
# # Output directory
# output_dir = "evaluation_figures_v2_updated"
# os.makedirs(output_dir, exist_ok=True)
# sns.set_theme(style="whitegrid")
# # -----------------------------------------------------------------------------
# # Figure 1: The Two Paths (Scatter with Trajectories)
# # -----------------------------------------------------------------------------
# plt.figure(figsize=(10, 8))
# # Define colors
# colors = {'Molmo': '#1f77b4', 'NVILA': '#ff7f0e', 'Qwen': '#2ca02c',
# 'RoboRefer': '#d62728', 'Qwen3': '#9467bd'} # Genuine 키 수정
# # Plot naive scaling models (with smaller dots)
# df_naive = df[df['Scale'] != 'Special']
# sns.scatterplot(data=df_naive, x='Entanglement', y='Peak Dist', hue='Base', palette=colors, s=80, alpha=0.7)
# # Draw arrows to show trajectories (vanilla -> 2M)
# scale_order = ['vanilla', '80k', '400k', '800k', '2M']
# for base in ['Molmo', 'NVILA', 'Qwen']:
# base_df = df_naive[df_naive['Base'] == base].set_index('Scale').loc[scale_order]
# for i in range(len(scale_order)-1):
# x1, y1 = base_df.iloc[i]['Entanglement'], base_df.iloc[i]['Peak Dist']
# x2, y2 = base_df.iloc[i+1]['Entanglement'], base_df.iloc[i+1]['Peak Dist']
# plt.annotate('', xy=(x2, y2), xytext=(x1, y1),
# arrowprops=dict(arrowstyle="->", color=colors[base], alpha=0.5, lw=1.5))
# # Plot RoboRefer and Qwen3 models (with big stars) - NVILA 제외
# df_genuine = df[df['Scale'] == 'Special']
# df_genuine_filtered = df_genuine[df_genuine['Base'] != 'NVILA'] # NVILA Special 모델 제외
# sns.scatterplot(data=df_genuine_filtered, x='Entanglement', y='Peak Dist', hue='Base',
# palette=colors, s=400, marker='*', edgecolor='black', zorder=5)
# plt.title('Figure 1: The Two Paths of Spatial Representation\n(Naive Scaling vs. Genuine Understanding)', fontsize=14, fontweight='bold')
# plt.xlabel('Entanglement Shortcut [Lower is Better]', fontsize=12)
# plt.ylabel('Distance Representation: Peak Dist [Higher is Better]', fontsize=12)
# # Add text annotations for clarity
# plt.text(0.6, 0.05, "Mechanism 1:\nNaive Scaling\n(More Data = More Entanglement)",
# fontsize=12, bbox=dict(facecolor='white', alpha=0.8, edgecolor='gray'))
# plt.text(0.1, 0.20, "Mechanism 2:\nGenuine Understanding\n(Break the Shortcut)",
# fontsize=12, bbox=dict(facecolor='white', alpha=0.8, edgecolor='gray'))
# plt.legend(title='Model Group')
# plt.tight_layout()
# plt.savefig(os.path.join(output_dir, 'figure1_two_paths_trajectory_updated.png'), dpi=300)
# plt.close()
# # -----------------------------------------------------------------------------
# # Figure 2: Entanglement Paradox (Line Plot)
# # -----------------------------------------------------------------------------
# df_scale = df[df['Scale'] != 'Special'].copy()
# df_scale['Scale'] = pd.Categorical(df_scale['Scale'], categories=scale_order, ordered=True)
# plt.figure(figsize=(10, 6))
# sns.lineplot(data=df_scale, x='Scale', y='Entanglement', hue='Base', marker='o', linewidth=2.5, markersize=8)
# # Add baselines for Genuine Models
# robo_ent = df[df['Model'] == 'RoboRefer']['Entanglement'].values[0]
# qwen3_ent = df[df['Model'] == 'Qwen3-235B']['Entanglement'].values[0]
# plt.axhline(y=qwen3_ent, color=colors['Qwen3'], linestyle='--', label=f'Qwen3-235B ({qwen3_ent:.4f})')
# plt.axhline(y=robo_ent, color=colors['RoboRefer'], linestyle='--', label=f'RoboRefer ({robo_ent:.4f})')
# plt.title('Figure 2: The Entanglement Paradox during Naive Scaling', fontsize=14, fontweight='bold')
# plt.ylabel('Entanglement', fontsize=12)
# plt.xlabel('Fine-tuning Data Scale', fontsize=12)
# plt.legend(title='Models', bbox_to_anchor=(1.05, 1), loc='upper left')
# plt.tight_layout()
# plt.savefig(os.path.join(output_dir, 'figure2_entanglement_paradox_updated.png'), dpi=300)
# plt.close()
# # -----------------------------------------------------------------------------
# # Figure 3: Depth Independence Ratio (Bar Chart)
# # -----------------------------------------------------------------------------
# # Calculate ratio: Peak Dist / Peak Vert
# df['Depth Independence Ratio'] = df['Peak Dist'] / df['Peak Vert']
# # Select representative models
# rep_models = ['Molmo vanilla', 'Molmo 2M', 'NVILA vanilla', 'NVILA 2M', 'Qwen vanilla', 'Qwen 2M', 'RoboRefer', 'Qwen3-235B']
# df_rep = df.set_index('Model').loc[rep_models]
# plt.figure(figsize=(12, 6))
# # Color scheme: Naive (blue/orange/green) vs Genuine (Red/Purple)
# bar_colors = ['#aec7e8', '#1f77b4', '#ffbb78', '#ff7f0e', '#98df8a', '#2ca02c', '#d62728', '#9467bd']
# ax = df_rep['Depth Independence Ratio'].plot(kind='bar', color=bar_colors, edgecolor='black')
# plt.title('Figure 3: Depth Independence Ratio (Peak Dist / Peak Vert)', fontsize=14, fontweight='bold')
# plt.ylabel('Ratio (Higher = Less dependent on vertical shortcut)', fontsize=12)
# plt.xticks(rotation=45, ha='right')
# # Add horizontal line to show the "Genuine" threshold
# plt.axhline(y=0.2, color='gray', linestyle=':', alpha=0.7)
# plt.text(-0.5, 0.22, "Genuine Understanding Threshold", color='gray', fontstyle='italic')
# plt.tight_layout()
# plt.savefig(os.path.join(output_dir, 'figure3_depth_independence_ratio_updated.png'), dpi=300)
# plt.close()
# # -----------------------------------------------------------------------------
# # Figure 4: Behavioral Consequence - The Gap (Grouped Bar Chart)
# # -----------------------------------------------------------------------------
# acc_models = ['Molmo vanilla', 'Molmo 2M', 'NVILA vanilla', 'NVILA 2M', 'Qwen vanilla', 'Qwen 2M', 'RoboRefer', 'Qwen3-235B'] # Qwen3 추가
# df_acc = df.set_index('Model').loc[acc_models]
# # We focus on EmbSpatial as it clearly shows the counter gap
# x = np.arange(len(acc_models))
# width = 0.35
# fig, ax = plt.subplots(figsize=(12, 6))
# rects1 = ax.bar(x - width/2, df_acc['EmbSpatial Acc (con)'], width, label='Consistent (Shortcut Works)', color='#2b83ba')
# rects2 = ax.bar(x + width/2, df_acc['EmbSpatial Acc (ctr)'], width, label='Counter (Shortcut Fails)', color='#d7191c')
# # Draw gap lines
# for i in range(len(acc_models)):
# con_val = df_acc['EmbSpatial Acc (con)'].iloc[i]
# ctr_val = df_acc['EmbSpatial Acc (ctr)'].iloc[i]
# gap = con_val - ctr_val
# # Plot an error bar-like line connecting the two tops
# ax.plot([i - width/2, i + width/2], [con_val, ctr_val], color='black', linestyle='-', linewidth=1.5, alpha=0.5)
# ax.text(i, max(con_val, ctr_val) + 2, f'Gap: {gap:.1f}%p', ha='center', fontsize=9, fontweight='bold')
# ax.set_ylabel('Accuracy (%)', fontsize=12)
# ax.set_title('Figure 4: The Consistent vs. Counter Performance Gap', fontsize=14, fontweight='bold')
# ax.set_xticks(x)
# ax.set_xticklabels(acc_models, rotation=45, ha='right')
# ax.legend()
# plt.tight_layout()
# plt.savefig(os.path.join(output_dir, 'figure4_accuracy_gap_updated.png'), dpi=300)
# plt.close()
# print(f"Success! 4 figures with requested updates have been saved to ./{output_dir}/")
# import os
# import pandas as pd
# import numpy as np
# import matplotlib.pyplot as plt
# import seaborn as sns
# from io import StringIO
# from matplotlib.lines import Line2D
# # 1. Input data
# data = """Model,Peak Horiz,Peak Vert,Peak Dist,Entanglement Layer,Entanglement,EmbSpatial Acc (con),EmbSpatial Acc (ctr),CVBench3D Acc (con),CVBench3D Acc (ctr)
# Molmo vanilla,0.1427,0.2279,0.0749,23,0.2791,63.5%,34.9%,93.1%,75.4%
# Molmo 80k,0.1224,0.3317,0.0718,23,0.3879,60.6%,29.5%,80.2%,56.9%
# Molmo 400k,0.2355,0.5971,0.0961,23,0.4586,62.7%,27.1%,89.5%,56.9%
# Molmo 800k,0.2468,0.5586,0.1073,23,0.5142,65.2%,34.1%,88.7%,70.8%
# Molmo 2M,0.2390,0.5743,0.1122,23,0.4744,65.3%,39.5%,90.6%,72.3%
# NVILA vanilla,0.3232,0.2890,0.0521,20,0.5387,15.3%,7.8%,74.4%,40.0%
# RoboRefer,0.6490,0.8302,0.1824,20,0.3619,87.0%,59.7%,98.9%,95.4%
# NVILA 80k,0.2946,0.4967,0.0701,20,0.6061,57.7%,15.5%,71.6%,50.8%
# NVILA 400k,0.2415,0.5741,0.0949,20,0.5889,61.1%,34.1%,81.3%,58.5%
# NVILA 800k,0.2779,0.4984,0.0885,20,0.5914,63.2%,38.8%,84.6%,67.7%
# NVILA 2M,0.2409,0.5531,0.1039,20,0.5501,60.7%,41.1%,97.2%,93.8%
# NVILA 10pct,0.4141,0.8469,0.1106,20,0.6028,N/A,N/A,N/A,N/A
# NVILA 20pct,0.4329,0.8179,0.0881,20,0.6871,N/A,N/A,N/A,N/A
# NVILA 30pct,0.4687,0.7497,0.0670,20,0.6669,N/A,N/A,N/A,N/A
# Qwen vanilla,0.3674,0.2925,0.0428,27,0.4568,54.7%,32.6%,75.5%,55.4%
# Qwen 80k,0.3862,0.3148,0.0404,27,0.4563,50.6%,30.2%,69.7%,60.0%
# Qwen 400k,0.4496,0.4522,0.0418,27,0.4514,52.6%,27.1%,65.8%,58.5%
# Qwen 800k,0.4730,0.5376,0.0454,27,0.4287,55.8%,26.4%,61.2%,58.5%
# Qwen 2M,0.4845,0.5858,0.0519,27,0.4720,60.9%,24.0%,62.0%,53.8%
# Qwen3-235B,0.6610,0.6187,0.2285,87,0.1169,70.5%,39.5%,N/A,N/A"""
# # Preprocessing
# df = pd.read_csv(StringIO(data))
# cols_to_convert = ['EmbSpatial Acc (con)', 'EmbSpatial Acc (ctr)', 'CVBench3D Acc (con)', 'CVBench3D Acc (ctr)']
# for col in cols_to_convert:
# df[col] = df[col].astype(str).str.replace('%', '').replace('N/A', np.nan).astype(float)
# # Add group and scale labels
# def get_base(name):
# if 'Molmo' in name: return 'Molmo'
# if 'NVILA' in name: return 'NVILA'
# if 'Qwen3' in name: return 'Qwen3'
# if 'Qwen' in name: return 'Qwen'
# if 'RoboRefer' in name: return 'RoboRefer'
# return 'Other'
# def get_scale(name):
# for s in ['vanilla', '80k', '400k', '800k', '2M']:
# if s in name: return s
# return 'Special'
# df['Base'] = df['Model'].apply(get_base)
# df['Scale'] = df['Model'].apply(get_scale)
# # Output directory
# output_dir = "evaluation_figures_v4"
# os.makedirs(output_dir, exist_ok=True)
# sns.set_theme(style="whitegrid")
# # Colors
# colors = {'Molmo': '#1f77b4', 'NVILA': '#ff7f0e', 'Qwen': '#2ca02c',
# 'RoboRefer': '#d62728', 'Qwen3': '#9467bd'}
# synth_color = '#cc5500' # 진한 주황색 (Darker Orange)
# # -----------------------------------------------------------------------------
# # Figure 1: The Two Paths (Scatter with Trajectories)
# # -----------------------------------------------------------------------------
# plt.figure(figsize=(10, 8))
# # 1. Plot naive scaling models
# df_naive = df[df['Scale'] != 'Special']
# sns.scatterplot(data=df_naive, x='Entanglement', y='Peak Dist', hue='Base', palette=colors, s=80, alpha=0.7, legend=False)
# # 2. Draw arrows for naive scaling
# scale_order = ['vanilla', '80k', '400k', '800k', '2M']
# for base in ['Molmo', 'NVILA', 'Qwen']:
# base_df = df_naive[df_naive['Base'] == base].set_index('Scale').loc[scale_order]
# for i in range(len(scale_order)-1):
# x1, y1 = base_df.iloc[i]['Entanglement'], base_df.iloc[i]['Peak Dist']
# x2, y2 = base_df.iloc[i+1]['Entanglement'], base_df.iloc[i+1]['Peak Dist']
# plt.annotate('', xy=(x2, y2), xytext=(x1, y1),
# arrowprops=dict(arrowstyle="->", color=colors[base], alpha=0.5, lw=1.5))
# # 3. Plot RoboRefer and Qwen3 (Stars)
# df_genuine = df[(df['Scale'] == 'Special') & (df['Base'] != 'NVILA')]
# sns.scatterplot(data=df_genuine, x='Entanglement', y='Peak Dist', hue='Base',
# palette=colors, s=400, marker='*', edgecolor='black', zorder=5, legend=False)
# # 4. Plot NVILA Synthetic Mix (Darker Orange Circles)
# df_synth = df[(df['Scale'] == 'Special') & (df['Base'] == 'NVILA')]
# plt.scatter(df_synth['Entanglement'], df_synth['Peak Dist'],
# color=synth_color, marker='o', s=130, edgecolor='black', zorder=4, label='_nolegend_')
# # Draw dashed arrows for Synthetic Mix trajectory (10 -> 20 -> 30)
# synth_order = ['NVILA 10pct', 'NVILA 20pct', 'NVILA 30pct']
# df_synth_sorted = df_synth.set_index('Model').loc[synth_order]
# for i in range(len(synth_order)-1):
# x1, y1 = df_synth_sorted.iloc[i]['Entanglement'], df_synth_sorted.iloc[i]['Peak Dist']
# x2, y2 = df_synth_sorted.iloc[i+1]['Entanglement'], df_synth_sorted.iloc[i+1]['Peak Dist']
# plt.annotate('', xy=(x2, y2), xytext=(x1, y1),
# arrowprops=dict(arrowstyle="->", color=synth_color, alpha=0.8, lw=1.5, ls='--'))
# # 5. Custom Legend
# custom_lines = [
# Line2D([0], [0], marker='o', color='w', markerfacecolor=colors['Molmo'], markersize=10, label='Molmo'),
# Line2D([0], [0], marker='o', color='w', markerfacecolor=colors['NVILA'], markersize=10, label='NVILA'),
# Line2D([0], [0], marker='o', color='w', markerfacecolor=synth_color, markeredgecolor='black', markersize=11, label='NVILA (Synthetic)'),
# Line2D([0], [0], marker='o', color='w', markerfacecolor=colors['Qwen'], markersize=10, label='Qwen'),
# Line2D([0], [0], marker='*', color='w', markerfacecolor=colors['RoboRefer'], markeredgecolor='black', markersize=18, label='RoboRefer'),
# Line2D([0], [0], marker='*', color='w', markerfacecolor=colors['Qwen3'], markeredgecolor='black', markersize=18, label='Qwen3')
# ]
# plt.legend(handles=custom_lines, title='Model Group', loc='upper right')
# plt.title('Figure 1: The Two Paths of Spatial Representation\n(Naive Scaling vs. Genuine Understanding)', fontsize=14, fontweight='bold')
# plt.xlabel('Entanglement Shortcut [Lower is Better]', fontsize=12)
# plt.ylabel('Distance Representation: Peak Dist [Higher is Better]', fontsize=12)
# plt.text(0.6, 0.05, "Mechanism 1:\nNaive Scaling\n(More Data = More Entanglement)",
# fontsize=12, bbox=dict(facecolor='white', alpha=0.8, edgecolor='gray'))
# plt.text(0.1, 0.20, "Mechanism 2:\nGenuine Understanding\n(Break the Shortcut)",
# fontsize=12, bbox=dict(facecolor='white', alpha=0.8, edgecolor='gray'))
# plt.tight_layout()
# plt.savefig(os.path.join(output_dir, 'figure1_two_paths_trajectory.png'), dpi=300)
# plt.close()
# # -----------------------------------------------------------------------------
# # Figure 2: Entanglement Paradox (Line Plot)
# # -----------------------------------------------------------------------------
# df_scale = df[df['Scale'] != 'Special'].copy()
# df_scale['Scale'] = pd.Categorical(df_scale['Scale'], categories=scale_order, ordered=True)
# plt.figure(figsize=(10, 6))
# sns.lineplot(data=df_scale, x='Scale', y='Entanglement', hue='Base', marker='o', linewidth=2.5, markersize=8)
# robo_ent = df[df['Model'] == 'RoboRefer']['Entanglement'].values[0]
# qwen3_ent = df[df['Model'] == 'Qwen3-235B']['Entanglement'].values[0]
# plt.axhline(y=qwen3_ent, color=colors['Qwen3'], linestyle='--', label=f'Qwen3-235B ({qwen3_ent:.4f})')
# plt.axhline(y=robo_ent, color=colors['RoboRefer'], linestyle='--', label=f'RoboRefer ({robo_ent:.4f})')
# plt.title('Figure 2: The Entanglement Paradox during Naive Scaling', fontsize=14, fontweight='bold')
# plt.ylabel('Entanglement', fontsize=12)
# plt.xlabel('Fine-tuning Data Scale', fontsize=12)
# plt.legend(title='Models', bbox_to_anchor=(1.05, 1), loc='upper left')
# plt.tight_layout()
# plt.savefig(os.path.join(output_dir, 'figure2_entanglement_paradox.png'), dpi=300)
# plt.close()
# # -----------------------------------------------------------------------------
# # Figure 3: Depth Independence Ratio (Bar Chart)
# # -----------------------------------------------------------------------------
# df['Depth Independence Ratio'] = df['Peak Dist'] / df['Peak Vert']
# rep_models = ['Molmo vanilla', 'Molmo 2M', 'NVILA vanilla', 'NVILA 2M', 'Qwen vanilla', 'Qwen 2M', 'RoboRefer', 'Qwen3-235B']
# df_rep = df.set_index('Model').loc[rep_models]
# plt.figure(figsize=(12, 6))
# bar_colors = ['#aec7e8', '#1f77b4', '#ffbb78', '#ff7f0e', '#98df8a', '#2ca02c', '#d62728', '#9467bd']
# ax = df_rep['Depth Independence Ratio'].plot(kind='bar', color=bar_colors, edgecolor='black')
# plt.title('Figure 3: Depth Independence Ratio (Peak Dist / Peak Vert)', fontsize=14, fontweight='bold')
# plt.ylabel('Ratio (Higher = Less dependent on vertical shortcut)', fontsize=12)
# plt.xticks(rotation=45, ha='right')
# plt.axhline(y=0.2, color='gray', linestyle=':', alpha=0.7)
# plt.text(-0.5, 0.22, "Genuine Understanding Threshold", color='gray', fontstyle='italic')
# plt.tight_layout()
# plt.savefig(os.path.join(output_dir, 'figure3_depth_independence_ratio.png'), dpi=300)
# plt.close()
# # -----------------------------------------------------------------------------
# # Figure 4: Behavioral Consequence - The Gap (Grouped Bar Chart)
# # -----------------------------------------------------------------------------
# acc_models = ['Molmo vanilla', 'Molmo 2M', 'NVILA vanilla', 'NVILA 2M', 'Qwen vanilla', 'Qwen 2M', 'RoboRefer', 'Qwen3-235B']
# df_acc = df.set_index('Model').loc[acc_models]
# x = np.arange(len(acc_models))
# width = 0.35
# fig, ax = plt.subplots(figsize=(12, 6))
# rects1 = ax.bar(x - width/2, df_acc['EmbSpatial Acc (con)'], width, label='Consistent (Shortcut Works)', color='#2b83ba')
# rects2 = ax.bar(x + width/2, df_acc['EmbSpatial Acc (ctr)'], width, label='Counter (Shortcut Fails)', color='#d7191c')
# for i in range(len(acc_models)):
# con_val = df_acc['EmbSpatial Acc (con)'].iloc[i]
# ctr_val = df_acc['EmbSpatial Acc (ctr)'].iloc[i]
# if pd.isna(con_val) or pd.isna(ctr_val):
# continue
# gap = con_val - ctr_val
# ax.plot([i - width/2, i + width/2], [con_val, ctr_val], color='black', linestyle='-', linewidth=1.5, alpha=0.5)
# ax.text(i, max(con_val, ctr_val) + 2, f'Gap: {gap:.1f}%p', ha='center', fontsize=9, fontweight='bold')
# ax.set_ylabel('Accuracy (%)', fontsize=12)
# ax.set_title('Figure 4: The Consistent vs. Counter Performance Gap', fontsize=14, fontweight='bold')
# ax.set_xticks(x)
# ax.set_xticklabels(acc_models, rotation=45, ha='right')
# ax.legend()
# plt.tight_layout()
# plt.savefig(os.path.join(output_dir, 'figure4_accuracy_gap.png'), dpi=300)
# plt.close() |