File size: 4,848 Bytes
d4bcd5c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Aggregate per-benchmark results into the paper's 'average relative accuracy'
metric: for each (method, budget), rel = mean_b [ score_b(method,budget) /
score_b(vanilla,576) ] * 100.  Emits a CSV, a JSON summary, and a Plotly HTML.
"""
import os, sys, json, glob
import numpy as np

RESULT_FILES = {
    "POPE": "outputs/pope_results.json",
    "TextVQA": "outputs/textvqa_results.json",
    "ScienceQA": "outputs/scienceqa_results.json",
}
BUDGETS = [192, 128, 64]
METHODS = ["split", "random", "attn"]

# Paper Table 1 average relative accuracy for LLaVA-1.5-7B (SPLIT) for reference
PAPER_SPLIT_REL = {192: 99.3, 128: 97.8, 64: 92.8}
PAPER_BASELINE_REL = {  # DART / DivPrune / FastV best-known from Table 1
    "DART": {192: 99.0, 128: 97.2, 64: 91.4},
    "DivPrune": {192: 96.9, 128: 95.2, 64: 91.7},
    "FastV": {192: 96.1, 128: 93.3, 64: 86.6},
}


def load():
    data = {}
    for name, path in RESULT_FILES.items():
        if os.path.exists(path):
            with open(path) as f:
                data[name] = json.load(f)
    return data


def acc(res, key):
    return res["results"].get(key, {}).get("accuracy")


def main():
    data = load()
    print("loaded benchmarks:", list(data.keys()))
    # per-benchmark absolute accuracy table
    abs_rows = []
    for name, d in data.items():
        r = d["results"]
        row = {"benchmark": name, "n": d["n_examples"], "vanilla": acc(d, "vanilla@576")}
        for m in METHODS:
            for b in BUDGETS:
                row[f"{m}@{b}"] = acc(d, f"{m}@{b}")
        abs_rows.append(row)

    # relative accuracy averaged across benchmarks
    rel = {m: {} for m in METHODS}
    per_bench_rel = {m: {b: {} for b in BUDGETS} for m in METHODS}
    for m in METHODS:
        for b in BUDGETS:
            ratios = []
            for name, d in data.items():
                van = acc(d, "vanilla@576")
                a = acc(d, f"{m}@{b}")
                if van and a is not None and van > 0:
                    ratios.append(a / van)
                    per_bench_rel[m][b][name] = round(100 * a / van, 2)
            rel[m][b] = round(100 * float(np.mean(ratios)), 2) if ratios else None

    summary = {
        "benchmarks": {name: {"n": d["n_examples"]} for name, d in data.items()},
        "absolute_accuracy": abs_rows,
        "relative_accuracy_avg": rel,
        "per_benchmark_relative": per_bench_rel,
        "paper_reference": {"SPLIT": PAPER_SPLIT_REL, "baselines": PAPER_BASELINE_REL},
    }
    os.makedirs("outputs", exist_ok=True)
    with open("outputs/aggregate.json", "w") as f:
        json.dump(summary, f, indent=2)

    # CSV
    import csv
    with open("outputs/aggregate.csv", "w", newline="") as f:
        w = csv.writer(f)
        w.writerow(["metric", "method", "budget", "value"])
        for m in METHODS:
            for b in BUDGETS:
                w.writerow(["rel_acc_avg", m, b, rel[m][b]])
        for b in BUDGETS:
            w.writerow(["rel_acc_avg", "SPLIT_paper", b, PAPER_SPLIT_REL[b]])

    # console table
    print("\n=== Average relative accuracy (%) vs vanilla-576, this reproduction ===")
    print(f"{'budget':>8} | {'SPLIT(ours)':>12} | {'random':>8} | {'attn':>8} | {'SPLIT(paper)':>12}")
    for b in BUDGETS:
        print(f"{b:>8} | {str(rel['split'][b]):>12} | {str(rel['random'][b]):>8} | "
              f"{str(rel['attn'][b]):>8} | {PAPER_SPLIT_REL[b]:>12}")
    print("\nper-benchmark relative accuracy (split):")
    print(json.dumps(per_bench_rel["split"], indent=2))

    # Plotly figure
    try:
        import plotly.graph_objects as go
        fig = go.Figure()
        x = BUDGETS[::-1]
        fig.add_trace(go.Scatter(x=x, y=[rel["split"][b] for b in x], name="SPLIT (ours)",
                                 mode="lines+markers", line=dict(width=3)))
        fig.add_trace(go.Scatter(x=x, y=[PAPER_SPLIT_REL[b] for b in x], name="SPLIT (paper)",
                                 mode="lines+markers", line=dict(dash="dash")))
        fig.add_trace(go.Scatter(x=x, y=[rel["attn"][b] for b in x], name="attn-topk (ours)",
                                 mode="lines+markers"))
        fig.add_trace(go.Scatter(x=x, y=[rel["random"][b] for b in x], name="random (ours)",
                                 mode="lines+markers"))
        fig.update_layout(title="SPLIT-VLM reproduction: avg relative accuracy vs token budget (LLaVA-1.5-7B)",
                          xaxis_title="retained vision tokens", yaxis_title="avg relative accuracy (%)",
                          template="plotly_white")
        fig.write_html("outputs/relative_accuracy.html", include_plotlyjs="cdn")
        print("wrote outputs/relative_accuracy.html")
    except Exception as e:
        print("plotly skipped:", e)
    print("wrote outputs/aggregate.json, outputs/aggregate.csv")


if __name__ == "__main__":
    main()