File size: 15,292 Bytes
3404d44
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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)

SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
OUTPUT_DIR = os.path.join(SCRIPT_DIR, "summarize_metrics", "plots")

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'),
]


def load_and_preprocess(path: str) -> pd.DataFrame:
    df = pd.read_csv(path)

    df.rename(columns={
        'EmbSpatial (con)': 'EmbSpatial Acc (con)',
        'EmbSpatial (ctr)': 'EmbSpatial Acc (ctr)',
        'CVBench3D (con)':  'CVBench3D Acc (con)',
        'CVBench3D (ctr)':  'CVBench3D Acc (ctr)',
    }, inplace=True)

    for col in ['EmbSpatial Acc (con)', 'EmbSpatial Acc (ctr)',
                'CVBench3D Acc (con)',  'CVBench3D Acc (ctr)']:
        if col in df.columns:
            df[col] = (df[col].astype(str)
                               .str.replace('%', '', regex=False)
                               .replace('N/A', np.nan)
                               .astype(float))

    def get_base(name):
        if 'Molmo'   in name: return 'Molmo'
        if 'NVILA-ST'in name: return 'NVILA-ST'
        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)
    df = df[df['Base'] != 'Qwen3']
    return df


# ── helpers ──────────────────────────────────────────────────────────────────

def _draw_2d_arrows(df_src, base_list, x_col, y_col):
    """Draw annotate arrows for a 2-D figure."""
    for base in base_list:
        order = ST_SCALE_ORDER if base == 'NVILA-ST' else SCALE_ORDER
        base_df = (df_src[(df_src['Base'] == base) & (df_src['Scale'].isin(order))]
                   .set_index('Scale').reindex(order)
                   .dropna(subset=[x_col, y_col]))
        if len(base_df) < 2:
            continue
        ls = '--' if base == 'NVILA-ST' else '-'
        for i in range(len(base_df) - 1):
            x1, y1 = base_df.iloc[i][[x_col, y_col]]
            x2, y2 = base_df.iloc[i + 1][[x_col, y_col]]
            plt.annotate('', xy=(x2, y2), xytext=(x1, y1),
                         arrowprops=dict(arrowstyle="->", color=COLORS[base],
                                         alpha=0.6, lw=1.8, ls=ls))


def _draw_3d_arrows(ax, df_src, base_list, x_col, y_col, z_col):
    """Draw arrows in a 3-D axes using quiver + dashed line for NVILA-ST."""
    for base in base_list:
        order = ST_SCALE_ORDER if base == 'NVILA-ST' else SCALE_ORDER
        base_df = (df_src[(df_src['Base'] == base) & (df_src['Scale'].isin(order))]
                   .set_index('Scale').reindex(order)
                   .dropna(subset=[x_col, y_col, z_col]))
        if len(base_df) < 2:
            continue
        ls = '--' if base == 'NVILA-ST' else '-'
        for i in range(len(base_df) - 1):
            x1, y1, z1 = base_df.iloc[i][[x_col, y_col, z_col]]
            x2, y2, z2 = base_df.iloc[i + 1][[x_col, y_col, z_col]]
            dx, dy, dz = x2 - x1, y2 - y1, z2 - z1

            # Draw the shaft as a line (supports dashes for NVILA-ST)
            ax.plot([x1, x2], [y1, y2], [z1, z2],
                    color=COLORS[base], linestyle=ls, linewidth=2.0, alpha=0.6)

            # Draw an arrowhead at the end using quiver
            tip_frac = 0.25          # arrowhead covers 25 % of segment
            ax.quiver(x2 - tip_frac * dx,
                      y2 - tip_frac * dy,
                      z2 - tip_frac * dz,
                      tip_frac * dx, tip_frac * dy, tip_frac * dz,
                      color=COLORS[base], alpha=0.8,
                      arrow_length_ratio=1.0, linewidth=0)


# ── figures ──────────────────────────────────────────────────────────────────

def figure1(df: pd.DataFrame, outdir: str):
    """Figure 1: Two Paths of Spatial Representation (scatter + arrows)."""
    plt.figure(figsize=(10, 8))

    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)

    # Arrows for all non-RoboRefer groups including NVILA-ST
    _draw_2d_arrows(df, ['Molmo', 'NVILA', 'NVILA-ST', 'Qwen'],
                    'Entanglement', 'Peak Dist')

    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)

    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 (Dist SC) [Higher is Better]', fontsize=12)
    plt.text(0.60, 0.05,
             "Mechanism 1:\nNaive Scaling\n(More Data = More Entanglement)",
             fontsize=12, transform=plt.gca().transAxes,
             bbox=dict(facecolor='white', alpha=0.8, edgecolor='gray'))
    plt.text(0.02, 0.72,
             "Mechanism 2:\nGenuine Understanding\n(Break the Shortcut)",
             fontsize=12, transform=plt.gca().transAxes,
             bbox=dict(facecolor='white', alpha=0.8, edgecolor='gray'))
    plt.tight_layout()
    plt.savefig(os.path.join(outdir, 'figure1_two_paths_trajectory.png'), dpi=300)
    plt.close()


def figure2(df: pd.DataFrame, outdir: str):
    """Figure 2: Entanglement Paradox (line plot, NVILA-ST included)."""
    df_scale = df[df['Base'] != 'RoboRefer'].copy()
    df_scale = df_scale[df_scale['Scale'].isin(SCALE_ORDER)]
    df_scale['Scale'] = pd.Categorical(df_scale['Scale'],
                                        categories=SCALE_ORDER, ordered=True)

    plt.figure(figsize=(10, 6))

    # Separate NVILA-ST for manual plotting to support dashed style
    df_main = df_scale[df_scale['Base'] != 'NVILA-ST']
    df_st   = df_scale[df_scale['Base'] == 'NVILA-ST'].sort_values('Scale')

    sns.lineplot(data=df_main, x='Scale', y='Entanglement',
                 hue='Base', style='Base',
                 palette={k: v for k, v in COLORS.items() if k != 'NVILA-ST'},
                 marker='o', linewidth=2.5, markersize=8, legend='auto')

    # Overlay NVILA-ST as dashed line
    if not df_st.empty:
        ax = plt.gca()
        ax.plot(df_st['Scale'].cat.codes if hasattr(df_st['Scale'], 'cat') else
                [SCALE_ORDER.index(s) for s in df_st['Scale']],
                df_st['Entanglement'],
                color=COLORS['NVILA-ST'], linestyle='--', linewidth=2.5,
                marker='o', markersize=8, label='NVILA-ST')

    df_robo = df[df['Base'] == 'RoboRefer']
    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(outdir, 'figure2_entanglement_paradox.png'), dpi=300)
    plt.close()


def figure4(df: pd.DataFrame, outdir: str):
    """Figure 4: Consistent vs Counter Performance Gap (grouped bar)."""
    acc_models = [
        'Molmo vanilla', 'Molmo 2M',
        'NVILA vanilla',  'NVILA 2M',
        'NVILA-ST 80k',   'NVILA-ST 800k',
        'Qwen vanilla',   'Qwen 2M',
        'RoboRefer',
    ]
    available = [m for m in acc_models if m in df['Model'].values]
    df_acc = df.set_index('Model').loc[available]

    x     = np.arange(len(available))
    width = 0.35

    fig, ax = plt.subplots(figsize=(14, 6))
    ax.bar(x - width / 2, df_acc['EmbSpatial Acc (con)'], width,
           label='Consistent (Shortcut Works)', color='#2b83ba')
    ax.bar(x + width / 2, df_acc['EmbSpatial Acc (ctr)'], width,
           label='Counter (Shortcut Fails)',    color='#d7191c')

    for i in range(len(available)):
        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(available, rotation=45, ha='right')
    ax.legend()
    plt.tight_layout()
    plt.savefig(os.path.join(outdir, 'figure4_accuracy_gap.png'), dpi=300)
    plt.close()


def figure5(df: pd.DataFrame, outdir: str):
    """Figure 5: Peak Dist vs EmbSpatial Counter Accuracy (scatter + arrows).

    NVILA-ST has N/A accuracy in the default CSV; their points/arrows will
    appear automatically if the data file contains numeric values for them.
    """
    df_valid = df.dropna(subset=['EmbSpatial Acc (ctr)', 'Peak Dist'])

    plt.figure(figsize=(10, 8))

    df_bases = df_valid[df_valid['Base'] != 'RoboRefer']
    sns.scatterplot(data=df_bases, x='Peak Dist', y='EmbSpatial Acc (ctr)',
                    hue='Base', palette=COLORS, s=150,
                    edgecolor='black', alpha=0.8, legend=False)

    # Arrows for all groups including NVILA-ST
    _draw_2d_arrows(df_valid, ['Molmo', 'NVILA', 'NVILA-ST', 'Qwen'],
                    'Peak Dist', 'EmbSpatial Acc (ctr)')

    df_robo = df_valid[df_valid['Base'] == 'RoboRefer']
    if not df_robo.empty:
        sns.scatterplot(data=df_robo, x='Peak Dist', y='EmbSpatial Acc (ctr)',
                        hue='Base', palette=COLORS, s=400, marker='*',
                        edgecolor='black', zorder=5, legend=False)

    if len(df_valid) > 1:
        corr = np.corrcoef(df_valid['Peak Dist'], df_valid['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(outdir, 'figure5_distSC_vs_counterAcc.png'), dpi=300)
    plt.close()


def figure6(df: pd.DataFrame, outdir: str):
    """Figure 6: 3-D scatter (Peak Dist Γ— Entanglement Γ— Counter Acc) with arrows."""
    df_valid = df.dropna(subset=['EmbSpatial Acc (ctr)', 'Peak Dist'])

    fig = plt.figure(figsize=(12, 10))
    ax  = fig.add_subplot(111, projection='3d')

    for base_name in df_valid['Base'].unique():
        subset = df_valid[df_valid['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)

    # Arrows (shaft + quiver arrowhead) for trajectory
    _draw_3d_arrows(ax, df_valid,
                    ['Molmo', 'NVILA', 'NVILA-ST', 'Qwen'],
                    'Peak Dist', 'Entanglement', 'EmbSpatial Acc (ctr)')

    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(outdir, 'figure6_3d_distSC_ent_counterAcc.png'),
                dpi=300, bbox_inches='tight')
    plt.close()


# ── main ─────────────────────────────────────────────────────────────────────

def main():
    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()

    df = load_and_preprocess(args.data_path)

    os.makedirs(OUTPUT_DIR, exist_ok=True)
    sns.set_theme(style='whitegrid')

    figure1(df, OUTPUT_DIR)
    figure2(df, OUTPUT_DIR)
    figure4(df, OUTPUT_DIR)
    figure5(df, OUTPUT_DIR)
    figure6(df, OUTPUT_DIR)

    print(f"Saved figures to {OUTPUT_DIR}/")


if __name__ == '__main__':
    main()