Visualize Run¶
Loads a completed harness run directory and renders the paper-ready figures for that run. Companion to qualification.ipynb (which holds the methodology + LaTeX equations); this notebook is for plots only.
1. Configure¶
In [ ]:
Copied!
from pathlib import Path
import csv
import json
import re
# Edit RUN_DIR to point at any completed local run.
RUN_DIR = Path('runs/cmmd_20260429T070616Z')
RECORDS_PATH = RUN_DIR / 'records.jsonl'
SUMMARY_PATH = RUN_DIR / 'summary.csv'
TOP3_PATH = RUN_DIR / 'top3.md'
FIGURES_DIR = Path('notebooks/figures'); FIGURES_DIR.mkdir(parents=True, exist_ok=True)
for p in [RECORDS_PATH, SUMMARY_PATH, TOP3_PATH]:
assert p.exists(), f'missing artifact: {p}'
print(f'Loading run: {RUN_DIR}')
from pathlib import Path
import csv
import json
import re
# Edit RUN_DIR to point at any completed local run.
RUN_DIR = Path('runs/cmmd_20260429T070616Z')
RECORDS_PATH = RUN_DIR / 'records.jsonl'
SUMMARY_PATH = RUN_DIR / 'summary.csv'
TOP3_PATH = RUN_DIR / 'top3.md'
FIGURES_DIR = Path('notebooks/figures'); FIGURES_DIR.mkdir(parents=True, exist_ok=True)
for p in [RECORDS_PATH, SUMMARY_PATH, TOP3_PATH]:
assert p.exists(), f'missing artifact: {p}'
print(f'Loading run: {RUN_DIR}')
2. Apply paper style¶
Single-column width, colorblind-safe palette, B&W-distinguishable markers.
In [ ]:
Copied!
from recall_guard.harness import configure_paper_style
configure_paper_style()
from recall_guard.harness import configure_paper_style
configure_paper_style()
3. Reconstruct dataclasses from on-disk artifacts¶
The harness writes primitive types to JSONL / CSV; the plot helpers want frozen
dataclasses. The cell below rebuilds Record, CIBound, ModelEvalResult, and
CompositeScore instances from the run files.
In [ ]:
Copied!
from recall_guard.harness import Record, CIBound, ModelEvalResult, CompositeScore
from recall_guard.mia import MiaFeatures
def _load_records(path: Path) -> dict[str, list[Record]]:
by_model: dict[str, list[Record]] = {}
with path.open() as f:
for line in f:
row = json.loads(line)
feats = MiaFeatures(**row['features_raw']) if row.get('features_raw') else None
rec = Record(
model=row['model'],
prompt_hash=row['prompt_hash'],
parse_ok=row['parse_ok'],
predicted_direction=row['predicted_direction'],
raw_confidence=row['raw_confidence'],
penalized_confidence=row['penalized_confidence'],
target_direction=row['target_direction'],
features_raw=feats,
features_standardised=row.get('features_standardised') or {},
p_memorized=row.get('p_memorized'),
fail_reason=row.get('fail_reason'),
)
by_model.setdefault(rec.model, []).append(rec)
return by_model
def _f(s: str) -> float:
return float(s) if s not in ('', None) else 0.0
def _load_summary(path: Path):
results: list[ModelEvalResult] = []
majority: CIBound | None = None
raw_rows: list[dict] = []
with path.open() as f:
for row in csv.DictReader(f):
raw_rows.append(row)
return raw_rows
records_by_model = _load_records(RECORDS_PATH)
summary_rows = _load_summary(SUMMARY_PATH)
results: list[ModelEvalResult] = []
scores: list[CompositeScore] = []
majority: CIBound | None = None
for row in summary_rows:
name = row['model']
if name == '__majority_baseline__':
majority = CIBound(_f(row['raw_acc_point']), _f(row['raw_acc_lo']), _f(row['raw_acc_hi']))
continue
raw_acc = CIBound(_f(row['raw_acc_point']), _f(row['raw_acc_lo']), _f(row['raw_acc_hi']))
mg_acc = CIBound(_f(row['memguard_acc_point']), _f(row['memguard_acc_lo']), _f(row['memguard_acc_hi']))
auc = CIBound(_f(row['mcs_auc_point']), _f(row['mcs_auc_lo']), _f(row['mcs_auc_hi']))
parse = _f(row['parse_success_rate'])
pf = int(row['parse_failures']) if row['parse_failures'] not in ('', None) else 0
warns = [w for w in (row['warnings'] or '').split(',') if w.strip()]
recs = records_by_model.get(name, [])
results.append(ModelEvalResult(
model=name, raw_accuracy=raw_acc, memguard_accuracy=mg_acc,
mcs_auc=auc, parse_success_rate=parse, parse_failures=pf,
warnings=warns, records=recs,
))
scores.append(CompositeScore(
model=name,
score=_f(row['score']),
components={'memguard_acc_lo': mg_acc.lo, 'mcs_auc_point': auc.point, 'parse_success_rate': parse},
survives_gates=(row['survives_gates'].lower() == 'true'),
warnings=warns,
))
assert majority is not None, '__majority_baseline__ row missing from summary.csv'
print(f'Loaded {len(results)} models with {sum(len(r.records) for r in results)} records total.')
print(f'Majority baseline: point={majority.point:.3f} CI=[{majority.lo:.3f}, {majority.hi:.3f}]')
from recall_guard.harness import Record, CIBound, ModelEvalResult, CompositeScore
from recall_guard.mia import MiaFeatures
def _load_records(path: Path) -> dict[str, list[Record]]:
by_model: dict[str, list[Record]] = {}
with path.open() as f:
for line in f:
row = json.loads(line)
feats = MiaFeatures(**row['features_raw']) if row.get('features_raw') else None
rec = Record(
model=row['model'],
prompt_hash=row['prompt_hash'],
parse_ok=row['parse_ok'],
predicted_direction=row['predicted_direction'],
raw_confidence=row['raw_confidence'],
penalized_confidence=row['penalized_confidence'],
target_direction=row['target_direction'],
features_raw=feats,
features_standardised=row.get('features_standardised') or {},
p_memorized=row.get('p_memorized'),
fail_reason=row.get('fail_reason'),
)
by_model.setdefault(rec.model, []).append(rec)
return by_model
def _f(s: str) -> float:
return float(s) if s not in ('', None) else 0.0
def _load_summary(path: Path):
results: list[ModelEvalResult] = []
majority: CIBound | None = None
raw_rows: list[dict] = []
with path.open() as f:
for row in csv.DictReader(f):
raw_rows.append(row)
return raw_rows
records_by_model = _load_records(RECORDS_PATH)
summary_rows = _load_summary(SUMMARY_PATH)
results: list[ModelEvalResult] = []
scores: list[CompositeScore] = []
majority: CIBound | None = None
for row in summary_rows:
name = row['model']
if name == '__majority_baseline__':
majority = CIBound(_f(row['raw_acc_point']), _f(row['raw_acc_lo']), _f(row['raw_acc_hi']))
continue
raw_acc = CIBound(_f(row['raw_acc_point']), _f(row['raw_acc_lo']), _f(row['raw_acc_hi']))
mg_acc = CIBound(_f(row['memguard_acc_point']), _f(row['memguard_acc_lo']), _f(row['memguard_acc_hi']))
auc = CIBound(_f(row['mcs_auc_point']), _f(row['mcs_auc_lo']), _f(row['mcs_auc_hi']))
parse = _f(row['parse_success_rate'])
pf = int(row['parse_failures']) if row['parse_failures'] not in ('', None) else 0
warns = [w for w in (row['warnings'] or '').split(',') if w.strip()]
recs = records_by_model.get(name, [])
results.append(ModelEvalResult(
model=name, raw_accuracy=raw_acc, memguard_accuracy=mg_acc,
mcs_auc=auc, parse_success_rate=parse, parse_failures=pf,
warnings=warns, records=recs,
))
scores.append(CompositeScore(
model=name,
score=_f(row['score']),
components={'memguard_acc_lo': mg_acc.lo, 'mcs_auc_point': auc.point, 'parse_success_rate': parse},
survives_gates=(row['survives_gates'].lower() == 'true'),
warnings=warns,
))
assert majority is not None, '__majority_baseline__ row missing from summary.csv'
print(f'Loaded {len(results)} models with {sum(len(r.records) for r in results)} records total.')
print(f'Majority baseline: point={majority.point:.3f} CI=[{majority.lo:.3f}, {majority.hi:.3f}]')
4. Top-3 narrative¶
In [ ]:
Copied!
from IPython.display import Markdown, display
display(Markdown(TOP3_PATH.read_text()))
from IPython.display import Markdown, display
display(Markdown(TOP3_PATH.read_text()))
5. Figure: Accuracy with bootstrap 95% CI vs majority baseline¶
In [ ]:
Copied!
from recall_guard.harness import plot_accuracy_with_ci
fig = plot_accuracy_with_ci(results, majority)
fig.savefig(FIGURES_DIR / 'accuracy_ci.pdf')
fig
from recall_guard.harness import plot_accuracy_with_ci
fig = plot_accuracy_with_ci(results, majority)
fig.savefig(FIGURES_DIR / 'accuracy_ci.pdf')
fig
6. Figure: MCS-AUC with bootstrap 95% CI¶
In [ ]:
Copied!
from recall_guard.harness import plot_mcs_auc_with_ci
fig = plot_mcs_auc_with_ci(results)
fig.savefig(FIGURES_DIR / 'mcs_auc_ci.pdf')
fig
from recall_guard.harness import plot_mcs_auc_with_ci
fig = plot_mcs_auc_with_ci(results)
fig.savefig(FIGURES_DIR / 'mcs_auc_ci.pdf')
fig
7. Figure: Composite ranking¶
In [ ]:
Copied!
from recall_guard.harness import plot_composite_ranking
fig = plot_composite_ranking(scores)
fig.savefig(FIGURES_DIR / 'composite_ranking.pdf')
fig
from recall_guard.harness import plot_composite_ranking
fig = plot_composite_ranking(scores)
fig.savefig(FIGURES_DIR / 'composite_ranking.pdf')
fig
8. Saved figures¶
All three are written to notebooks/figures/*.pdf at single-column width for direct inclusion in a two-column manuscript.
In [ ]:
Copied!
for p in sorted(FIGURES_DIR.glob('*.pdf')):
print(p, p.stat().st_size, 'bytes')
for p in sorted(FIGURES_DIR.glob('*.pdf')):
print(p, p.stat().st_size, 'bytes')