memaudit-code / scripts /make_figures.py
edgeclustr's picture
Upload MemAudit code artifacts
6c5f29f verified
"""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()