kpshinnik's picture
Upload folder using huggingface_hub
d4bcd5c verified
Raw
History Blame Contribute Delete
4.85 kB
"""
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()