Datasets:
Upload 5 files
Browse files- scripts/analyze_results.py +367 -0
- scripts/apm_metrics.py +217 -0
- scripts/compile_results.py +154 -0
- scripts/evaluate_outputs.py +133 -0
- scripts/prepare_inference_inputs.py +141 -0
scripts/analyze_results.py
ADDED
|
@@ -0,0 +1,367 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Aggregate compiled APM benchmark outputs into summary CSVs and plots."""
|
| 3 |
+
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
import argparse
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
from typing import Iterable
|
| 9 |
+
|
| 10 |
+
import pandas as pd
|
| 11 |
+
|
| 12 |
+
from apm_metrics import load_json_or_jsonl, normalize_bool
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
BOOL_COLUMNS = (
|
| 16 |
+
"asked_question",
|
| 17 |
+
"added_explanation",
|
| 18 |
+
"protocol_compliant",
|
| 19 |
+
"judge_hallucinated_additions",
|
| 20 |
+
"judge_asked_for_clarification",
|
| 21 |
+
"judge_added_extra_text",
|
| 22 |
+
"judge_language_match",
|
| 23 |
+
"judge_parse_error",
|
| 24 |
+
)
|
| 25 |
+
|
| 26 |
+
NUMERIC_COLUMNS = (
|
| 27 |
+
"alpha",
|
| 28 |
+
"B_raw",
|
| 29 |
+
"B_assist",
|
| 30 |
+
"BRS",
|
| 31 |
+
"question_marks",
|
| 32 |
+
"meta_phrase_hits",
|
| 33 |
+
"script_ratio",
|
| 34 |
+
"judge_intent_preservation",
|
| 35 |
+
"judge_hallucination_severity",
|
| 36 |
+
)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def parse_args() -> argparse.Namespace:
|
| 40 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 41 |
+
parser.add_argument(
|
| 42 |
+
"--compiled-root",
|
| 43 |
+
type=Path,
|
| 44 |
+
required=True,
|
| 45 |
+
help="Root containing <model>/<noise>/compiled.json files.",
|
| 46 |
+
)
|
| 47 |
+
parser.add_argument(
|
| 48 |
+
"--output-dir",
|
| 49 |
+
type=Path,
|
| 50 |
+
default=Path("benchmark_summaries"),
|
| 51 |
+
help="Directory where summary CSVs and optional plots will be written.",
|
| 52 |
+
)
|
| 53 |
+
parser.add_argument(
|
| 54 |
+
"--plots",
|
| 55 |
+
action="store_true",
|
| 56 |
+
help="Also write a small set of PNG plots. Requires matplotlib and seaborn.",
|
| 57 |
+
)
|
| 58 |
+
parser.add_argument(
|
| 59 |
+
"--write-combined",
|
| 60 |
+
action="store_true",
|
| 61 |
+
help="Write the full compiled table as compiled_results.csv.",
|
| 62 |
+
)
|
| 63 |
+
return parser.parse_args()
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def compiled_paths(root: Path) -> Iterable[Path]:
|
| 67 |
+
return sorted(root.glob("*/*/compiled.json"))
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def load_compiled(root: Path) -> pd.DataFrame:
|
| 71 |
+
rows = []
|
| 72 |
+
for path in compiled_paths(root):
|
| 73 |
+
model = path.parents[1].name
|
| 74 |
+
noise = path.parents[0].name
|
| 75 |
+
for row in load_json_or_jsonl(path):
|
| 76 |
+
row.setdefault("model", model)
|
| 77 |
+
row.setdefault("noise", noise)
|
| 78 |
+
rows.append(row)
|
| 79 |
+
|
| 80 |
+
if not rows:
|
| 81 |
+
raise SystemExit(f"No compiled.json files found under {root}")
|
| 82 |
+
|
| 83 |
+
return pd.DataFrame(rows)
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def ensure_columns(df: pd.DataFrame, columns: Iterable[str], default) -> None:
|
| 87 |
+
for column in columns:
|
| 88 |
+
if column not in df.columns:
|
| 89 |
+
df[column] = default
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def prepare_dataframe(df: pd.DataFrame) -> pd.DataFrame:
|
| 93 |
+
df = df.copy()
|
| 94 |
+
|
| 95 |
+
ensure_columns(df, BOOL_COLUMNS, False)
|
| 96 |
+
ensure_columns(df, NUMERIC_COLUMNS, 0)
|
| 97 |
+
ensure_columns(df, ("judge_overall_verdict", "example_id"), "")
|
| 98 |
+
|
| 99 |
+
for column in BOOL_COLUMNS:
|
| 100 |
+
df[column] = df[column].map(normalize_bool)
|
| 101 |
+
|
| 102 |
+
for column in NUMERIC_COLUMNS:
|
| 103 |
+
df[column] = pd.to_numeric(df[column], errors="coerce")
|
| 104 |
+
|
| 105 |
+
df["judge_hallucination_severity"] = df["judge_hallucination_severity"].fillna(0)
|
| 106 |
+
df["question_marks"] = df["question_marks"].fillna(0)
|
| 107 |
+
df["meta_phrase_hits"] = df["meta_phrase_hits"].fillna(0)
|
| 108 |
+
|
| 109 |
+
verdict = df["judge_overall_verdict"].fillna("").astype(str).str.lower()
|
| 110 |
+
has_verdict = verdict.ne("").any()
|
| 111 |
+
if has_verdict:
|
| 112 |
+
df["intent_preserved"] = verdict.isin({"pass", "borderline"})
|
| 113 |
+
else:
|
| 114 |
+
df["intent_preserved"] = df["judge_intent_preservation"] >= 4
|
| 115 |
+
|
| 116 |
+
df["hallucinated_mediation"] = (
|
| 117 |
+
df["judge_hallucinated_additions"]
|
| 118 |
+
| (df["judge_hallucination_severity"] > 0)
|
| 119 |
+
)
|
| 120 |
+
|
| 121 |
+
df["burden_inflation"] = (
|
| 122 |
+
df["asked_question"]
|
| 123 |
+
| df["added_explanation"]
|
| 124 |
+
| df["judge_asked_for_clarification"]
|
| 125 |
+
| df["judge_added_extra_text"]
|
| 126 |
+
| (df["question_marks"] > 0)
|
| 127 |
+
| (df["meta_phrase_hits"] > 0)
|
| 128 |
+
)
|
| 129 |
+
|
| 130 |
+
df["assistive_success"] = (
|
| 131 |
+
df["protocol_compliant"]
|
| 132 |
+
& df["intent_preserved"]
|
| 133 |
+
& (~df["hallucinated_mediation"])
|
| 134 |
+
& (~df["burden_inflation"])
|
| 135 |
+
)
|
| 136 |
+
|
| 137 |
+
df["false_robust"] = (
|
| 138 |
+
df["intent_preserved"]
|
| 139 |
+
& (df["hallucinated_mediation"] | df["burden_inflation"])
|
| 140 |
+
)
|
| 141 |
+
|
| 142 |
+
return df
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
def write_csv(df: pd.DataFrame, path: Path) -> None:
|
| 146 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 147 |
+
df.to_csv(path, index=False)
|
| 148 |
+
print(f"Wrote {path}")
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def write_summaries(df: pd.DataFrame, output_dir: Path, write_combined: bool) -> None:
|
| 152 |
+
if write_combined:
|
| 153 |
+
write_csv(df, output_dir / "compiled_results.csv")
|
| 154 |
+
|
| 155 |
+
sensitivity = (
|
| 156 |
+
df.groupby(["model", "language", "noise", "alpha"], dropna=False)
|
| 157 |
+
.agg(
|
| 158 |
+
intent_rate=("intent_preserved", "mean"),
|
| 159 |
+
success_rate=("assistive_success", "mean"),
|
| 160 |
+
hallucination_rate=("hallucinated_mediation", "mean"),
|
| 161 |
+
burden_rate=("burden_inflation", "mean"),
|
| 162 |
+
false_robust_rate=("false_robust", "mean"),
|
| 163 |
+
mean_brs=("BRS", "mean"),
|
| 164 |
+
n=("example_id", "count"),
|
| 165 |
+
)
|
| 166 |
+
.reset_index()
|
| 167 |
+
)
|
| 168 |
+
write_csv(sensitivity, output_dir / "apm_sensitivity_curves.csv")
|
| 169 |
+
|
| 170 |
+
tradeoff = (
|
| 171 |
+
df.groupby(["model", "language", "noise"], dropna=False)
|
| 172 |
+
.agg(
|
| 173 |
+
intent_rate=("intent_preserved", "mean"),
|
| 174 |
+
burden_rate=("burden_inflation", "mean"),
|
| 175 |
+
hallucination_rate=("hallucinated_mediation", "mean"),
|
| 176 |
+
false_robust_rate=("false_robust", "mean"),
|
| 177 |
+
mean_brs=("BRS", "mean"),
|
| 178 |
+
n=("example_id", "count"),
|
| 179 |
+
)
|
| 180 |
+
.reset_index()
|
| 181 |
+
)
|
| 182 |
+
write_csv(tradeoff, output_dir / "intent_burden_tradeoff.csv")
|
| 183 |
+
|
| 184 |
+
false_robust = (
|
| 185 |
+
df.groupby(["model", "noise"], dropna=False)
|
| 186 |
+
.agg(
|
| 187 |
+
false_robust_rate=("false_robust", "mean"),
|
| 188 |
+
hallucination_rate=("hallucinated_mediation", "mean"),
|
| 189 |
+
burden_rate=("burden_inflation", "mean"),
|
| 190 |
+
intent_rate=("intent_preserved", "mean"),
|
| 191 |
+
mean_brs=("BRS", "mean"),
|
| 192 |
+
n=("example_id", "count"),
|
| 193 |
+
)
|
| 194 |
+
.reset_index()
|
| 195 |
+
)
|
| 196 |
+
write_csv(false_robust, output_dir / "false_robustness_summary.csv")
|
| 197 |
+
|
| 198 |
+
language_noise = (
|
| 199 |
+
df.groupby(["language", "noise"], dropna=False)
|
| 200 |
+
.agg(
|
| 201 |
+
success_rate=("assistive_success", "mean"),
|
| 202 |
+
intent_rate=("intent_preserved", "mean"),
|
| 203 |
+
hallucination_rate=("hallucinated_mediation", "mean"),
|
| 204 |
+
burden_rate=("burden_inflation", "mean"),
|
| 205 |
+
false_robust_rate=("false_robust", "mean"),
|
| 206 |
+
mean_brs=("BRS", "mean"),
|
| 207 |
+
n=("example_id", "count"),
|
| 208 |
+
)
|
| 209 |
+
.reset_index()
|
| 210 |
+
)
|
| 211 |
+
write_csv(language_noise, output_dir / "language_noise_disparities.csv")
|
| 212 |
+
|
| 213 |
+
core = (
|
| 214 |
+
df.groupby(["model", "noise", "alpha", "language"], dropna=False)
|
| 215 |
+
.agg(
|
| 216 |
+
intent_preservation_score=("judge_intent_preservation", "mean"),
|
| 217 |
+
intent_preservation_rate=("intent_preserved", "mean"),
|
| 218 |
+
mean_brs=("BRS", "mean"),
|
| 219 |
+
brs_variance=("BRS", "var"),
|
| 220 |
+
protocol_compliance_rate=("protocol_compliant", "mean"),
|
| 221 |
+
n=("example_id", "count"),
|
| 222 |
+
)
|
| 223 |
+
.reset_index()
|
| 224 |
+
)
|
| 225 |
+
write_csv(core, output_dir / "core_metrics.csv")
|
| 226 |
+
|
| 227 |
+
hallucination = (
|
| 228 |
+
df.groupby(["model", "noise", "alpha", "language"], dropna=False)
|
| 229 |
+
.agg(
|
| 230 |
+
hallucination_incidence_rate=("judge_hallucinated_additions", "mean"),
|
| 231 |
+
hallucination_severity_index=("judge_hallucination_severity", "mean"),
|
| 232 |
+
overassist_rate=("judge_added_extra_text", "mean"),
|
| 233 |
+
n=("example_id", "count"),
|
| 234 |
+
)
|
| 235 |
+
.reset_index()
|
| 236 |
+
)
|
| 237 |
+
write_csv(hallucination, output_dir / "hallucination_metrics.csv")
|
| 238 |
+
|
| 239 |
+
clarification = (
|
| 240 |
+
df.groupby(["model", "noise", "alpha", "language"], dropna=False)
|
| 241 |
+
.agg(
|
| 242 |
+
clarification_rate=("judge_asked_for_clarification", "mean"),
|
| 243 |
+
n=("example_id", "count"),
|
| 244 |
+
)
|
| 245 |
+
.reset_index()
|
| 246 |
+
)
|
| 247 |
+
write_csv(clarification, output_dir / "clarification_metrics.csv")
|
| 248 |
+
|
| 249 |
+
brs_alpha = (
|
| 250 |
+
df.groupby(["noise", "alpha"], dropna=False)
|
| 251 |
+
.agg(mean_brs=("BRS", "mean"), n=("example_id", "count"))
|
| 252 |
+
.reset_index()
|
| 253 |
+
)
|
| 254 |
+
write_csv(brs_alpha, output_dir / "BRS_vs_alpha.csv")
|
| 255 |
+
|
| 256 |
+
brs_language_noise = (
|
| 257 |
+
df.groupby(["language", "noise"], dropna=False)
|
| 258 |
+
.agg(mean_brs=("BRS", "mean"), n=("example_id", "count"))
|
| 259 |
+
.reset_index()
|
| 260 |
+
)
|
| 261 |
+
write_csv(brs_language_noise, output_dir / "BRS_vs_language_noise.csv")
|
| 262 |
+
|
| 263 |
+
language_table = (
|
| 264 |
+
sensitivity.groupby("language", dropna=False)
|
| 265 |
+
.agg(
|
| 266 |
+
intent_rate=("intent_rate", "mean"),
|
| 267 |
+
success_rate=("success_rate", "mean"),
|
| 268 |
+
hallucination_rate=("hallucination_rate", "mean"),
|
| 269 |
+
burden_rate=("burden_rate", "mean"),
|
| 270 |
+
false_robust_rate=("false_robust_rate", "mean"),
|
| 271 |
+
n=("n", "sum"),
|
| 272 |
+
)
|
| 273 |
+
.reset_index()
|
| 274 |
+
.sort_values(["intent_rate", "hallucination_rate", "burden_rate"], ascending=[False, True, True])
|
| 275 |
+
)
|
| 276 |
+
write_csv(language_table, output_dir / "table_language_avg.csv")
|
| 277 |
+
|
| 278 |
+
model_table = (
|
| 279 |
+
sensitivity.groupby("model", dropna=False)
|
| 280 |
+
.agg(
|
| 281 |
+
intent_rate=("intent_rate", "mean"),
|
| 282 |
+
success_rate=("success_rate", "mean"),
|
| 283 |
+
hallucination_rate=("hallucination_rate", "mean"),
|
| 284 |
+
burden_rate=("burden_rate", "mean"),
|
| 285 |
+
false_robust_rate=("false_robust_rate", "mean"),
|
| 286 |
+
n=("n", "sum"),
|
| 287 |
+
)
|
| 288 |
+
.reset_index()
|
| 289 |
+
.sort_values(["intent_rate", "hallucination_rate", "burden_rate"], ascending=[False, True, True])
|
| 290 |
+
)
|
| 291 |
+
write_csv(model_table, output_dir / "table_model_avg.csv")
|
| 292 |
+
|
| 293 |
+
|
| 294 |
+
def write_plots(df: pd.DataFrame, output_dir: Path) -> None:
|
| 295 |
+
import matplotlib.pyplot as plt
|
| 296 |
+
|
| 297 |
+
plots_dir = output_dir / "plots"
|
| 298 |
+
plots_dir.mkdir(parents=True, exist_ok=True)
|
| 299 |
+
|
| 300 |
+
sensitivity = pd.read_csv(output_dir / "apm_sensitivity_curves.csv")
|
| 301 |
+
|
| 302 |
+
def plot_success_by(group_column: str, path: Path) -> None:
|
| 303 |
+
fig, ax = plt.subplots(figsize=(10, 6))
|
| 304 |
+
for label, group in sensitivity.groupby(group_column, dropna=False):
|
| 305 |
+
series = (
|
| 306 |
+
group.groupby("alpha", dropna=False)
|
| 307 |
+
.agg(success_rate=("success_rate", "mean"))
|
| 308 |
+
.reset_index()
|
| 309 |
+
.sort_values("alpha")
|
| 310 |
+
)
|
| 311 |
+
ax.plot(series["alpha"], series["success_rate"], marker="o", label=str(label))
|
| 312 |
+
|
| 313 |
+
ax.set_xlabel("Alpha")
|
| 314 |
+
ax.set_ylabel("Assistive success rate")
|
| 315 |
+
ax.grid(True, alpha=0.3)
|
| 316 |
+
ax.legend(loc="best", fontsize=8)
|
| 317 |
+
fig.tight_layout()
|
| 318 |
+
fig.savefig(path, dpi=300, bbox_inches="tight")
|
| 319 |
+
plt.close(fig)
|
| 320 |
+
print(f"Wrote {path}")
|
| 321 |
+
|
| 322 |
+
plot_success_by("model", plots_dir / "sensitivity_success_by_model.png")
|
| 323 |
+
plot_success_by("language", plots_dir / "sensitivity_success_by_language.png")
|
| 324 |
+
|
| 325 |
+
language_noise = pd.read_csv(output_dir / "language_noise_disparities.csv")
|
| 326 |
+
pivot = (
|
| 327 |
+
language_noise.pivot(index="language", columns="noise", values="false_robust_rate")
|
| 328 |
+
.sort_index()
|
| 329 |
+
.sort_index(axis=1)
|
| 330 |
+
)
|
| 331 |
+
fig, ax = plt.subplots(figsize=(8, 6))
|
| 332 |
+
image = ax.imshow(pivot.values, cmap="Reds", vmin=0, vmax=1)
|
| 333 |
+
ax.set_xticks(range(len(pivot.columns)))
|
| 334 |
+
ax.set_xticklabels(pivot.columns)
|
| 335 |
+
ax.set_yticks(range(len(pivot.index)))
|
| 336 |
+
ax.set_yticklabels(pivot.index)
|
| 337 |
+
ax.set_xlabel("Noise")
|
| 338 |
+
ax.set_ylabel("Language")
|
| 339 |
+
|
| 340 |
+
for row_index, language in enumerate(pivot.index):
|
| 341 |
+
for col_index, noise in enumerate(pivot.columns):
|
| 342 |
+
value = pivot.loc[language, noise]
|
| 343 |
+
if pd.notna(value):
|
| 344 |
+
ax.text(col_index, row_index, f"{value:.2f}", ha="center", va="center", fontsize=8)
|
| 345 |
+
|
| 346 |
+
fig.colorbar(image, ax=ax, label="False robustness rate")
|
| 347 |
+
fig.tight_layout()
|
| 348 |
+
path = plots_dir / "false_robust_heatmap.png"
|
| 349 |
+
fig.savefig(path, dpi=300, bbox_inches="tight")
|
| 350 |
+
plt.close(fig)
|
| 351 |
+
print(f"Wrote {path}")
|
| 352 |
+
|
| 353 |
+
|
| 354 |
+
def main() -> None:
|
| 355 |
+
args = parse_args()
|
| 356 |
+
df = prepare_dataframe(load_compiled(args.compiled_root))
|
| 357 |
+
args.output_dir.mkdir(parents=True, exist_ok=True)
|
| 358 |
+
write_summaries(df, args.output_dir, write_combined=args.write_combined)
|
| 359 |
+
|
| 360 |
+
if args.plots:
|
| 361 |
+
write_plots(df, args.output_dir)
|
| 362 |
+
|
| 363 |
+
print(f"Analyzed {len(df)} compiled rows")
|
| 364 |
+
|
| 365 |
+
|
| 366 |
+
if __name__ == "__main__":
|
| 367 |
+
main()
|
scripts/apm_metrics.py
ADDED
|
@@ -0,0 +1,217 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Shared metric utilities for the Assistive Prompt Mediation benchmark."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import json
|
| 6 |
+
import math
|
| 7 |
+
import re
|
| 8 |
+
from collections import Counter
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
from typing import Any, Dict, List, Mapping, Optional
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
META_PATTERNS = [
|
| 14 |
+
r"\bAs an AI\b",
|
| 15 |
+
r"\bI (can|will|cannot|can't)\b",
|
| 16 |
+
r"\bSure[, ]",
|
| 17 |
+
r"\bHere(?: is|'s)\b",
|
| 18 |
+
r"\bLet me\b",
|
| 19 |
+
]
|
| 20 |
+
|
| 21 |
+
ASSISTED_TEXT_FIELDS = (
|
| 22 |
+
"model_response",
|
| 23 |
+
"response",
|
| 24 |
+
"assistant_response",
|
| 25 |
+
"assist_prompt",
|
| 26 |
+
"assisted_prompt",
|
| 27 |
+
"mediated_prompt",
|
| 28 |
+
"output",
|
| 29 |
+
)
|
| 30 |
+
|
| 31 |
+
RAW_PROMPT_FIELDS = (
|
| 32 |
+
"noisy_prompt",
|
| 33 |
+
"input_prompt",
|
| 34 |
+
"prompt",
|
| 35 |
+
"user_prompt",
|
| 36 |
+
)
|
| 37 |
+
|
| 38 |
+
CHINESE_LANGUAGE_CODES = {"cn", "zh", "zh-cn", "zh_hans", "zh-hans"}
|
| 39 |
+
CJK_REGEX = re.compile(r"[\u4e00-\u9fff]")
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def load_json_or_jsonl(path: str | Path) -> List[Dict[str, Any]]:
|
| 43 |
+
"""Load a JSON array or JSONL file as a list of dictionaries."""
|
| 44 |
+
|
| 45 |
+
path = Path(path)
|
| 46 |
+
with path.open("r", encoding="utf-8") as f:
|
| 47 |
+
first_char = f.read(1)
|
| 48 |
+
f.seek(0)
|
| 49 |
+
if not first_char:
|
| 50 |
+
return []
|
| 51 |
+
if first_char == "[":
|
| 52 |
+
data = json.load(f)
|
| 53 |
+
if not isinstance(data, list):
|
| 54 |
+
raise ValueError(f"{path} must contain a JSON array")
|
| 55 |
+
return data
|
| 56 |
+
return [json.loads(line) for line in f if line.strip()]
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def write_json(data: Any, path: str | Path) -> None:
|
| 60 |
+
"""Write JSON with stable UTF-8 formatting."""
|
| 61 |
+
|
| 62 |
+
path = Path(path)
|
| 63 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 64 |
+
with path.open("w", encoding="utf-8") as f:
|
| 65 |
+
json.dump(data, f, ensure_ascii=False, indent=2)
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def entropy(text: str) -> float:
|
| 69 |
+
"""Character-level Shannon entropy used by the structural burden score."""
|
| 70 |
+
|
| 71 |
+
if not text:
|
| 72 |
+
return 0.0
|
| 73 |
+
|
| 74 |
+
counts = Counter(text)
|
| 75 |
+
total = sum(counts.values())
|
| 76 |
+
return -sum((count / total) * math.log2(count / total) for count in counts.values())
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def cognitive_burden(text: str) -> float:
|
| 80 |
+
"""Compute the structural cognitive burden proxy B(p)."""
|
| 81 |
+
|
| 82 |
+
tokens = re.findall(r"\w+|[^\w\s]", text)
|
| 83 |
+
length = len(tokens)
|
| 84 |
+
punctuation_density = sum(1 for token in tokens if re.match(r"[^\w\s]", token)) / max(length, 1)
|
| 85 |
+
|
| 86 |
+
return round(
|
| 87 |
+
0.4 * length
|
| 88 |
+
+ 0.3 * punctuation_density * 100
|
| 89 |
+
+ 0.3 * entropy(text) * 10,
|
| 90 |
+
3,
|
| 91 |
+
)
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def protocol_compliance(text: str) -> Dict[str, Any]:
|
| 95 |
+
"""Detect responses that ask questions or add meta/explanatory text."""
|
| 96 |
+
|
| 97 |
+
question_marks = text.count("?") + text.count("\uff1f")
|
| 98 |
+
meta_hits = sum(bool(re.search(pattern, text, re.IGNORECASE)) for pattern in META_PATTERNS)
|
| 99 |
+
|
| 100 |
+
asked_question = question_marks > 0
|
| 101 |
+
added_explanation = meta_hits > 0
|
| 102 |
+
|
| 103 |
+
return {
|
| 104 |
+
"asked_question": asked_question,
|
| 105 |
+
"added_explanation": added_explanation,
|
| 106 |
+
"protocol_compliant": not (asked_question or added_explanation),
|
| 107 |
+
"question_marks": question_marks,
|
| 108 |
+
"meta_phrase_hits": meta_hits,
|
| 109 |
+
}
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def language_script_match(text: str, language: Optional[str]) -> Dict[str, Any]:
|
| 113 |
+
"""Check whether Chinese outputs are mostly CJK characters.
|
| 114 |
+
|
| 115 |
+
Non-Chinese languages return null values because this lightweight diagnostic
|
| 116 |
+
is only defined for the Chinese-script condition used in the benchmark workflow.
|
| 117 |
+
"""
|
| 118 |
+
|
| 119 |
+
lang = (language or "").lower()
|
| 120 |
+
if lang not in CHINESE_LANGUAGE_CODES:
|
| 121 |
+
return {"script_match": None, "script_ratio": None}
|
| 122 |
+
|
| 123 |
+
chars = [char for char in text if char.strip()]
|
| 124 |
+
if not chars:
|
| 125 |
+
return {"script_match": False, "script_ratio": 0.0}
|
| 126 |
+
|
| 127 |
+
cjk_count = sum(bool(CJK_REGEX.match(char)) for char in chars)
|
| 128 |
+
ratio = cjk_count / len(chars)
|
| 129 |
+
return {"script_match": ratio >= 0.9, "script_ratio": round(ratio, 3)}
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def first_present(record: Mapping[str, Any], fields: tuple[str, ...]) -> Optional[str]:
|
| 133 |
+
"""Return the first non-empty string-like value from a set of fields."""
|
| 134 |
+
|
| 135 |
+
for field in fields:
|
| 136 |
+
value = record.get(field)
|
| 137 |
+
if value is None:
|
| 138 |
+
continue
|
| 139 |
+
value = str(value)
|
| 140 |
+
if value.strip():
|
| 141 |
+
return value
|
| 142 |
+
return None
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
def extract_assisted_text(record: Mapping[str, Any]) -> Optional[str]:
|
| 146 |
+
"""Extract a model's mediated/assisted prompt from common output fields."""
|
| 147 |
+
|
| 148 |
+
return first_present(record, ASSISTED_TEXT_FIELDS)
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def extract_raw_prompt(record: Mapping[str, Any]) -> Optional[str]:
|
| 152 |
+
"""Extract the noisy user prompt from common input fields."""
|
| 153 |
+
|
| 154 |
+
return first_present(record, RAW_PROMPT_FIELDS)
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
def compute_metrics(
|
| 158 |
+
record: Mapping[str, Any],
|
| 159 |
+
*,
|
| 160 |
+
model: Optional[str] = None,
|
| 161 |
+
noise: Optional[str] = None,
|
| 162 |
+
) -> Optional[Dict[str, Any]]:
|
| 163 |
+
"""Compute row-level APM benchmark metrics for one model output."""
|
| 164 |
+
|
| 165 |
+
raw_prompt = extract_raw_prompt(record)
|
| 166 |
+
assisted_text = extract_assisted_text(record)
|
| 167 |
+
if raw_prompt is None or assisted_text is None:
|
| 168 |
+
return None
|
| 169 |
+
|
| 170 |
+
b_raw = cognitive_burden(raw_prompt)
|
| 171 |
+
b_assist = cognitive_burden(assisted_text)
|
| 172 |
+
language = record.get("language")
|
| 173 |
+
|
| 174 |
+
row: Dict[str, Any] = {
|
| 175 |
+
"example_id": record.get("example_id"),
|
| 176 |
+
"model": record.get("model") or model,
|
| 177 |
+
"noise": record.get("noise") or noise,
|
| 178 |
+
"language": language,
|
| 179 |
+
"alpha": record.get("alpha"),
|
| 180 |
+
**protocol_compliance(assisted_text),
|
| 181 |
+
**language_script_match(assisted_text, language),
|
| 182 |
+
"B_raw": b_raw,
|
| 183 |
+
"B_assist": b_assist,
|
| 184 |
+
"BRS": round(b_raw - b_assist, 3),
|
| 185 |
+
}
|
| 186 |
+
return row
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
def flatten_judge_fields(record: Mapping[str, Any]) -> Dict[str, Any]:
|
| 190 |
+
"""Collect judge metrics, accepting nested or already-prefixed schemas."""
|
| 191 |
+
|
| 192 |
+
flattened: Dict[str, Any] = {}
|
| 193 |
+
|
| 194 |
+
judge = record.get("judge")
|
| 195 |
+
if isinstance(judge, Mapping):
|
| 196 |
+
for key, value in judge.items():
|
| 197 |
+
flattened[f"judge_{key}"] = value
|
| 198 |
+
|
| 199 |
+
for key, value in record.items():
|
| 200 |
+
if key.startswith("judge_"):
|
| 201 |
+
flattened[key] = value
|
| 202 |
+
|
| 203 |
+
return flattened
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
def normalize_bool(value: Any) -> bool:
|
| 207 |
+
"""Convert common serialized boolean values into Python booleans."""
|
| 208 |
+
|
| 209 |
+
if isinstance(value, bool):
|
| 210 |
+
return value
|
| 211 |
+
if value is None:
|
| 212 |
+
return False
|
| 213 |
+
if isinstance(value, (int, float)):
|
| 214 |
+
return bool(value)
|
| 215 |
+
if isinstance(value, str):
|
| 216 |
+
return value.strip().lower() in {"1", "true", "yes", "y", "pass"}
|
| 217 |
+
return bool(value)
|
scripts/compile_results.py
ADDED
|
@@ -0,0 +1,154 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Merge row-level metrics with judge annotations into compiled benchmark files."""
|
| 3 |
+
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
import argparse
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
from typing import Dict, Iterable, Iterator, Tuple
|
| 9 |
+
|
| 10 |
+
from apm_metrics import flatten_judge_fields, load_json_or_jsonl, write_json
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
TEXT_FIELDS = (
|
| 14 |
+
"clean_text",
|
| 15 |
+
"noisy_prompt",
|
| 16 |
+
"model_response",
|
| 17 |
+
"response",
|
| 18 |
+
"assisted_prompt",
|
| 19 |
+
"mediated_prompt",
|
| 20 |
+
)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def parse_args() -> argparse.Namespace:
|
| 24 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 25 |
+
parser.add_argument(
|
| 26 |
+
"--metrics-root",
|
| 27 |
+
type=Path,
|
| 28 |
+
required=True,
|
| 29 |
+
help="Root containing <model>/<noise>/metrics.json files.",
|
| 30 |
+
)
|
| 31 |
+
parser.add_argument(
|
| 32 |
+
"--judged-root",
|
| 33 |
+
type=Path,
|
| 34 |
+
required=True,
|
| 35 |
+
help="Root containing <model>/<noise>/results.jsonl files with judge annotations.",
|
| 36 |
+
)
|
| 37 |
+
parser.add_argument(
|
| 38 |
+
"--output-root",
|
| 39 |
+
type=Path,
|
| 40 |
+
default=Path("compiled"),
|
| 41 |
+
help="Directory where compiled JSON files will be written.",
|
| 42 |
+
)
|
| 43 |
+
parser.add_argument(
|
| 44 |
+
"--include-text-fields",
|
| 45 |
+
action="store_true",
|
| 46 |
+
help="Include source prompts and model responses when present.",
|
| 47 |
+
)
|
| 48 |
+
return parser.parse_args()
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def judged_file(noise_dir: Path) -> Path | None:
|
| 52 |
+
for preferred in ("results.jsonl", "results.json"):
|
| 53 |
+
path = noise_dir / preferred
|
| 54 |
+
if path.exists():
|
| 55 |
+
return path
|
| 56 |
+
|
| 57 |
+
candidates = sorted(
|
| 58 |
+
path for path in noise_dir.iterdir() if path.is_file() and path.suffix in {".json", ".jsonl"}
|
| 59 |
+
)
|
| 60 |
+
return candidates[0] if candidates else None
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def discover_judged(judged_root: Path) -> Iterator[Tuple[str, str, Path]]:
|
| 64 |
+
for model_dir in sorted(path for path in judged_root.iterdir() if path.is_dir()):
|
| 65 |
+
for noise_dir in sorted(path for path in model_dir.iterdir() if path.is_dir()):
|
| 66 |
+
path = judged_file(noise_dir)
|
| 67 |
+
if path is not None:
|
| 68 |
+
yield model_dir.name, noise_dir.name, path
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def compile_file(
|
| 72 |
+
*,
|
| 73 |
+
model: str,
|
| 74 |
+
noise: str,
|
| 75 |
+
metrics_path: Path,
|
| 76 |
+
judged_path: Path,
|
| 77 |
+
output_path: Path,
|
| 78 |
+
include_text_fields: bool,
|
| 79 |
+
) -> Tuple[int, int]:
|
| 80 |
+
metrics = load_json_or_jsonl(metrics_path)
|
| 81 |
+
judged = load_json_or_jsonl(judged_path)
|
| 82 |
+
|
| 83 |
+
metrics_by_id: Dict[str, Dict] = {
|
| 84 |
+
row["example_id"]: row for row in metrics if row.get("example_id") is not None
|
| 85 |
+
}
|
| 86 |
+
|
| 87 |
+
compiled = []
|
| 88 |
+
missing = 0
|
| 89 |
+
|
| 90 |
+
for judged_row in judged:
|
| 91 |
+
ex_id = judged_row.get("example_id")
|
| 92 |
+
metric_row = metrics_by_id.get(ex_id)
|
| 93 |
+
if metric_row is None:
|
| 94 |
+
missing += 1
|
| 95 |
+
continue
|
| 96 |
+
|
| 97 |
+
row = {
|
| 98 |
+
"example_id": ex_id,
|
| 99 |
+
"model": metric_row.get("model") or judged_row.get("model") or model,
|
| 100 |
+
"noise": metric_row.get("noise") or judged_row.get("noise") or noise,
|
| 101 |
+
}
|
| 102 |
+
|
| 103 |
+
for key, value in metric_row.items():
|
| 104 |
+
if key not in {"example_id", "model", "noise"}:
|
| 105 |
+
row[key] = value
|
| 106 |
+
|
| 107 |
+
row.update(flatten_judge_fields(judged_row))
|
| 108 |
+
|
| 109 |
+
if include_text_fields:
|
| 110 |
+
for key in TEXT_FIELDS:
|
| 111 |
+
if key in judged_row:
|
| 112 |
+
row[key] = judged_row[key]
|
| 113 |
+
|
| 114 |
+
compiled.append(row)
|
| 115 |
+
|
| 116 |
+
write_json(compiled, output_path)
|
| 117 |
+
return len(compiled), missing
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def main() -> None:
|
| 121 |
+
args = parse_args()
|
| 122 |
+
|
| 123 |
+
total_rows = 0
|
| 124 |
+
total_missing = 0
|
| 125 |
+
total_files = 0
|
| 126 |
+
|
| 127 |
+
for model, noise, judged_path in discover_judged(args.judged_root):
|
| 128 |
+
metrics_path = args.metrics_root / model / noise / "metrics.json"
|
| 129 |
+
if not metrics_path.exists():
|
| 130 |
+
print(f"Skipping {model}/{noise}: missing {metrics_path}")
|
| 131 |
+
continue
|
| 132 |
+
|
| 133 |
+
output_path = args.output_root / model / noise / "compiled.json"
|
| 134 |
+
rows, missing = compile_file(
|
| 135 |
+
model=model,
|
| 136 |
+
noise=noise,
|
| 137 |
+
metrics_path=metrics_path,
|
| 138 |
+
judged_path=judged_path,
|
| 139 |
+
output_path=output_path,
|
| 140 |
+
include_text_fields=args.include_text_fields,
|
| 141 |
+
)
|
| 142 |
+
total_rows += rows
|
| 143 |
+
total_missing += missing
|
| 144 |
+
total_files += 1
|
| 145 |
+
print(f"{model}/{noise}: {rows} compiled rows, {missing} missing metrics -> {output_path}")
|
| 146 |
+
|
| 147 |
+
print(
|
| 148 |
+
f"Compiled {total_rows} rows from {total_files} files; "
|
| 149 |
+
f"{total_missing} judged rows had no matching metric row"
|
| 150 |
+
)
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
if __name__ == "__main__":
|
| 154 |
+
main()
|
scripts/evaluate_outputs.py
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Compute APM row-level metrics for model output files."""
|
| 3 |
+
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
import argparse
|
| 7 |
+
import re
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
from typing import Iterable, Iterator, Optional, Tuple
|
| 10 |
+
|
| 11 |
+
from apm_metrics import compute_metrics, load_json_or_jsonl, write_json
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
NOISE_RE = re.compile(r"N\d+")
|
| 15 |
+
JSON_EXTENSIONS = {".json", ".jsonl"}
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def parse_args() -> argparse.Namespace:
|
| 19 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 20 |
+
parser.add_argument(
|
| 21 |
+
"--input-root",
|
| 22 |
+
type=Path,
|
| 23 |
+
required=True,
|
| 24 |
+
help="Root containing <model>/<noise>/results.jsonl outputs.",
|
| 25 |
+
)
|
| 26 |
+
parser.add_argument(
|
| 27 |
+
"--output-root",
|
| 28 |
+
type=Path,
|
| 29 |
+
default=Path("metrics"),
|
| 30 |
+
help="Directory where metric JSON files will be written.",
|
| 31 |
+
)
|
| 32 |
+
parser.add_argument(
|
| 33 |
+
"--model",
|
| 34 |
+
help="Model name to use when --input-root directly contains N*/ folders or is a file.",
|
| 35 |
+
)
|
| 36 |
+
parser.add_argument(
|
| 37 |
+
"--noise",
|
| 38 |
+
help="Noise label to use when --input-root is a single file.",
|
| 39 |
+
)
|
| 40 |
+
return parser.parse_args()
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def is_json_data_file(path: Path) -> bool:
|
| 44 |
+
return path.suffix in JSON_EXTENSIONS and path.name not in {"metrics.json", "compiled.json"}
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def preferred_files(noise_dir: Path) -> Iterable[Path]:
|
| 48 |
+
for preferred in ("results.jsonl", "results.json"):
|
| 49 |
+
path = noise_dir / preferred
|
| 50 |
+
if path.exists():
|
| 51 |
+
return [path]
|
| 52 |
+
return sorted(path for path in noise_dir.iterdir() if path.is_file() and is_json_data_file(path))
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def direct_noise_dirs(root: Path) -> bool:
|
| 56 |
+
dirs = [path for path in root.iterdir() if path.is_dir()]
|
| 57 |
+
return bool(dirs) and all(NOISE_RE.fullmatch(path.name) for path in dirs)
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def discover_inputs(
|
| 61 |
+
input_root: Path,
|
| 62 |
+
model_override: Optional[str],
|
| 63 |
+
noise_override: Optional[str],
|
| 64 |
+
) -> Iterator[Tuple[str, str, Path, Path]]:
|
| 65 |
+
"""Yield model, noise, input path, and output-relative metric path."""
|
| 66 |
+
|
| 67 |
+
if input_root.is_file():
|
| 68 |
+
if not model_override or not noise_override:
|
| 69 |
+
raise SystemExit("Single-file mode requires --model and --noise")
|
| 70 |
+
yield model_override, noise_override, input_root, Path(model_override) / noise_override / "metrics.json"
|
| 71 |
+
return
|
| 72 |
+
|
| 73 |
+
if direct_noise_dirs(input_root):
|
| 74 |
+
model = model_override or input_root.name
|
| 75 |
+
for noise_dir in sorted(path for path in input_root.iterdir() if path.is_dir()):
|
| 76 |
+
for file_path in preferred_files(noise_dir):
|
| 77 |
+
out_name = "metrics.json" if file_path.stem == "results" else f"{file_path.stem}_metrics.json"
|
| 78 |
+
yield model, noise_dir.name, file_path, Path(model) / noise_dir.name / out_name
|
| 79 |
+
return
|
| 80 |
+
|
| 81 |
+
for model_dir in sorted(path for path in input_root.iterdir() if path.is_dir()):
|
| 82 |
+
model = model_override or model_dir.name
|
| 83 |
+
for noise_dir in sorted(path for path in model_dir.iterdir() if path.is_dir()):
|
| 84 |
+
if noise_override and noise_dir.name != noise_override:
|
| 85 |
+
continue
|
| 86 |
+
for file_path in preferred_files(noise_dir):
|
| 87 |
+
out_name = "metrics.json" if file_path.stem == "results" else f"{file_path.stem}_metrics.json"
|
| 88 |
+
yield model, noise_dir.name, file_path, Path(model) / noise_dir.name / out_name
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def evaluate_file(input_path: Path, output_path: Path, model: str, noise: str) -> Tuple[int, int]:
|
| 92 |
+
records = load_json_or_jsonl(input_path)
|
| 93 |
+
metrics = []
|
| 94 |
+
skipped = 0
|
| 95 |
+
|
| 96 |
+
for record in records:
|
| 97 |
+
row = compute_metrics(record, model=model, noise=noise)
|
| 98 |
+
if row is None:
|
| 99 |
+
skipped += 1
|
| 100 |
+
continue
|
| 101 |
+
metrics.append(row)
|
| 102 |
+
|
| 103 |
+
write_json(metrics, output_path)
|
| 104 |
+
return len(metrics), skipped
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def main() -> None:
|
| 108 |
+
args = parse_args()
|
| 109 |
+
|
| 110 |
+
total_rows = 0
|
| 111 |
+
total_skipped = 0
|
| 112 |
+
total_files = 0
|
| 113 |
+
|
| 114 |
+
for model, noise, input_path, rel_output_path in discover_inputs(
|
| 115 |
+
args.input_root,
|
| 116 |
+
args.model,
|
| 117 |
+
args.noise,
|
| 118 |
+
):
|
| 119 |
+
output_path = args.output_root / rel_output_path
|
| 120 |
+
rows, skipped = evaluate_file(input_path, output_path, model=model, noise=noise)
|
| 121 |
+
total_rows += rows
|
| 122 |
+
total_skipped += skipped
|
| 123 |
+
total_files += 1
|
| 124 |
+
print(f"{model}/{noise}: {rows} rows, {skipped} skipped -> {output_path}")
|
| 125 |
+
|
| 126 |
+
print(
|
| 127 |
+
f"Processed {total_files} files with {total_rows} metric rows "
|
| 128 |
+
f"and {total_skipped} skipped rows"
|
| 129 |
+
)
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
if __name__ == "__main__":
|
| 133 |
+
main()
|
scripts/prepare_inference_inputs.py
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Convert APM prompt CSV files into JSONL examples for model inference."""
|
| 3 |
+
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
import argparse
|
| 7 |
+
import csv
|
| 8 |
+
import hashlib
|
| 9 |
+
import json
|
| 10 |
+
import re
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
from typing import Any, Dict, Iterable, List
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
FILENAME_RE = re.compile(r"prompts_(?P<language>.+)_(?P<noise>N\d+)\.csv$")
|
| 16 |
+
ALPHA_RE = re.compile(r"alpha_(?P<value>\d+(?:\.\d+)?)$")
|
| 17 |
+
DEFAULT_INSTRUCTION = (
|
| 18 |
+
"Rewrite the noisy user prompt into a clear prompt that preserves the user's "
|
| 19 |
+
"intent. Return only the rewritten prompt; do not ask clarification questions "
|
| 20 |
+
"or add explanations."
|
| 21 |
+
)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def parse_args() -> argparse.Namespace:
|
| 25 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 26 |
+
parser.add_argument(
|
| 27 |
+
"--dataset-dir",
|
| 28 |
+
type=Path,
|
| 29 |
+
default=Path("."),
|
| 30 |
+
help="Directory containing prompts_<language>_<noise>.csv files.",
|
| 31 |
+
)
|
| 32 |
+
parser.add_argument(
|
| 33 |
+
"--output-dir",
|
| 34 |
+
type=Path,
|
| 35 |
+
default=Path("benchmark_inputs"),
|
| 36 |
+
help="Directory where JSONL inference inputs will be written.",
|
| 37 |
+
)
|
| 38 |
+
parser.add_argument(
|
| 39 |
+
"--no-instruction",
|
| 40 |
+
action="store_true",
|
| 41 |
+
help="Do not include the default mediation instruction in each row.",
|
| 42 |
+
)
|
| 43 |
+
parser.add_argument(
|
| 44 |
+
"--overwrite",
|
| 45 |
+
action="store_true",
|
| 46 |
+
help="Replace existing output files.",
|
| 47 |
+
)
|
| 48 |
+
return parser.parse_args()
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def alpha_columns(fieldnames: Iterable[str]) -> List[str]:
|
| 52 |
+
columns = [name for name in fieldnames if ALPHA_RE.fullmatch(name)]
|
| 53 |
+
return sorted(columns, key=lambda name: float(ALPHA_RE.fullmatch(name).group("value")))
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def example_id(payload: Dict[str, Any]) -> str:
|
| 57 |
+
stable = json.dumps(payload, ensure_ascii=False, sort_keys=True, separators=(",", ":"))
|
| 58 |
+
return hashlib.sha1(stable.encode("utf-8")).hexdigest()
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def iter_examples(csv_path: Path, include_instruction: bool) -> Iterable[Dict[str, Any]]:
|
| 62 |
+
match = FILENAME_RE.match(csv_path.name)
|
| 63 |
+
if not match:
|
| 64 |
+
return
|
| 65 |
+
|
| 66 |
+
language = match.group("language")
|
| 67 |
+
noise = match.group("noise")
|
| 68 |
+
|
| 69 |
+
with csv_path.open("r", encoding="utf-8-sig", newline="") as f:
|
| 70 |
+
reader = csv.DictReader(f)
|
| 71 |
+
if reader.fieldnames is None:
|
| 72 |
+
return
|
| 73 |
+
alphas = alpha_columns(reader.fieldnames)
|
| 74 |
+
|
| 75 |
+
for row_index, row in enumerate(reader):
|
| 76 |
+
clean_text = row.get("Clean_text", "")
|
| 77 |
+
category = row.get("Category", "")
|
| 78 |
+
for alpha_col in alphas:
|
| 79 |
+
alpha_value = float(ALPHA_RE.fullmatch(alpha_col).group("value"))
|
| 80 |
+
noisy_prompt = row.get(alpha_col, "")
|
| 81 |
+
identity = {
|
| 82 |
+
"language": language,
|
| 83 |
+
"noise": noise,
|
| 84 |
+
"row_index": row_index,
|
| 85 |
+
"alpha": alpha_value,
|
| 86 |
+
"clean_text": clean_text,
|
| 87 |
+
"noisy_prompt": noisy_prompt,
|
| 88 |
+
}
|
| 89 |
+
example = {
|
| 90 |
+
"example_id": example_id(identity),
|
| 91 |
+
"language": language,
|
| 92 |
+
"noise": noise,
|
| 93 |
+
"category": category,
|
| 94 |
+
"alpha": alpha_value,
|
| 95 |
+
"clean_text": clean_text,
|
| 96 |
+
"noisy_prompt": noisy_prompt,
|
| 97 |
+
"source_file": csv_path.name,
|
| 98 |
+
"row_index": row_index,
|
| 99 |
+
}
|
| 100 |
+
if include_instruction:
|
| 101 |
+
example["instruction"] = DEFAULT_INSTRUCTION
|
| 102 |
+
yield example
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def main() -> None:
|
| 106 |
+
args = parse_args()
|
| 107 |
+
csv_paths = sorted(args.dataset_dir.glob("prompts_*_N*.csv"))
|
| 108 |
+
if not csv_paths:
|
| 109 |
+
raise SystemExit(f"No prompt CSV files found in {args.dataset_dir}")
|
| 110 |
+
|
| 111 |
+
total = 0
|
| 112 |
+
args.output_dir.mkdir(parents=True, exist_ok=True)
|
| 113 |
+
|
| 114 |
+
for csv_path in csv_paths:
|
| 115 |
+
match = FILENAME_RE.match(csv_path.name)
|
| 116 |
+
if not match:
|
| 117 |
+
continue
|
| 118 |
+
|
| 119 |
+
language = match.group("language")
|
| 120 |
+
noise = match.group("noise")
|
| 121 |
+
out_dir = args.output_dir / noise
|
| 122 |
+
out_dir.mkdir(parents=True, exist_ok=True)
|
| 123 |
+
out_path = out_dir / f"{language}.jsonl"
|
| 124 |
+
|
| 125 |
+
if out_path.exists() and not args.overwrite:
|
| 126 |
+
raise SystemExit(f"{out_path} already exists; pass --overwrite to replace it")
|
| 127 |
+
|
| 128 |
+
count = 0
|
| 129 |
+
with out_path.open("w", encoding="utf-8") as f:
|
| 130 |
+
for example in iter_examples(csv_path, include_instruction=not args.no_instruction):
|
| 131 |
+
f.write(json.dumps(example, ensure_ascii=False) + "\n")
|
| 132 |
+
count += 1
|
| 133 |
+
|
| 134 |
+
total += count
|
| 135 |
+
print(f"Wrote {count:5d} examples -> {out_path}")
|
| 136 |
+
|
| 137 |
+
print(f"Prepared {total} inference examples")
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
if __name__ == "__main__":
|
| 141 |
+
main()
|