File size: 7,056 Bytes
510314e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Grafici della corsa di conferma: PNG + un HTML autonomo (SVG in linea, nessuna dipendenza esterna).
Uso: ~/.hermes/cache/scratch/mpl-venv/bin/python analysis/charts.py   (matplotlib solo per disegnare)"""
import io
import json
from pathlib import Path

import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt  # noqa: E402

import stats as S  # noqa: E402

OUT = Path(__file__).resolve().parents[1] / "charts"
OUT.mkdir(exist_ok=True)
A = Path(__file__).resolve().parent
summ = json.load(open(A / "summary.json"))
xsum = json.load(open(A / "extra.json"))
POLS = ["A", "D", "B", "T"]
NAMES = {"A": "full window", "D": "mnemonic-proxy", "B": "summary (LLM compaction)", "T": "truncation"}
COL = {"A": "#7f7f7f", "D": "#1f77b4", "B": "#ff7f0e", "T": "#2ca02c"}
SVGS = {}
LAB = {"unite": "64k + 128k pooled"}


def save(fig, name):
    fig.savefig(OUT / (name + ".png"), dpi=130, bbox_inches="tight")
    buf = io.StringIO()
    fig.savefig(buf, format="svg", bbox_inches="tight")
    s = buf.getvalue()
    SVGS[name] = s[s.index("<svg"):]
    plt.close(fig)


# 1. corrette per politica e lunghezza, IC 95% Wilson
def bars(data, title, name, groups, ylabel="fully correct (official score = 1), %"):
    fig, ax = plt.subplots(figsize=(8, 4.2))
    w = 0.2
    for k, p in enumerate(POLS):
        xs, ys, lo, hi = [], [], [], []
        for g, key in enumerate(groups):
            x, n = data[key][p]
            l, u = S.wilson(x, n)
            xs.append(g + (k - 1.5) * w)
            ys.append(100 * x / n)
            lo.append(100 * (x / n - l))
            hi.append(100 * (u - x / n))
        ax.bar(xs, ys, w, color=COL[p], label=NAMES[p], yerr=[lo, hi], capsize=3, error_kw={"lw": 1})
        for xx, yy in zip(xs, ys):
            ax.text(xx, 2, f"{yy:.0f}", ha="center", va="bottom", fontsize=7, color="white")
    ax.set_xticks(range(len(groups)))
    ax.set_xticklabels([f"{LAB.get(g, g)} (n={data[g]['A'][1]})" for g in groups])
    ax.set_ylim(0, 100)
    ax.set_ylabel(ylabel)
    ax.set_title(title, fontsize=10)
    ax.legend(fontsize=8, ncol=4, loc="upper center", bbox_to_anchor=(0.5, -0.1))
    ax.grid(axis="y", alpha=0.3)
    save(fig, name)


bars(summ["correct"]["off"], "Confirmation run. AgentLongBench kf-c tool_response, Qwen3.8 Flash Next IQ3_XXS,\n"
     "window 32K (full window: 80K / 160K). Error bars: 95% Wilson", "correct_by_policy", ["64k", "128k", "unite"])

# 1b. corsa principale (domanda ambigua) contro conferma (domanda con la nota), 64k + 128k
mvc = xsum["main_vs_confirm"]["unite"]
data = {"main run (ambiguous question)": {p: [mvc[p]["main"], mvc[p]["n"]] for p in POLS},
        "confirmation run (question + note)": {p: [mvc[p]["confirm"], mvc[p]["n"]] for p in POLS}}
bars(data, "Same 100 questions, same engine and settings. Only change: one sentence added to the question\n"
     "(64k + 128k pooled, error bars: 95% Wilson)", "main_vs_confirm",
     ["main run (ambiguous question)", "confirmation run (question + note)"])

# 2. tempo mediano per domanda
fig, ax = plt.subplots(figsize=(8, 4.2))
w = 0.2
for k, p in enumerate(POLS):
    for g, L in enumerate(["64k", "128k"]):
        c = summ["cost"][f"{L}/{p}"]
        x = g + (k - 1.5) * w
        ax.bar(x, c["prep_med"], w, color=COL[p], alpha=0.45, hatch="//", edgecolor="white")
        ax.bar(x, c["q_med"], w, bottom=c["prep_med"], color=COL[p], label=NAMES[p] if g == 0 else None)
        ax.text(x, c["prep_med"] + c["q_med"] + 3, f"{c['wall_med']:.0f}s", ha="center", fontsize=7)
from matplotlib.patches import Patch  # noqa: E402
ax.set_xticks([0, 1])
ax.set_xticklabels(["64k (~74K-token history)", "128k (~150K-token history)"])
ax.set_ylim(0, 330)
h, l = ax.get_legend_handles_labels()
h += [Patch(facecolor="#bbbbbb", hatch="//", edgecolor="white"), Patch(facecolor="#555555")]
l += ["preparation", "at question time"]
ax.set_ylabel("seconds per question (median)")
ax.set_title("Median time per question. Hatched = preparation (proxy: history replay through the proxy;\n"
             "summary: compactions). Solid = work at question time. Label = median end-to-end wall time.", fontsize=9)
ax.legend(h, l, fontsize=8, ncol=3, loc="upper center", bbox_to_anchor=(0.5, -0.1))
ax.grid(axis="y", alpha=0.3)
save(fig, "time_per_question")

# 3. matrice delle discordanze D/B
fig, axs = plt.subplots(1, 3, figsize=(10, 3.4), constrained_layout=True)
for ax, key in zip(axs, ["64k", "128k", "unite"]):
    c = summ["compare"]["main"][f"D-B/{key}"]
    m = [[c["a"], c["b"]], [c["c"], c["d"]]]
    for i in range(2):
        for j in range(2):
            ax.text(j, i, m[i][j], ha="center", va="center", fontsize=14,
                    color="white" if m[i][j] >= 20 else "black")
    ax.imshow(m, cmap="Blues", vmin=0, vmax=45)
    ax.set_xticks([0, 1])
    ax.set_xticklabels(["summary right", "summary wrong"])
    ax.set_yticks([0, 1])
    ax.set_yticklabels(["proxy right", "proxy wrong"])
    ax.set_title(f"{LAB.get(key, key)}: n = {c['n']}, McNemar exact p = {c['p_mcnemar']:.2g}", fontsize=9)
fig.suptitle("Primary comparison (confirmation run): mnemonic-proxy vs summary, paired", fontsize=10)
save(fig, "discordance_D_B")

# HTML autonomo
html = ["<!doctype html><html><head><meta charset='utf-8'><title>AgentLongBench confirmation run — mnemonic-proxy</title>",
        "<style>body{font-family:sans-serif;max-width:980px;margin:2em auto;color:#222}svg{max-width:100%;height:auto}"
        "table{border-collapse:collapse;font-size:13px}td,th{border:1px solid #ccc;padding:3px 7px;text-align:right}"
        "</style></head><body>",
        "<h1>AgentLongBench confirmation run (window 32K, 64k + 128k)</h1>",
        "<p>Qwen3.8 Flash Next IQ3_XXS on Strata 0.1.40, RTX 4070 Ti 12 GB, KV int8, seed 1. kf-c tool_response, "
        "Count Frequency + Find Duplicates, 25 + 25 questions per length, max_tokens 4,096. Full window = 81,920 / 163,840; "
        "mnemonic-proxy 0.3.5 (b8d4920), summary (LLM compaction, at most 2,048 tokens) and truncation at 32,768. "
        "Same questions as the main run plus one note that says which tool output \u201cround N\u201d refers to; "
        "official answers and scorer unchanged.</p>"]
html.append("<table><tr><th>set</th>" + "".join(f"<th>{NAMES[p]}</th>" for p in POLS) + "</tr>")
for key in ["64k", "128k", "unite"]:
    html.append(f"<tr><td>{LAB.get(key, key)}</td>" + "".join(
        f"<td>{summ['correct']['off'][key][p][0]}/{summ['correct']['off'][key][p][1]}</td>" for p in POLS) + "</tr>")
html.append("</table>")
for name, cap in (("correct_by_policy", "Fully correct answers per method and length."),
                  ("main_vs_confirm", "Main run vs confirmation run."),
                  ("discordance_D_B", "Primary comparison: mnemonic-proxy vs summary, paired."),
                  ("time_per_question", "Median time per question.")):
    html.append(f"<h2>{cap}</h2>")
    html.append(SVGS[name])
html.append("</body></html>")
(OUT / "confirm-charts.html").write_text("\n".join(html))
print("ok", sorted(p.name for p in OUT.iterdir()))