File size: 13,178 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
#!/usr/bin/env python3
"""Compute and plot VD/HD/HV entanglement metrics across all layers for all scales.

Definitions (values come from the delta-similarity CSV heatmaps, where each cell is
the cosine similarity between the mean delta vector of row-category and col-category):

  VD-entanglement = 1/4 * (mean(above-far, below-close) - mean(above-close, below-far))
  HD-entanglement = 1/4 * (mean(left-far,  right-close)  - mean(left-close,  right-far))
  HV-entanglement = 1/4 * (mean(left-above, right-below) - mean(left-below,  right-above))

  Note: 'below' is stored as 'under' in the CSV.  The script handles both transparently.

Positive value = the two axes are more entangled in the "expected" direction
  (e.g. above↔far, left↔above) than in the "unexpected" direction.

Single directory:   color by scale (vanilla=blue, 80k=orange, …)
Multiple directories: color by model family, linestyle by scale

Usage (single dir):
    python plot_entanglement.py results_short_answer/molmo
    python plot_entanglement.py results_short_answer/molmo --subset both_correct

Usage (multiple dirs β€” compare families):
    python plot_entanglement.py results_short_answer/molmo results_short_answer/nvila results_short_answer/qwen
    python plot_entanglement.py results_short_answer/molmo results_short_answer/nvila --out-dir /tmp/compare
"""

import argparse
import re
from pathlib import Path
from collections import defaultdict

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

# ── Scale ordering and colors (kept in sync with swap_analysis.py) ────────────

SCALE_ORDER = [
    'vanilla', '80k', '80k-5pct', '80k-10pct', '80k-20pct', '80k-30pct',
    '400k', '400k-5pct', '800k', '800k-5pct', '2m', 'roborefer',
    'molmo2', 'qwen3_32b', 'qwen3_235b',
]

# Used in single-dir mode (one color per scale)
SCALE_COLORS = {
    'vanilla':    '#1f77b4', '80k':       '#ff7f0e', '400k':      '#2ca02c',
    '800k':       '#d62728', '2m':        '#9467bd', 'roborefer': '#8c564b',
    'molmo2':     '#17becf', 'qwen3_32b': '#bcbd22', 'qwen3_235b':'#e377c2',
    '80k-5pct':   '#b2dfdb', '80k-10pct': '#00b894', '80k-20pct': '#00897b',
    '80k-30pct':  '#004d40', '400k-5pct': '#66bb6a', '800k-5pct': '#ef9a9a',
}

SCALE_DISPLAY_NAMES = {
    '80k-5pct':  '80k 5%',  '80k-10pct': '80k 10%',
    '80k-20pct': '80k 20%', '80k-30pct': '80k 30%',
    '400k-5pct': '400k 5%', '800k-5pct': '800k 5%',
}

# Used in multi-dir mode (one color per model family, one linestyle per scale)
FAMILY_COLOR_CYCLE = [
    '#1f77b4',  # blue
    '#d62728',  # red
    '#2ca02c',  # green
    '#ff7f0e',  # orange
    '#9467bd',  # purple
    '#8c564b',  # brown
    '#e377c2',  # pink
    '#17becf',  # cyan
    '#bcbd22',  # yellow-green
]

SCALE_LINESTYLE_CYCLE = [
    'solid',
    'dashed',
    'dotted',
    'dashdot',
    (0, (5, 1)),          # long dash
    (0, (3, 1, 1, 1)),    # dash-dot-dot
    (0, (1, 1)),          # dotted dense
    (0, (5, 5)),          # long dash sparse
]

# ── CSV helpers ────────────────────────────────────────────────────────────────

_CSV_RE = re.compile(r'^delta_similarity_(.+)_L(\d+)_(all_pairs|both_correct)\.csv$')


def _loc(df: pd.DataFrame, row: str, col: str) -> float:
    """Look up (row, col) with 'under' ↔ 'below' aliasing."""
    aliases = {'below': 'under', 'under': 'below'}
    r = row if row in df.index else aliases.get(row, row)
    c = col if col in df.columns else aliases.get(col, col)
    if r not in df.index or c not in df.columns:
        return float('nan')
    return float(df.loc[r, c])


def compute_entanglement(df: pd.DataFrame) -> dict:
    """Compute VD, HD, HV entanglement from a 6Γ—6 delta-similarity DataFrame.

    Each metric is the difference of two means of cosine similarities (range [-2, 2]),
    divided by 4 to normalise to [-0.5, 0.5].
    """
    vd = (_loc(df, 'above', 'far') + _loc(df, 'below', 'close') -
          _loc(df, 'above', 'close') - _loc(df, 'below', 'far')) / 4

    hd = (_loc(df, 'left', 'far') + _loc(df, 'right', 'close') -
          _loc(df, 'left', 'close') - _loc(df, 'right', 'far')) / 4

    hv = (_loc(df, 'left', 'above') + _loc(df, 'right', 'below') -
          _loc(df, 'left', 'below') - _loc(df, 'right', 'above')) / 4

    return {'VD': vd, 'HD': hd, 'HV': hv}


def load_entanglement(csv_dir: Path, subset: str) -> dict:
    """
    Returns:
        {scale: {layer_int: {'VD': float, 'HD': float, 'HV': float}}}
    """
    data = defaultdict(dict)
    for fname in sorted(csv_dir.iterdir()):
        m = _CSV_RE.match(fname.name)
        if not m:
            continue
        scale, layer_str, file_subset = m.group(1), m.group(2), m.group(3)
        if file_subset != subset:
            continue
        layer = int(layer_str)
        try:
            df = pd.read_csv(fname, index_col=0)
        except Exception as e:
            print(f"  [warn] Could not read {fname.name}: {e}")
            continue
        data[scale][layer] = compute_entanglement(df)
    return dict(data)


def _scale_sort_key(s):
    return SCALE_ORDER.index(s) if s in SCALE_ORDER else 99


# ── Plotting ──────────────────────────────────────────────────────────────────

METRICS = [
    ('VD', 'Vertical-Distance Entanglement\nmean(above-far, below-close) βˆ’ mean(above-close, below-far)'),
    ('HD', 'Horizontal-Distance Entanglement\nmean(left-far, right-close) βˆ’ mean(left-close, right-far)'),
    # ('HV', 'HV-Entanglement\nmean(left-above, right-below) βˆ’ mean(left-below, right-above)'),
]


def plot_entanglement_single(scale_data: dict, model_type: str,
                              subset: str, save_path: Path):
    """Single directory: color by scale."""
    fig, axes = plt.subplots(1, 2, figsize=(12, 5))

    for ax, (metric_key, metric_label) in zip(axes, METRICS):
        for scale in SCALE_ORDER:
            if scale not in scale_data:
                continue
            layer_dict = scale_data[scale]
            layers = sorted(layer_dict.keys())
            vals = [layer_dict[l][metric_key] for l in layers]
            if not any(np.isfinite(v) for v in vals):
                continue
            ax.plot(
                layers, vals, '-',
                color=SCALE_COLORS.get(scale, 'gray'),
                label=SCALE_DISPLAY_NAMES.get(scale, scale),
                linewidth=2,
            )
        _style_ax(ax, metric_label)

    tag = 'Both-Correct' if subset == 'both_correct' else 'All Pairs'
    fig.suptitle(
        f'{model_type.upper()} β€” Entanglement Metrics Across Layers  [{tag}]',
        fontsize=13, fontweight='bold',
    )
    _save(fig, save_path)


def plot_entanglement_multi(family_data: dict, subset: str, save_path: Path):
    """Multiple directories: color by family, linestyle by scale."""
    # Collect all scales across all families (in canonical order)
    all_scales = sorted(
        {s for scales in family_data.values() for s in scales},
        key=_scale_sort_key,
    )
    families = list(family_data.keys())  # preserve insertion order

    # Assign colors to families and linestyles to scales
    family_color = {f: FAMILY_COLOR_CYCLE[i % len(FAMILY_COLOR_CYCLE)]
                    for i, f in enumerate(families)}
    scale_ls = {s: SCALE_LINESTYLE_CYCLE[i % len(SCALE_LINESTYLE_CYCLE)]
                for i, s in enumerate(all_scales)}

    fig, axes = plt.subplots(1, 2, figsize=(12, 5))

    for ax, (metric_key, metric_label) in zip(axes, METRICS):
        for family in families:
            scale_data = family_data[family]
            color = family_color[family]
            for scale in all_scales:
                if scale not in scale_data:
                    continue
                layer_dict = scale_data[scale]
                layers = sorted(layer_dict.keys())
                vals = [layer_dict[l][metric_key] for l in layers]
                if not any(np.isfinite(v) for v in vals):
                    continue
                scale_disp = SCALE_DISPLAY_NAMES.get(scale, scale)
                ax.plot(
                    layers, vals,
                    color=color,
                    linestyle=scale_ls[scale],
                    label=f'{family} {scale_disp}',
                    linewidth=2,
                )
        _style_ax(ax, metric_label)

    tag = 'Both-Correct' if subset == 'both_correct' else 'All Pairs'
    title_families = ' vs '.join(f.upper() for f in families)
    fig.suptitle(
        f'{title_families} β€” Entanglement Metrics Across Layers  [{tag}]',
        fontsize=13, fontweight='bold',
    )
    _save(fig, save_path)


def _style_ax(ax, title: str):
    ax.axhline(y=0, color='gray', linestyle='--', alpha=0.5, linewidth=1)
    ax.set_xlabel('Layer Index', fontsize=11)
    ax.set_ylabel('Entanglement', fontsize=11)
    ax.set_ylim(-1, 1)
    ax.set_title(title, fontsize=10, fontweight='bold')
    ax.legend(fontsize=9)
    ax.grid(True, alpha=0.3)


def _save(fig, save_path: Path):
    plt.tight_layout()
    save_path.parent.mkdir(parents=True, exist_ok=True)
    plt.savefig(save_path, dpi=300, bbox_inches='tight')
    plt.close()
    print(f"Saved: {save_path}")


# ── Main ──────────────────────────────────────────────────────────────────────

def main():
    parser = argparse.ArgumentParser(
        description='Plot VD/HD/HV entanglement metrics from saved delta-similarity CSVs.',
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog=__doc__,
    )
    parser.add_argument('results_dirs', nargs='+', type=str,
                        help='One or more results directories '
                             '(e.g. results_short_answer/molmo results_short_answer/nvila)')
    parser.add_argument('--subset', choices=['all_pairs', 'both_correct'], default='all_pairs',
                        help='Which CSV subset to use (default: all_pairs)')
    parser.add_argument('--scales', nargs='+', default=None,
                        help='Restrict to these scales (default: all found)')
    parser.add_argument('--out-dir', type=str, default=None,
                        help='Output directory. Single dir default: {results_dir}/plots/entanglement/. '
                             'Multi dir default: {common_parent}/entanglement_compare/')
    args = parser.parse_args()

    # Resolve and validate all directories
    dirs = []
    for p in args.results_dirs:
        d = Path(p).resolve()
        if not d.is_dir():
            parser.error(f'Directory not found: {d}')
        csv_dir = d / 'csv'
        if not csv_dir.is_dir():
            parser.error(f'No csv/ subdirectory in: {d}')
        dirs.append(d)

    multi = len(dirs) > 1
    subset = args.subset
    tag = 'Both-Correct' if subset == 'both_correct' else 'All Pairs'

    # Determine output path
    if args.out_dir:
        out_dir = Path(args.out_dir)
    elif multi:
        common = dirs[0].parent
        out_dir = common / 'entanglement_compare'
    else:
        out_dir = dirs[0] / 'plots' / 'entanglement'

    print(f"Subset     : {subset}")
    print(f"Output dir : {out_dir}")
    print()

    # Load data from all directories
    family_data = {}   # {model_type: {scale: {layer: entanglement}}}
    for d in dirs:
        model_type = d.name
        scale_data = load_entanglement(d / 'csv', subset)

        if not scale_data:
            print(f"[warn] No matching CSVs in {d}/csv β€” skipping")
            continue

        if args.scales:
            scale_data = {s: v for s, v in scale_data.items() if s in args.scales}

        found = sorted(scale_data.keys(), key=_scale_sort_key)
        print(f"  {model_type}: {len(found)} scales β€” {found}")
        for s in found:
            layers = sorted(scale_data[s].keys())
            deepest = layers[-1]
            e = scale_data[s][deepest]
            vd = f"{e['VD']:>7.4f}" if np.isfinite(e['VD']) else '    nan'
            hd = f"{e['HD']:>7.4f}" if np.isfinite(e['HD']) else '    nan'
            hv = f"{e['HV']:>7.4f}" if np.isfinite(e['HV']) else '    nan'
            print(f"    {s:<15} L{deepest:>2}  VD={vd}  HD={hd}  HV={hv}")

        family_data[model_type] = scale_data

    if not family_data:
        print("[error] No data loaded from any directory.")
        return

    print()
    if multi:
        families_tag = '_'.join(family_data.keys())
        save_path = out_dir / f'entanglement_{families_tag}_{subset}.png'
        plot_entanglement_multi(family_data, subset, save_path)
    else:
        model_type = list(family_data.keys())[0]
        save_path = out_dir / f'entanglement_{subset}.png'
        plot_entanglement_single(family_data[model_type], model_type, subset, save_path)


if __name__ == '__main__':
    main()