Ishan3141's picture
Upload 5 files
028b945 verified
Raw
History Blame Contribute Delete
12.2 kB
#!/usr/bin/env python3
"""Aggregate compiled APM benchmark outputs into summary CSVs and plots."""
from __future__ import annotations
import argparse
from pathlib import Path
from typing import Iterable
import pandas as pd
from apm_metrics import load_json_or_jsonl, normalize_bool
BOOL_COLUMNS = (
"asked_question",
"added_explanation",
"protocol_compliant",
"judge_hallucinated_additions",
"judge_asked_for_clarification",
"judge_added_extra_text",
"judge_language_match",
"judge_parse_error",
)
NUMERIC_COLUMNS = (
"alpha",
"B_raw",
"B_assist",
"BRS",
"question_marks",
"meta_phrase_hits",
"script_ratio",
"judge_intent_preservation",
"judge_hallucination_severity",
)
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"--compiled-root",
type=Path,
required=True,
help="Root containing <model>/<noise>/compiled.json files.",
)
parser.add_argument(
"--output-dir",
type=Path,
default=Path("benchmark_summaries"),
help="Directory where summary CSVs and optional plots will be written.",
)
parser.add_argument(
"--plots",
action="store_true",
help="Also write a small set of PNG plots. Requires matplotlib and seaborn.",
)
parser.add_argument(
"--write-combined",
action="store_true",
help="Write the full compiled table as compiled_results.csv.",
)
return parser.parse_args()
def compiled_paths(root: Path) -> Iterable[Path]:
return sorted(root.glob("*/*/compiled.json"))
def load_compiled(root: Path) -> pd.DataFrame:
rows = []
for path in compiled_paths(root):
model = path.parents[1].name
noise = path.parents[0].name
for row in load_json_or_jsonl(path):
row.setdefault("model", model)
row.setdefault("noise", noise)
rows.append(row)
if not rows:
raise SystemExit(f"No compiled.json files found under {root}")
return pd.DataFrame(rows)
def ensure_columns(df: pd.DataFrame, columns: Iterable[str], default) -> None:
for column in columns:
if column not in df.columns:
df[column] = default
def prepare_dataframe(df: pd.DataFrame) -> pd.DataFrame:
df = df.copy()
ensure_columns(df, BOOL_COLUMNS, False)
ensure_columns(df, NUMERIC_COLUMNS, 0)
ensure_columns(df, ("judge_overall_verdict", "example_id"), "")
for column in BOOL_COLUMNS:
df[column] = df[column].map(normalize_bool)
for column in NUMERIC_COLUMNS:
df[column] = pd.to_numeric(df[column], errors="coerce")
df["judge_hallucination_severity"] = df["judge_hallucination_severity"].fillna(0)
df["question_marks"] = df["question_marks"].fillna(0)
df["meta_phrase_hits"] = df["meta_phrase_hits"].fillna(0)
verdict = df["judge_overall_verdict"].fillna("").astype(str).str.lower()
has_verdict = verdict.ne("").any()
if has_verdict:
df["intent_preserved"] = verdict.isin({"pass", "borderline"})
else:
df["intent_preserved"] = df["judge_intent_preservation"] >= 4
df["hallucinated_mediation"] = (
df["judge_hallucinated_additions"]
| (df["judge_hallucination_severity"] > 0)
)
df["burden_inflation"] = (
df["asked_question"]
| df["added_explanation"]
| df["judge_asked_for_clarification"]
| df["judge_added_extra_text"]
| (df["question_marks"] > 0)
| (df["meta_phrase_hits"] > 0)
)
df["assistive_success"] = (
df["protocol_compliant"]
& df["intent_preserved"]
& (~df["hallucinated_mediation"])
& (~df["burden_inflation"])
)
df["false_robust"] = (
df["intent_preserved"]
& (df["hallucinated_mediation"] | df["burden_inflation"])
)
return df
def write_csv(df: pd.DataFrame, path: Path) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
df.to_csv(path, index=False)
print(f"Wrote {path}")
def write_summaries(df: pd.DataFrame, output_dir: Path, write_combined: bool) -> None:
if write_combined:
write_csv(df, output_dir / "compiled_results.csv")
sensitivity = (
df.groupby(["model", "language", "noise", "alpha"], dropna=False)
.agg(
intent_rate=("intent_preserved", "mean"),
success_rate=("assistive_success", "mean"),
hallucination_rate=("hallucinated_mediation", "mean"),
burden_rate=("burden_inflation", "mean"),
false_robust_rate=("false_robust", "mean"),
mean_brs=("BRS", "mean"),
n=("example_id", "count"),
)
.reset_index()
)
write_csv(sensitivity, output_dir / "apm_sensitivity_curves.csv")
tradeoff = (
df.groupby(["model", "language", "noise"], dropna=False)
.agg(
intent_rate=("intent_preserved", "mean"),
burden_rate=("burden_inflation", "mean"),
hallucination_rate=("hallucinated_mediation", "mean"),
false_robust_rate=("false_robust", "mean"),
mean_brs=("BRS", "mean"),
n=("example_id", "count"),
)
.reset_index()
)
write_csv(tradeoff, output_dir / "intent_burden_tradeoff.csv")
false_robust = (
df.groupby(["model", "noise"], dropna=False)
.agg(
false_robust_rate=("false_robust", "mean"),
hallucination_rate=("hallucinated_mediation", "mean"),
burden_rate=("burden_inflation", "mean"),
intent_rate=("intent_preserved", "mean"),
mean_brs=("BRS", "mean"),
n=("example_id", "count"),
)
.reset_index()
)
write_csv(false_robust, output_dir / "false_robustness_summary.csv")
language_noise = (
df.groupby(["language", "noise"], dropna=False)
.agg(
success_rate=("assistive_success", "mean"),
intent_rate=("intent_preserved", "mean"),
hallucination_rate=("hallucinated_mediation", "mean"),
burden_rate=("burden_inflation", "mean"),
false_robust_rate=("false_robust", "mean"),
mean_brs=("BRS", "mean"),
n=("example_id", "count"),
)
.reset_index()
)
write_csv(language_noise, output_dir / "language_noise_disparities.csv")
core = (
df.groupby(["model", "noise", "alpha", "language"], dropna=False)
.agg(
intent_preservation_score=("judge_intent_preservation", "mean"),
intent_preservation_rate=("intent_preserved", "mean"),
mean_brs=("BRS", "mean"),
brs_variance=("BRS", "var"),
protocol_compliance_rate=("protocol_compliant", "mean"),
n=("example_id", "count"),
)
.reset_index()
)
write_csv(core, output_dir / "core_metrics.csv")
hallucination = (
df.groupby(["model", "noise", "alpha", "language"], dropna=False)
.agg(
hallucination_incidence_rate=("judge_hallucinated_additions", "mean"),
hallucination_severity_index=("judge_hallucination_severity", "mean"),
overassist_rate=("judge_added_extra_text", "mean"),
n=("example_id", "count"),
)
.reset_index()
)
write_csv(hallucination, output_dir / "hallucination_metrics.csv")
clarification = (
df.groupby(["model", "noise", "alpha", "language"], dropna=False)
.agg(
clarification_rate=("judge_asked_for_clarification", "mean"),
n=("example_id", "count"),
)
.reset_index()
)
write_csv(clarification, output_dir / "clarification_metrics.csv")
brs_alpha = (
df.groupby(["noise", "alpha"], dropna=False)
.agg(mean_brs=("BRS", "mean"), n=("example_id", "count"))
.reset_index()
)
write_csv(brs_alpha, output_dir / "BRS_vs_alpha.csv")
brs_language_noise = (
df.groupby(["language", "noise"], dropna=False)
.agg(mean_brs=("BRS", "mean"), n=("example_id", "count"))
.reset_index()
)
write_csv(brs_language_noise, output_dir / "BRS_vs_language_noise.csv")
language_table = (
sensitivity.groupby("language", dropna=False)
.agg(
intent_rate=("intent_rate", "mean"),
success_rate=("success_rate", "mean"),
hallucination_rate=("hallucination_rate", "mean"),
burden_rate=("burden_rate", "mean"),
false_robust_rate=("false_robust_rate", "mean"),
n=("n", "sum"),
)
.reset_index()
.sort_values(["intent_rate", "hallucination_rate", "burden_rate"], ascending=[False, True, True])
)
write_csv(language_table, output_dir / "table_language_avg.csv")
model_table = (
sensitivity.groupby("model", dropna=False)
.agg(
intent_rate=("intent_rate", "mean"),
success_rate=("success_rate", "mean"),
hallucination_rate=("hallucination_rate", "mean"),
burden_rate=("burden_rate", "mean"),
false_robust_rate=("false_robust_rate", "mean"),
n=("n", "sum"),
)
.reset_index()
.sort_values(["intent_rate", "hallucination_rate", "burden_rate"], ascending=[False, True, True])
)
write_csv(model_table, output_dir / "table_model_avg.csv")
def write_plots(df: pd.DataFrame, output_dir: Path) -> None:
import matplotlib.pyplot as plt
plots_dir = output_dir / "plots"
plots_dir.mkdir(parents=True, exist_ok=True)
sensitivity = pd.read_csv(output_dir / "apm_sensitivity_curves.csv")
def plot_success_by(group_column: str, path: Path) -> None:
fig, ax = plt.subplots(figsize=(10, 6))
for label, group in sensitivity.groupby(group_column, dropna=False):
series = (
group.groupby("alpha", dropna=False)
.agg(success_rate=("success_rate", "mean"))
.reset_index()
.sort_values("alpha")
)
ax.plot(series["alpha"], series["success_rate"], marker="o", label=str(label))
ax.set_xlabel("Alpha")
ax.set_ylabel("Assistive success rate")
ax.grid(True, alpha=0.3)
ax.legend(loc="best", fontsize=8)
fig.tight_layout()
fig.savefig(path, dpi=300, bbox_inches="tight")
plt.close(fig)
print(f"Wrote {path}")
plot_success_by("model", plots_dir / "sensitivity_success_by_model.png")
plot_success_by("language", plots_dir / "sensitivity_success_by_language.png")
language_noise = pd.read_csv(output_dir / "language_noise_disparities.csv")
pivot = (
language_noise.pivot(index="language", columns="noise", values="false_robust_rate")
.sort_index()
.sort_index(axis=1)
)
fig, ax = plt.subplots(figsize=(8, 6))
image = ax.imshow(pivot.values, cmap="Reds", vmin=0, vmax=1)
ax.set_xticks(range(len(pivot.columns)))
ax.set_xticklabels(pivot.columns)
ax.set_yticks(range(len(pivot.index)))
ax.set_yticklabels(pivot.index)
ax.set_xlabel("Noise")
ax.set_ylabel("Language")
for row_index, language in enumerate(pivot.index):
for col_index, noise in enumerate(pivot.columns):
value = pivot.loc[language, noise]
if pd.notna(value):
ax.text(col_index, row_index, f"{value:.2f}", ha="center", va="center", fontsize=8)
fig.colorbar(image, ax=ax, label="False robustness rate")
fig.tight_layout()
path = plots_dir / "false_robust_heatmap.png"
fig.savefig(path, dpi=300, bbox_inches="tight")
plt.close(fig)
print(f"Wrote {path}")
def main() -> None:
args = parse_args()
df = prepare_dataframe(load_compiled(args.compiled_root))
args.output_dir.mkdir(parents=True, exist_ok=True)
write_summaries(df, args.output_dir, write_combined=args.write_combined)
if args.plots:
write_plots(df, args.output_dir)
print(f"Analyzed {len(df)} compiled rows")
if __name__ == "__main__":
main()