File size: 12,201 Bytes
19898f1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
Post-hoc Analysis: cos(original, swapped) per sample

Loads saved vectors_{scale}.npz from exp2a_swap_analysis results,
computes cosine similarity between original and swapped embeddings per sample,
and reports category-level statistics.

This measures whether the model's representation actually changes when
obj1↔obj2 are swapped — the fundamental test of spatial relation encoding.

Usage:
    python compute_swap_cosine.py --model_type molmo
    python compute_swap_cosine.py --model_type molmo --results_dir /path/to/results
"""

import os
import json
import argparse
import numpy as np
import pandas as pd
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt

CATEGORY_ORDER = ['left', 'right', 'above', 'under', 'far', 'close']
GROUP_MAP = {
    'left': 'horizontal', 'right': 'horizontal',
    'above': 'vertical', 'under': 'vertical',
    'far': 'distance', 'close': 'distance',
}
GROUP_ORDER = ['horizontal', 'vertical', 'distance']

SCALE_COLORS = {
    'vanilla': '#1f77b4', '80k': '#ff7f0e', '400k': '#2ca02c',
    '800k': '#d62728', '2m': '#9467bd', 'roborefer': '#8c564b',
}


def cosine_sim_per_sample(orig: np.ndarray, swap: np.ndarray) -> np.ndarray:
    """Compute cosine similarity per row (sample)."""
    # orig, swap: (N, D)
    dot = np.sum(orig * swap, axis=1)
    norm_o = np.linalg.norm(orig, axis=1)
    norm_s = np.linalg.norm(swap, axis=1)
    return dot / (norm_o * norm_s + 1e-10)


def analyze_scale(npz_path: str, scale: str) -> dict:
    """Analyze one scale's NPZ file. Returns dict of results."""
    data = np.load(npz_path, allow_pickle=True)

    # Find available layers
    layer_keys = sorted([k for k in data.files if k.startswith('orig_L')])
    layers = [int(k.replace('orig_L', '')) for k in layer_keys]

    scale_results = {}

    for layer in layers:
        orig = data.get(f'orig_L{layer}')
        swap = data.get(f'swap_L{layer}')
        labels = data.get(f'labels_L{layer}')

        if orig is None or swap is None or labels is None:
            continue

        labels = np.array([str(l) for l in labels])
        cos_sims = cosine_sim_per_sample(orig, swap)

        layer_result = {
            'overall_mean': float(np.mean(cos_sims)),
            'overall_std': float(np.std(cos_sims)),
            'overall_n': len(cos_sims),
        }

        # Per category
        for cat in CATEGORY_ORDER:
            mask = labels == cat
            if mask.any():
                cat_sims = cos_sims[mask]
                layer_result[f'{cat}_mean'] = float(np.mean(cat_sims))
                layer_result[f'{cat}_std'] = float(np.std(cat_sims))
                layer_result[f'{cat}_n'] = int(mask.sum())

        # Per group
        for group in GROUP_ORDER:
            group_cats = [c for c in CATEGORY_ORDER if GROUP_MAP[c] == group]
            mask = np.isin(labels, group_cats)
            if mask.any():
                group_sims = cos_sims[mask]
                layer_result[f'{group}_mean'] = float(np.mean(group_sims))
                layer_result[f'{group}_std'] = float(np.std(group_sims))

        scale_results[layer] = layer_result

    return scale_results


def plot_swap_cosine_by_layer(
    all_results: dict,  # {scale: {layer: {category_mean, ...}}}
    model_type: str,
    save_path: str,
):
    """Plot cos(orig, swap) across layers for each scale."""
    fig, axes = plt.subplots(1, 3, figsize=(21, 6))
    scale_order = ['vanilla', '80k', '400k', '800k', '2m', 'roborefer']

    for idx, group in enumerate(GROUP_ORDER):
        ax = axes[idx]
        for scale in scale_order:
            if scale not in all_results:
                continue
            results = all_results[scale]
            layers = sorted(results.keys())
            vals = [results[l].get(f'{group}_mean', np.nan) for l in layers]
            color = SCALE_COLORS.get(scale, 'gray')
            ax.plot(layers, vals, '-o', color=color, label=scale, linewidth=2, markersize=5)

        ax.set_xlabel('Layer Index', fontsize=11)
        ax.set_ylabel('cos(original, swapped)', fontsize=11)
        ax.set_title(f'{group}', fontsize=13, fontweight='bold')
        ax.legend(fontsize=9)
        ax.grid(True, alpha=0.3)
        ax.set_ylim(None, 1.02)

    fig.suptitle(
        f'{model_type.upper()} - cos(original, swapped) Across Layers\n'
        f'(Lower = model distinguishes swap more)',
        fontsize=14, fontweight='bold', y=1.04
    )
    plt.tight_layout()
    plt.savefig(save_path, dpi=300, bbox_inches='tight')
    plt.close()
    print(f"Saved: {save_path}")


def plot_swap_cosine_barplot(
    all_results: dict,
    model_type: str,
    save_path: str,
):
    """Bar plot at deepest layer: per-category cos(orig, swap) across scales."""
    scale_order = ['vanilla', '80k', '400k', '800k', '2m', 'roborefer']
    available_scales = [s for s in scale_order if s in all_results]

    if not available_scales:
        return

    # Use deepest layer
    sample_layers = sorted(all_results[available_scales[0]].keys())
    deepest = sample_layers[-1]

    fig, ax = plt.subplots(figsize=(14, 6))
    x = np.arange(len(CATEGORY_ORDER))
    width = 0.8 / len(available_scales)

    for i, scale in enumerate(available_scales):
        results = all_results[scale]
        if deepest not in results:
            continue
        layer_data = results[deepest]
        vals = [layer_data.get(f'{cat}_mean', 0) for cat in CATEGORY_ORDER]
        offset = (i - len(available_scales) / 2 + 0.5) * width
        color = SCALE_COLORS.get(scale, 'gray')
        bars = ax.bar(x + offset, vals, width, label=scale, color=color)
        for bar, val in zip(bars, vals):
            if val > 0:
                ax.annotate(f'{val:.3f}', xy=(bar.get_x() + bar.get_width() / 2, bar.get_height()),
                            xytext=(0, 2), textcoords='offset points',
                            ha='center', va='bottom', fontsize=6, rotation=90)

    ax.set_xticks(x)
    ax.set_xticklabels(CATEGORY_ORDER, fontsize=11)
    ax.set_ylabel('cos(original, swapped)', fontsize=12)
    ax.set_title(f'{model_type.upper()} - Layer {deepest}: cos(original, swapped) by Category\n'
                 f'(Lower = model representation changes more on swap)',
                 fontsize=13, fontweight='bold')
    ax.legend(fontsize=9)
    ax.grid(True, alpha=0.3, axis='y')

    plt.tight_layout()
    plt.savefig(save_path, dpi=300, bbox_inches='tight')
    plt.close()
    print(f"Saved: {save_path}")


def plot_swap_cosine_distribution(
    all_results_raw: dict,  # {scale: {layer: {'sims': array, 'labels': array}}}
    model_type: str,
    save_dir: str,
):
    """Histogram of per-sample cos(orig, swap) at deepest layer, per group."""
    scale_order = ['vanilla', '80k', '400k', '800k', '2m', 'roborefer']
    available_scales = [s for s in scale_order if s in all_results_raw]

    if not available_scales:
        return

    sample_layers = sorted(all_results_raw[available_scales[0]].keys())
    deepest = sample_layers[-1]

    for group in GROUP_ORDER:
        fig, axes = plt.subplots(1, len(available_scales), figsize=(5 * len(available_scales), 4),
                                  sharey=True, sharex=True)
        if len(available_scales) == 1:
            axes = [axes]

        for i, scale in enumerate(available_scales):
            ax = axes[i]
            raw = all_results_raw[scale].get(deepest)
            if raw is None:
                continue
            sims = raw['sims']
            labels = raw['labels']
            group_cats = [c for c in CATEGORY_ORDER if GROUP_MAP[c] == group]
            mask = np.isin(labels, group_cats)

            if mask.any():
                group_sims = sims[mask]
                ax.hist(group_sims, bins=30, alpha=0.7, color=SCALE_COLORS.get(scale, 'gray'),
                        edgecolor='white', linewidth=0.5)
                ax.axvline(np.mean(group_sims), color='red', linestyle='--', linewidth=1.5,
                           label=f'mean={np.mean(group_sims):.3f}')
                ax.legend(fontsize=8)

            ax.set_title(f'{scale}', fontsize=11, fontweight='bold')
            ax.set_xlabel('cos(orig, swap)', fontsize=9)
            if i == 0:
                ax.set_ylabel('Count', fontsize=9)

        fig.suptitle(f'{model_type.upper()} - {group} - Layer {deepest}: Distribution of cos(orig, swap)',
                     fontsize=13, fontweight='bold')
        plt.tight_layout()
        plt.savefig(os.path.join(save_dir, f'swap_cosine_dist_{group}.png'), dpi=200, bbox_inches='tight')
        plt.close()

    print(f"Saved distribution plots to {save_dir}")


def main():
    parser = argparse.ArgumentParser(description='Post-hoc: cos(original, swapped) analysis')
    parser.add_argument('--model_type', type=str, required=True, choices=['molmo', 'nvila', 'qwen'])
    parser.add_argument('--results_dir', type=str,
                        default='/data/shared/Qwen/experiments/exp2a_swap_analysis/results')
    args = parser.parse_args()

    model_dir = os.path.join(args.results_dir, args.model_type)
    plots_dir = os.path.join(model_dir, 'plots')
    os.makedirs(plots_dir, exist_ok=True)

    scale_order = ['vanilla', '80k', '400k', '800k', '2m', 'roborefer']

    all_results = {}       # {scale: {layer: stats_dict}}
    all_results_raw = {}   # {scale: {layer: {'sims': array, 'labels': array}}}

    for scale in scale_order:
        npz_path = os.path.join(model_dir, f'vectors_{scale}.npz')
        if not os.path.exists(npz_path):
            continue

        print(f"\nProcessing {args.model_type} - {scale}")
        results = analyze_scale(npz_path, scale)
        all_results[scale] = results

        # Also extract raw per-sample cosines for distribution plots
        data = np.load(npz_path, allow_pickle=True)
        raw_layers = {}
        for layer in sorted(results.keys()):
            orig = data.get(f'orig_L{layer}')
            swap = data.get(f'swap_L{layer}')
            labels = data.get(f'labels_L{layer}')
            if orig is not None and swap is not None and labels is not None:
                sims = cosine_sim_per_sample(orig, swap)
                raw_layers[layer] = {
                    'sims': sims,
                    'labels': np.array([str(l) for l in labels]),
                }
        all_results_raw[scale] = raw_layers

        # Print summary for deepest layer
        deepest = sorted(results.keys())[-1]
        r = results[deepest]
        print(f"  Layer {deepest} (deepest):")
        print(f"    Overall: {r['overall_mean']:.4f} ± {r['overall_std']:.4f} (n={r['overall_n']})")
        for cat in CATEGORY_ORDER:
            m = r.get(f'{cat}_mean')
            s = r.get(f'{cat}_std')
            n = r.get(f'{cat}_n', 0)
            if m is not None:
                print(f"    {cat:>6s}: {m:.4f} ± {s:.4f} (n={n})")

    if not all_results:
        print("No data found. Check results_dir.")
        return

    # Save JSON
    json_data = {}
    for scale, layers in all_results.items():
        json_data[scale] = {str(l): v for l, v in layers.items()}
    json_path = os.path.join(model_dir, 'swap_cosine_stats.json')
    with open(json_path, 'w') as f:
        json.dump(json_data, f, indent=2)
    print(f"\nSaved stats: {json_path}")

    # Save CSV (one row per scale×layer)
    csv_rows = []
    for scale, layers in all_results.items():
        for layer, stats in sorted(layers.items()):
            row = {'scale': scale, 'layer': layer}
            row.update(stats)
            csv_rows.append(row)
    csv_path = os.path.join(model_dir, 'swap_cosine_stats.csv')
    pd.DataFrame(csv_rows).to_csv(csv_path, index=False)
    print(f"Saved CSV: {csv_path}")

    # Plots
    plot_swap_cosine_by_layer(all_results, args.model_type,
                               os.path.join(plots_dir, 'swap_cosine_by_layer.png'))
    plot_swap_cosine_barplot(all_results, args.model_type,
                             os.path.join(plots_dir, 'swap_cosine_barplot.png'))
    plot_swap_cosine_distribution(all_results_raw, args.model_type, plots_dir)

    print(f"\nDone. Results in: {model_dir}")


if __name__ == '__main__':
    main()