File size: 17,203 Bytes
203a7fb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Generate paper-quality figures comparing the user's fine-tuned model against
two baselines (Qwen3-Omni vanilla, MiniCPM-o-4.5) on the Shift (sync) and
VGGSoundSync benchmarks. All figures use DejaVu Serif, no titles, 300 dpi
PDF + PNG, paper-friendly fonttype=42.
"""

import json
from pathlib import Path
from typing import Dict, List

import matplotlib.pyplot as plt
import numpy as np

# ---------------------------------------------------------------------------
# Style
# ---------------------------------------------------------------------------
plt.rcParams.update({
    "font.family":      "DejaVu Serif",
    "font.serif":       ["DejaVu Serif"],
    "mathtext.fontset": "dejavuserif",
    "font.size":        11,
    "axes.titlesize":   12,
    "axes.titleweight": "bold",
    "axes.labelsize":   11,
    "xtick.labelsize":  10.5,
    "ytick.labelsize":  10.5,
    "legend.fontsize":  10,
    "pdf.fonttype":     42,
    "ps.fonttype":      42,
    "savefig.dpi":      300,
    "savefig.bbox":     "tight",
    "axes.spines.top":   False,
    "axes.spines.right": False,
})

# ---------------------------------------------------------------------------
# Data sources
# ---------------------------------------------------------------------------
ROOT = Path("/home/ubuntu/eval_results/paper_shift_backup")
OUT  = Path("/home/ubuntu/figs/my_model_vs_baselines")
OUT.mkdir(parents=True, exist_ok=True)

MODELS = [
    # (display, sync_dir, vggsync_dir, color)
    ("Qwen3-Omni",   ROOT/"sync/sync_qwen3omni_vanilla",
                     ROOT/"vggsoundsync/vggsync_freetext_vanilla_qwen3omni_3k",
                     "#5b8def"),
    ("MiniCPM-o",    ROOT/"minicpmo_sync",
                     ROOT/"minicpmo_vggsync",
                     "#f4a04a"),
    ("Ours",         ROOT/"sync/sync_sft_dpo_mdpo_fin_avmcqa_longform",
                     ROOT/"vggsoundsync/vggsync_freetext_sft_dpo_mdpo_fin_avmcqa_longform_3k",
                     "#2fa363"),
]

def load_metrics(p: Path) -> dict:
    return json.loads((p / "metrics.json").read_text())

def load_jsonl(p: Path):
    f = p / "eval_results.jsonl"
    if not f.exists():
        return []
    return [json.loads(l) for l in f.open() if l.strip()]


# ===========================================================================
# Figure 1 β€” Headline three-metric bar chart (2 panels: Shift + VGGSoundSync)
# ===========================================================================
def fig_headline():
    metric_keys   = [
        ("three_class_accuracy",        "3-class Acc."),
        ("sync_desync_accuracy",        "Sync/Desync Acc."),
        ("direction_accuracy_on_desync","Direction Acc."),
    ]
    panels = [
        ("Shift",         [load_metrics(m[1]) for m in MODELS]),
        ("VGGSoundSync",  [load_metrics(m[2]) for m in MODELS]),
    ]

    fig, axes = plt.subplots(1, 2, figsize=(11.0, 4.2),
                              gridspec_kw={"wspace": 0.22})
    n_models = len(MODELS)
    n_metric = len(metric_keys)
    bar_w = 0.24

    for ax, (title, mets) in zip(axes, panels):
        x = np.arange(n_metric)
        for i, (m, met) in enumerate(zip(MODELS, mets)):
            offsets = (i - (n_models - 1) / 2) * bar_w
            heights = [met.get(k, 0.0) for k, _ in metric_keys]
            bars = ax.bar(x + offsets, heights, bar_w,
                           color=m[3], edgecolor="white", linewidth=0.6,
                           label=m[0], zorder=3)
            for b, v in zip(bars, heights):
                ax.text(b.get_x() + b.get_width() / 2, v + 0.012,
                        f"{v*100:.1f}", ha="center", va="bottom",
                        fontsize=9, color="#1a1a1a")
        ax.set_xticks(x)
        ax.set_xticklabels([lbl for _, lbl in metric_keys])
        ax.set_ylim(0, 1.05)
        ax.set_yticks(np.arange(0, 1.01, 0.2))
        ax.set_yticklabels([f"{int(v*100)}" for v in np.arange(0, 1.01, 0.2)])
        ax.set_ylabel("Accuracy (%)" if ax is axes[0] else "")
        ax.set_title(title, pad=6)
        ax.grid(axis="y", color="#e0e0e0", lw=0.6, zorder=0)
        ax.set_axisbelow(True)
    handles, labels = axes[0].get_legend_handles_labels()
    fig.legend(handles, labels, loc="upper center",
                bbox_to_anchor=(0.5, 1.04), ncol=n_models,
                frameon=False, fontsize=11)
    fig.tight_layout(rect=(0, 0, 1, 0.95))
    fig.savefig(OUT/"fig1_headline.pdf"); fig.savefig(OUT/"fig1_headline.png")
    plt.close(fig)


# ===========================================================================
# Figure 2 β€” Per-direction accuracy on Shift (synced / delay / early)
# ===========================================================================
def fig_per_direction():
    cats = [("synced_accuracy", "Synced (Orig.)"),
            ("delay_accuracy",  "Delay"),
            ("early_accuracy",  "Early")]
    fig, ax = plt.subplots(figsize=(7.4, 4.0))
    n_models = len(MODELS)
    bar_w = 0.25
    x = np.arange(len(cats))
    for i, (name, sync_dir, _, color) in enumerate(MODELS):
        m = load_metrics(sync_dir)
        pc = m["per_category"]
        heights = [pc[k] for k, _ in cats]
        offsets = (i - (n_models - 1) / 2) * bar_w
        bars = ax.bar(x + offsets, heights, bar_w, color=color,
                       edgecolor="white", linewidth=0.6, label=name, zorder=3)
        for b, v in zip(bars, heights):
            ax.text(b.get_x() + b.get_width()/2, v + 0.012,
                    f"{v*100:.1f}", ha="center", va="bottom",
                    fontsize=9, color="#1a1a1a")
    ax.set_xticks(x); ax.set_xticklabels([lbl for _, lbl in cats])
    ax.set_ylim(0, 1.10)
    ax.set_yticks(np.arange(0, 1.01, 0.2))
    ax.set_yticklabels([f"{int(v*100)}" for v in np.arange(0, 1.01, 0.2)])
    ax.set_ylabel("Accuracy (%)")
    ax.grid(axis="y", color="#e0e0e0", lw=0.6, zorder=0); ax.set_axisbelow(True)
    ax.legend(loc="upper right", frameon=False)
    fig.tight_layout()
    fig.savefig(OUT/"fig2_per_direction.pdf"); fig.savefig(OUT/"fig2_per_direction.png")
    plt.close(fig)


# ===========================================================================
# Figure 3 β€” Per-difficulty line chart on VGGSoundSync
# ===========================================================================
def fig_per_difficulty():
    diff_order = ["synced", "very_easy", "easy", "medium", "hard"]
    diff_labels = ["Orig.\n(synced)", "Very Easy\n(2.0–2.5s)",
                   "Easy\n(1.5–2.0s)", "Medium\n(1.0–1.5s)",
                   "Hard\n(0.5–1.0s)"]
    fig, ax = plt.subplots(figsize=(8.2, 4.4))
    x = np.arange(len(diff_order))
    for name, _, vggsync_dir, color in MODELS:
        m = load_metrics(vggsync_dir)
        pd_ = m["per_difficulty"]
        ys = [pd_[d]["accuracy"] for d in diff_order]
        ax.plot(x, ys, marker="o", linewidth=2.2, markersize=8.5,
                color=color, label=name, markeredgecolor="white",
                markeredgewidth=1.2, zorder=3)
        for xi, v in zip(x, ys):
            ax.text(xi, v + 0.025, f"{v*100:.0f}", ha="center", va="bottom",
                    fontsize=9, color=color)
    ax.set_xticks(x); ax.set_xticklabels(diff_labels)
    ax.set_ylim(0, 1.0)
    ax.set_yticks(np.arange(0, 1.01, 0.2))
    ax.set_yticklabels([f"{int(v*100)}" for v in np.arange(0, 1.01, 0.2)])
    ax.set_ylabel("Accuracy (%)")
    ax.set_xlabel("VGGSoundSync difficulty bucket  (offset magnitude shown)")
    ax.grid(axis="y", color="#e0e0e0", lw=0.6, zorder=0); ax.set_axisbelow(True)
    ax.legend(loc="upper right", frameon=False)
    fig.tight_layout()
    fig.savefig(OUT/"fig3_per_difficulty.pdf"); fig.savefig(OUT/"fig3_per_difficulty.png")
    plt.close(fig)


# ===========================================================================
# Figure 4 β€” Offset CDF on Shift and VGGSoundSync (two panels)
# ===========================================================================
def _abs_offset_errors(rows):
    """Extract |pred_offset - gt_offset| only on samples where the model
    actually claimed a desync (i.e. produced a non-zero offset)."""
    out = []
    for r in rows:
        gt_off = r.get("gt_offset_sec")
        if gt_off is None:
            continue
        # gt_synced=True samples have no offset to evaluate
        if r.get("gt_synced") is True:
            continue
        pred_off = r.get("pred_offset_sec")
        if pred_off is None:
            continue
        # only include evaluations where the model also said it was offset
        if r.get("pred_synced") is True:
            continue
        out.append(abs(float(pred_off) - float(gt_off)))
    return np.array(out, dtype=float)


def fig_offset_cdf():
    fig, axes = plt.subplots(1, 2, figsize=(11.0, 4.2),
                              gridspec_kw={"wspace": 0.22})
    panels = [
        ("Shift",        [m[1] for m in MODELS]),
        ("VGGSoundSync", [m[2] for m in MODELS]),
    ]
    thresholds = np.linspace(0, 3.0, 121)
    for ax, (title, dirs) in zip(axes, panels):
        for (name, _, _, color), d in zip(MODELS, dirs):
            rows = load_jsonl(d)
            errs = _abs_offset_errors(rows)
            if len(errs) == 0:
                continue
            # CDF over ALL desync samples (denominator = total desync gt count)
            n_desync = sum(1 for r in rows
                            if r.get("gt_synced") is False
                            or r.get("gt_direction") in ("delay", "early"))
            ys = [(errs <= t).sum() / max(n_desync, 1) for t in thresholds]
            ax.plot(thresholds, ys, color=color, linewidth=2.4,
                    label=name, zorder=3)
            # mark the value at 0.5s (a key threshold) with a dot
            t_mark = 0.5
            y_mark = (errs <= t_mark).sum() / max(n_desync, 1)
            ax.scatter([t_mark], [y_mark], s=70, color=color,
                       edgecolor="white", linewidth=1.2, zorder=4)
            ax.text(t_mark + 0.05, y_mark + 0.018,
                    f"{y_mark*100:.0f}%", color=color, fontsize=9,
                    weight="bold")
        ax.set_xlim(0, 3.0)
        ax.set_ylim(0, 1.0)
        ax.set_yticks(np.arange(0, 1.01, 0.2))
        ax.set_yticklabels([f"{int(v*100)}" for v in np.arange(0, 1.01, 0.2)])
        ax.set_xlabel("Offset error tolerance |Ξ”| (sec)")
        ax.set_ylabel("Fraction of desync samples within tolerance (%)"
                      if ax is axes[0] else "")
        ax.set_title(title, pad=6)
        ax.axvline(0.5, color="#bbb", linestyle=":", linewidth=0.8, zorder=1)
        ax.grid(axis="both", color="#e8e8e8", lw=0.5, zorder=0)
        ax.set_axisbelow(True)
    handles, labels = axes[0].get_legend_handles_labels()
    fig.legend(handles, labels, loc="upper center",
                bbox_to_anchor=(0.5, 1.04), ncol=len(MODELS),
                frameon=False, fontsize=11)
    fig.tight_layout(rect=(0, 0, 1, 0.95))
    fig.savefig(OUT/"fig4_offset_cdf.pdf"); fig.savefig(OUT/"fig4_offset_cdf.png")
    plt.close(fig)


# ===========================================================================
# Figure 5 β€” Per-class scatter on VGGSoundSync (vanilla vs ours)
# ===========================================================================
def fig_per_class_scatter():
    vanilla = load_metrics(MODELS[0][2])["per_class"]
    ours    = load_metrics(MODELS[2][2])["per_class"]
    minicpm = load_metrics(MODELS[1][2])["per_class"]
    classes = sorted(set(vanilla) & set(ours) & set(minicpm))

    fig, axes = plt.subplots(1, 2, figsize=(11.0, 5.2),
                              gridspec_kw={"wspace": 0.25})

    panels = [
        (axes[0], "vs Qwen3-Omni",  vanilla, MODELS[0][3]),
        (axes[1], "vs MiniCPM-o",   minicpm, MODELS[1][3]),
    ]
    for ax, sub_title, baseline_d, base_color in panels:
        bx = np.array([baseline_d[c]["accuracy"]    for c in classes])
        oy = np.array([ours[c]["accuracy"]          for c in classes])
        sizes = np.array([vanilla[c]["count"]       for c in classes])
        # Use lighter "base_color" mix for the dots; gradient by sample count
        ax.scatter(bx, oy, s=10 + sizes * 1.5,
                    color="#2fa363", alpha=0.65,
                    edgecolor="white", linewidth=0.5, zorder=3)
        ax.plot([0, 1], [0, 1], ls="--", color="#888", lw=1.0, zorder=2)
        # Highlight a few extreme points with class names
        deltas = oy - bx
        top_imp = np.argsort(-deltas)[:5]
        bot_imp = np.argsort(deltas)[:3]
        for idx in list(top_imp) + list(bot_imp):
            ax.annotate(classes[idx], (bx[idx], oy[idx]),
                        xytext=(4, 4), textcoords="offset points",
                        fontsize=7.5, color="#444", style="italic")
        # Stats annotation
        win = (deltas > 0).sum()
        ax.text(0.02, 0.97,
                f"Ours wins on {win}/{len(classes)} classes\n"
                f"Mean Ξ” = +{deltas.mean()*100:.1f} pts",
                transform=ax.transAxes, va="top", ha="left",
                fontsize=10, color="#1a1a1a",
                bbox=dict(facecolor="#fefef0", edgecolor="#888",
                          boxstyle="round,pad=0.35"))
        ax.set_xlim(0, 1.0); ax.set_ylim(0, 1.0)
        ax.set_xticks(np.arange(0, 1.01, 0.2))
        ax.set_yticks(np.arange(0, 1.01, 0.2))
        ax.set_xticklabels([f"{int(v*100)}" for v in np.arange(0, 1.01, 0.2)])
        ax.set_yticklabels([f"{int(v*100)}" for v in np.arange(0, 1.01, 0.2)])
        ax.set_xlabel(f"Baseline accuracy {sub_title.split()[1]} (%)")
        ax.set_ylabel("Ours accuracy (%)" if ax is axes[0] else "")
        ax.set_title(sub_title, pad=6)
        ax.grid(color="#eee", lw=0.5, zorder=0)
        ax.set_axisbelow(True)
    fig.tight_layout()
    fig.savefig(OUT/"fig5_per_class_scatter.pdf")
    fig.savefig(OUT/"fig5_per_class_scatter.png")
    plt.close(fig)


# ===========================================================================
# Figure 6 β€” Within-tolerance bar grid (offset attribution success)
# ===========================================================================
def fig_within_thresholds():
    """Show the % of desync samples for which the predicted offset is within a
    fixed tolerance, computed against the FULL desync sample count (not just
    samples where the model attempted an offset)."""
    fig, axes = plt.subplots(1, 2, figsize=(11.0, 4.2),
                              gridspec_kw={"wspace": 0.22})
    sync_thresh   = ["offset_within_0.5s", "offset_within_1.0s"]
    sync_labels   = ["≀ 0.5 s", "≀ 1.0 s"]
    vggsync_thresh = ["offset_within_0.2s", "offset_within_0.5s"]
    vggsync_labels = ["≀ 0.2 s", "≀ 0.5 s"]
    panels = [
        ("Shift",        sync_thresh,    sync_labels,   1),
        ("VGGSoundSync", vggsync_thresh, vggsync_labels, 2),
    ]
    bar_w = 0.25

    for ax, (title, ks, labs, dir_idx) in zip(axes, panels):
        x = np.arange(len(ks))
        # denominator: total desync samples (= total - synced_count)
        for i, (name, sd, vd, color) in enumerate(MODELS):
            m = load_metrics(sd if dir_idx == 1 else vd)
            if dir_idx == 1:
                n_synced = m["per_category"]["synced_count"]
            else:
                n_synced = m["per_difficulty"]["synced"]["count"]
            n_desync = m["total_samples"] - n_synced
            heights = [m.get(k, 0) / max(n_desync, 1) for k in ks]
            offsets = (i - (len(MODELS) - 1) / 2) * bar_w
            bars = ax.bar(x + offsets, heights, bar_w, color=color,
                           edgecolor="white", linewidth=0.6,
                           label=name, zorder=3)
            for b, v in zip(bars, heights):
                ax.text(b.get_x() + b.get_width()/2, v + 0.012,
                        f"{v*100:.1f}", ha="center", va="bottom",
                        fontsize=9, color="#1a1a1a")
        ax.set_xticks(x); ax.set_xticklabels(labs)
        ax.set_xlabel("Offset tolerance")
        ax.set_ylim(0, max(0.4, ax.get_ylim()[1]) + 0.05)
        ax.set_ylabel("Desync samples within tolerance (%)"
                      if ax is axes[0] else "")
        ax.set_title(title, pad=6)
        ax.grid(axis="y", color="#e0e0e0", lw=0.6, zorder=0)
        ax.set_axisbelow(True)
        # convert ticks to %
        yticks = ax.get_yticks()
        ax.set_yticklabels([f"{int(v*100)}" for v in yticks])
    handles, labels = axes[0].get_legend_handles_labels()
    fig.legend(handles, labels, loc="upper center",
                bbox_to_anchor=(0.5, 1.04), ncol=len(MODELS),
                frameon=False, fontsize=11)
    fig.tight_layout(rect=(0, 0, 1, 0.95))
    fig.savefig(OUT/"fig6_within_thresholds.pdf")
    fig.savefig(OUT/"fig6_within_thresholds.png")
    plt.close(fig)


# ===========================================================================
# Run all
# ===========================================================================
if __name__ == "__main__":
    fig_headline()
    fig_per_direction()
    fig_per_difficulty()
    fig_offset_cdf()
    fig_per_class_scatter()
    fig_within_thresholds()
    print("All figures saved to:", OUT)
    for p in sorted(OUT.glob("*.png")):
        print(" ", p.name)