File size: 12,756 Bytes
6c5f29f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Generate MemAudit paper figures from canonical artifacts.


The script is intentionally dependency-light: matplotlib plus the Python

standard library. It reads existing run summaries and writes vector PDF/SVG

figures to the figures/ directory.

"""

from __future__ import annotations

import argparse
import json
from pathlib import Path

import matplotlib.pyplot as plt
from matplotlib.patches import FancyArrowPatch, FancyBboxPatch, Rectangle


ROOT = Path(__file__).resolve().parents[1]
FIG_DIR = ROOT / "figures"

PALETTE = {
    "oracle": "#0072B2",
    "opt": "#111111",
    "full_raw": "#D55E00",
    "density": "#E69F00",
    "no_tombstone": "#CC79A7",
    "fact": "#009E73",
    "summary": "#B58900",
    "recency": "#7A7A7A",
    "fifo": "#7A7A7A",
    "light": "#F7F7F7",
    "mid": "#9ECAE1",
    "dark": "#08519C",
}

METHOD_LABELS = {
    "oracle_gvt": "MemAudit-GVT",
    "density_only": "Density-only",
    "no_tombstone_opt": "No-tombstone OPT",
    "fact_only": "Fact-only",
    "summary_only": "Summary-only",
    "recency_raw": "Recency raw",
    "dense_budgeted_bsc": "MemAudit + dense",
    "dense_rag_e5": "Full raw dense",
    "dense_budgeted_replay": "Budgeted raw replay",
    "fifo_replay": "FIFO",
}


def load_json(path: str | Path):
    return json.loads((ROOT / path).read_text(encoding="utf-8"))


def save(fig, name: str):
    FIG_DIR.mkdir(exist_ok=True)
    for ext in ("pdf", "svg"):
        fig.savefig(FIG_DIR / f"{name}.{ext}", bbox_inches="tight")
    plt.close(fig)


def style_axes(ax):
    ax.spines["top"].set_visible(False)
    ax.spines["right"].set_visible(False)
    ax.grid(axis="y", color="#E5E5E5", linewidth=0.8)
    ax.set_axisbelow(True)


def add_box(ax, xy, w, h, text, color, fontsize=9):
    box = FancyBboxPatch(
        xy,
        w,
        h,
        boxstyle="round,pad=0.02,rounding_size=0.03",
        linewidth=1.2,
        edgecolor=color,
        facecolor=color,
        alpha=0.12,
    )
    ax.add_patch(box)
    ax.text(xy[0] + w / 2, xy[1] + h / 2, text, ha="center", va="center", fontsize=fontsize)


def arrow(ax, p1, p2, color="#444444"):
    ax.add_patch(FancyArrowPatch(p1, p2, arrowstyle="->", mutation_scale=12, lw=1.2, color=color))


def pipeline_schematic():
    fig, ax = plt.subplots(figsize=(10, 3.1))
    ax.set_xlim(0, 10)
    ax.set_ylim(0, 3)
    ax.axis("off")
    ax.add_patch(Rectangle((0.2, 0.15), 9.6, 0.95, facecolor="#FCE8C8", edgecolor="none", alpha=0.7))
    ax.text(5, 0.9, "Hidden event graph -> evidence units -> future query requirements", ha="center", fontsize=9)

    xs = [0.35, 1.75, 3.15, 4.55, 5.95, 7.35, 8.75]
    labels = [
        "Experience\nstream",
        "Candidate\nrepresentations",
        "Budgeted\nwriter",
        "Memory\nstore X",
        "Exact oracle\nF(X) / OPT",
        "Retriever",
        "Reader\nanswers",
    ]
    colors = ["#7A7A7A", "#CC79A7", "#0072B2", "#0072B2", "#111111", "#009E73", "#009E73"]
    for x, label, color in zip(xs, labels, colors):
        add_box(ax, (x, 1.65), 1.0, 0.7, label, color)
    for x1, x2 in zip(xs[:-1], xs[1:]):
        arrow(ax, (x1 + 1.02, 2.0), (x2 - 0.05, 2.0))
    ax.text(1.75, 1.38, "discard / raw / fact / summary / tombstone / compound", ha="center", fontsize=7)
    ax.text(5.95, 1.38, "computed before retrieval and reader reasoning", ha="center", fontsize=7)
    save(fig, "pipeline_schematic")


def tombstone_timeline():
    fig, ax = plt.subplots(figsize=(8, 2.8))
    ax.set_xlim(0, 10)
    ax.set_ylim(0, 3)
    ax.axis("off")
    ax.plot([1, 9], [2.35, 2.35], color="#444444", lw=1.5)
    for x, label in [(2, "t1"), (6, "t2"), (8.7, "future query")]:
        ax.plot([x, x], [2.25, 2.45], color="#444444", lw=1)
        ax.text(x, 2.58, label, ha="center", fontsize=8)
    ax.text(2, 2.0, '"I prefer vegetarian\nmeals for travel."', ha="center", fontsize=8)
    ax.text(6, 2.0, '"Actually, I am\npescatarian now."', ha="center", fontsize=8)
    ax.text(8.7, 2.0, "What meals\nshould we book?", ha="center", fontsize=8)

    add_box(ax, (0.7, 0.85), 2.0, 0.55, "Old fact:\ntravel = vegetarian", "#D55E00", fontsize=8)
    ax.plot([0.9, 2.5], [1.12, 1.12], color="#D55E00", lw=2)
    add_box(ax, (3.4, 0.85), 2.0, 0.55, "Current fact:\ntravel = pescatarian", "#009E73", fontsize=8)
    add_box(ax, (6.1, 0.85), 2.4, 0.55, "Tombstone:\nvegetarian invalid after t2", "#CC79A7", fontsize=8)
    arrow(ax, (5.45, 1.12), (6.05, 1.12), "#444444")
    ax.text(5, 0.35, "Compound update stores the new current fact plus the invalidation record.", ha="center", fontsize=9)
    save(fig, "tombstone_timeline")


def exact_budget_sweep():
    data = load_json("oraclemem_runs/exact_500/summary.json")
    rows = data["by_budget_method"]
    budgets = [2, 4, 8, 16]
    methods = ["oracle_gvt", "density_only", "no_tombstone_opt", "fact_only", "summary_only", "recency_raw"]
    colors = {
        "oracle_gvt": PALETTE["oracle"],
        "density_only": PALETTE["density"],
        "no_tombstone_opt": PALETTE["no_tombstone"],
        "fact_only": PALETTE["fact"],
        "summary_only": PALETTE["summary"],
        "recency_raw": PALETTE["recency"],
    }
    lookup = {(r["budget"], r["method"]): r for r in rows}
    fig, ax = plt.subplots(figsize=(6.5, 3.6))
    for method in methods:
        ys = [lookup[(b, method)]["mean_ratio_to_opt"] for b in budgets]
        lows = [lookup[(b, method)]["bootstrap95_ratio_to_opt_low"] for b in budgets]
        highs = [lookup[(b, method)]["bootstrap95_ratio_to_opt_high"] for b in budgets]
        ax.plot(budgets, ys, marker="o", lw=2, label=METHOD_LABELS[method], color=colors[method])
        ax.fill_between(budgets, lows, highs, color=colors[method], alpha=0.12, linewidth=0)
    ax.axhline(1.0, color=PALETTE["opt"], lw=1, ls="--", label="Exact OPT")
    ax.set_xlabel("Storage budget B")
    ax.set_ylabel("Ratio to exact OPT")
    ax.set_ylim(-0.02, 1.05)
    ax.set_xticks(budgets)
    style_axes(ax)
    ax.legend(ncol=2, fontsize=8, frameon=False)
    save(fig, "exact_budget_sweep")


def stress_heatmap_and_gap():
    data = load_json("oraclemem_runs/stress_exact_500/summary.json")
    rows = data["by_distribution_budget_method"]
    dists = ["base", "update_chain", "temporal_interval"]
    methods = ["oracle_gvt", "density_only", "no_tombstone_opt"]
    lookup = {(r["distribution"], r["budget"], r["method"]): r for r in rows}
    budget = 6
    vals = [[lookup[(d, budget, m)]["mean_ratio_to_opt"] for d in dists] for m in methods]

    fig, ax = plt.subplots(figsize=(5.8, 3.0))
    im = ax.imshow(vals, cmap="Blues", vmin=0, vmax=1)
    ax.set_xticks(range(len(dists)), ["Base", "Update\nchain", "Temporal\ninterval"])
    ax.set_yticks(range(len(methods)), [METHOD_LABELS[m] for m in methods])
    for i, row in enumerate(vals):
        for j, val in enumerate(row):
            ax.text(j, i, f"{val:.3f}", ha="center", va="center", fontsize=9, color="#111111")
    ax.set_title("Validity-heavy stress suite (B=6)", fontsize=10)
    fig.colorbar(im, ax=ax, fraction=0.046, pad=0.04, label="Ratio to OPT")
    save(fig, "stress_heatmap")

    gaps = [1.0 - lookup[(d, budget, "no_tombstone_opt")]["mean_ratio_to_opt"] for d in dists]
    fig, ax = plt.subplots(figsize=(5.2, 3.0))
    ax.bar(["Base", "Update\nchain", "Temporal\ninterval"], gaps, color=PALETTE["no_tombstone"], alpha=0.85)
    ax.set_ylabel("Full OPT - no-tombstone OPT")
    ax.set_ylim(0, max(gaps) * 1.25)
    style_axes(ax)
    for i, val in enumerate(gaps):
        ax.text(i, val + 0.015, f"{val:.3f}", ha="center", fontsize=9)
    save(fig, "validity_frontier_gap")


def longmemeval_retrieval():
    data = load_json("llm_memory_validation/longmemeval_focus_report_core4/summary.json")
    methods = ["dense_budgeted_bsc", "dense_rag_e5", "dense_budgeted_replay", "fifo_replay"]
    colors = {
        "dense_budgeted_bsc": PALETTE["oracle"],
        "dense_rag_e5": PALETTE["full_raw"],
        "dense_budgeted_replay": PALETTE["density"],
        "fifo_replay": PALETTE["fifo"],
    }
    ks = [1, 3, 5]
    fig, ax = plt.subplots(figsize=(6.0, 3.4))
    for method in methods:
        metrics = data["metrics"][method]
        ys = [metrics[f"focus_recall_at_{k}"] for k in ks]
        ax.plot(ks, ys, marker="o", lw=2, label=METHOD_LABELS[method], color=colors[method])
    ax.set_xlabel("k")
    ax.set_ylabel("Focus recall@k")
    ax.set_ylim(0, 1.02)
    ax.set_xticks(ks)
    style_axes(ax)
    ax.legend(fontsize=8, frameon=False, loc="lower right")
    save(fig, "longmemeval_retrieval_rk")


def gpt55_reader_bars():
    data = load_json("llm_memory_validation/longmemeval_reader_api_gpt55_answer_supported_focus_full/summary.json")
    methods = ["dense_budgeted_bsc", "dense_rag_e5", "dense_budgeted_replay", "fifo_replay"]
    labels = [METHOD_LABELS[m] for m in methods]
    metrics = [
        ("token_f1", "Token F1", True),
        ("evidence_use", "Evidence use", True),
        ("insufficient_evidence_rate", "Insufficient", False),
    ]
    colors = [PALETTE["oracle"], PALETTE["full_raw"], PALETTE["density"], PALETTE["fifo"]]
    fig, axes = plt.subplots(1, 3, figsize=(9.8, 3.2), sharey=True)
    for ax, (key, title, _) in zip(axes, metrics):
        vals = [data["metrics"][m]["focus"][key] for m in methods]
        ax.bar(range(len(methods)), vals, color=colors, alpha=0.9)
        ax.set_title(title, fontsize=10)
        ax.set_xticks(range(len(methods)), labels, rotation=35, ha="right", fontsize=7)
        ax.set_ylim(0, 1.0)
        style_axes(ax)
    axes[0].set_ylabel("Rate")
    save(fig, "gpt55_reader_bars")


def conditional_failure_audit():
    data = load_json("llm_memory_validation/longmemeval_reader_api_gpt55_answer_supported_focus_full/failure_bucket_counts.json")
    methods = ["dense_budgeted_bsc", "dense_rag_e5", "dense_budgeted_replay", "fifo_replay"]
    buckets = [
        ("missing_gold_evidence", "Missing evidence", "#D55E00"),
        ("abstained_despite_gold", "Abstained despite support", "#E69F00"),
        ("scoring_mismatch_possible", "Scoring mismatch possible", "#9ECAE1"),
        ("used_gold_but_wrong", "Wrong extraction", "#CC79A7"),
        ("unsupported_answer", "Unsupported", "#7A7A7A"),
        ("parse_failure", "Parse", "#111111"),
    ]
    fig, ax = plt.subplots(figsize=(7.2, 3.8))
    bottoms = [0.0] * len(methods)
    for bucket, label, color in buckets:
        vals = []
        for m in methods:
            row = data["by_method"][m]
            vals.append(row["outcome_counts"].get(bucket, 0) / row["n"])
        ax.bar(range(len(methods)), vals, bottom=bottoms, label=label, color=color, alpha=0.9)
        bottoms = [b + v for b, v in zip(bottoms, vals)]
    ax.set_xticks(range(len(methods)), [METHOD_LABELS[m] for m in methods], rotation=25, ha="right", fontsize=8)
    ax.set_ylabel("Share of focus questions")
    ax.set_ylim(0, 1.0)
    style_axes(ax)
    ax.legend(fontsize=7, frameon=False, ncol=2, loc="upper right")
    save(fig, "conditional_failure_audit")


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--dry-run", action="store_true", help="Print inputs/outputs without generating figures.")
    args = parser.parse_args()
    inputs = [
        "oraclemem_runs/exact_500/summary.json",
        "oraclemem_runs/stress_exact_500/summary.json",
        "llm_memory_validation/longmemeval_focus_report_core4/summary.json",
        "llm_memory_validation/longmemeval_reader_api_gpt55_answer_supported_focus_full/summary.json",
        "llm_memory_validation/longmemeval_reader_api_gpt55_answer_supported_focus_full/failure_bucket_counts.json",
    ]
    outputs = [
        "pipeline_schematic",
        "tombstone_timeline",
        "exact_budget_sweep",
        "stress_heatmap",
        "validity_frontier_gap",
        "longmemeval_retrieval_rk",
        "gpt55_reader_bars",
        "conditional_failure_audit",
    ]
    if args.dry_run:
        print("Inputs:")
        for item in inputs:
            print(f"  {item}")
        print("Outputs:")
        for item in outputs:
            print(f"  figures/{item}.pdf")
            print(f"  figures/{item}.svg")
        return

    pipeline_schematic()
    tombstone_timeline()
    exact_budget_sweep()
    stress_heatmap_and_gap()
    longmemeval_retrieval()
    gpt55_reader_bars()
    conditional_failure_audit()
    print(f"Wrote {len(outputs) * 2} vector figures to {FIG_DIR}")


if __name__ == "__main__":
    main()