miscellaneous / analyze_my_model.py
Rakancorle11's picture
Upload supp/ and root scripts
203a7fb verified
"""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)