Upload Figure 6 tail-threshold code bundle
Browse filesFiles changed (8)
- evaluation/tail/tail_threshold_code/README.mdAdded+18
- evaluation/tail/tail_threshold_code/manifest.jsonAdded+17
- evaluation/tail/tail_threshold_code/scripts/render_tail_metric_combined_tikz.pyAdded+245
- evaluation/tail/tail_threshold_code/scripts/render_tail_metric_model_grid.pyAdded+268
- evaluation/tail/tail_threshold_code/scripts/render_tail_stress_main_figure.pyAdded+377
- evaluation/tail/tail_threshold_code/scripts/run_tail_threshold.pyAdded+108
- evaluation/tail/tail_threshold_code/src/eval/common.pyAdded+1629
- evaluation/tail/tail_threshold_code/src/eval/tail_threshold/runner.pyAdded+1562
123456789101112131415161718This directory contains the minimum local code needed to reproduce the Figure 6 tail-threshold stress analysis and render its paper-facing outputs.
Main entrypoints:- `scripts/run_tail_threshold.py`: computes the tail-threshold experiment and writes a run bundle.- `scripts/render_tail_stress_main_figure.py`: renders the main stress figure from summary CSV tables.- `scripts/render_tail_metric_combined_tikz.py`: renders the combined submetric figure as PGFPlots/TikZ.
Key dependencies included here:- `src/eval/tail_threshold/runner.py`- `src/eval/common.py`- `scripts/render_tail_metric_model_grid.py`
Expected result inputs:- `evaluation/tail/tail_threshold_runs/20260505_latest48_keyset_tail_threshold/summaries/`- `evaluation/tail/tail_threshold_runs/20260505_latest48_keyset_tail_threshold/tables/`
Expected rendered outputs:- `evaluation/tail/tail_threshold_final/`1234567891011121314151617{ "artifact": "figure6_tail_threshold_code_bundle", "purpose": "Minimum code bundle for computing and rendering Figure 6 tail-threshold stress artifacts", "source_repo_subpaths": [ "scripts/run_tail_threshold.py", "scripts/render_tail_stress_main_figure.py", "scripts/render_tail_metric_combined_tikz.py", "scripts/render_tail_metric_model_grid.py", "src/eval/tail_threshold/runner.py", "src/eval/common.py" ], "source_run_tag": "20260505_latest48_keyset_tail_threshold", "notes": [ "The run bundle itself lives under evaluation/tail/tail_threshold_runs/20260505_latest48_keyset_tail_threshold.", "The final rendered figure assets live under evaluation/tail/tail_threshold_final." ]}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245#!/usr/bin/env python3"""Render the combined tail-submetric preview as a native PGFPlots figure."""
from __future__ import annotations
import argparsefrom pathlib import Pathimport sys
import numpy as npimport pandas as pd
PROJECT_ROOT = Path(__file__).resolve().parents[1]if str(PROJECT_ROOT) not in sys.path: sys.path.insert(0, str(PROJECT_ROOT))
from scripts.render_tail_metric_model_grid import _load_model_threshold, _metric_pivot, _model_orderfrom scripts.render_tail_stress_main_figure import DECOMP_COLORS
METRICS = [ ("tail_set_consistency", "Tail set consistency"), ("tail_mass_similarity", "Tail mass similarity"), ("tail_concentration_consistency", "Tail concentration consistency"),]
COLOR_NAMES = { "tail_set_consistency": "tailsetmetric", "tail_mass_similarity": "tailmassmetric", "tail_concentration_consistency": "tailconcmetric",}
def _build_parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--tables-dir", type=Path, required=True) parser.add_argument("--embedded-output", type=Path, required=True) parser.add_argument("--standalone-output", type=Path) parser.add_argument("--paper-embedded-output", type=Path) return parser
def _fmt(value: float) -> str: return f"{value:.6f}"
def _write(path: Path, text: str) -> None: path.parent.mkdir(parents=True, exist_ok=True) path.write_text(text, encoding="utf-8")
def _build_embedded_tex(df: pd.DataFrame) -> str: model_order = _model_order(df) payloads: list[dict[str, object]] = []
for metric, label in METRICS: pivot = _metric_pivot(df, metric, model_order) values = pivot.to_numpy(dtype=float) payloads.append( { "metric": metric, "label": label, "mean": np.nanmean(values, axis=1), "q25": np.nanquantile(values, 0.25, axis=1), "q75": np.nanquantile(values, 0.75, axis=1), "vmin": np.nanmin(values, axis=1), "vmax": np.nanmax(values, axis=1), } )
offsets = [-0.24, 0.0, 0.24] box_width = 0.18
lines: list[str] = [] lines.append(r"\definecolor{tailsetmetric}{HTML}{" + DECOMP_COLORS["tail_set_consistency_mean"].lstrip("#") + "}") lines.append(r"\definecolor{tailmassmetric}{HTML}{" + DECOMP_COLORS["tail_mass_similarity_mean"].lstrip("#") + "}") lines.append(r"\definecolor{tailconcmetric}{HTML}{" + DECOMP_COLORS["tail_concentration_consistency_mean"].lstrip("#") + "}") lines.append(r"\begin{tikzpicture}") lines.append(r"\begin{axis}[") lines.append(r" width=17.6cm,") lines.append(r" height=6.9cm,") lines.append(r" xmin=-0.65, xmax=" + _fmt(len(model_order) - 0.35) + ",") lines.append(r" ymin=0.0, ymax=1.0,") lines.append(r" xtick={0,...," + str(len(model_order) - 1) + r"},") lines.append(r" xticklabels={" + ",".join(model_order) + r"},") lines.append(r" xticklabel style={rotate=30, anchor=east, font=\small},") lines.append(r" yticklabel style={font=\small},") lines.append(r" xlabel={Model},") lines.append(r" ylabel={Score},") lines.append(r" axis line style={draw=gray!65, line width=0.8pt},") lines.append(r" tick style={black, line width=0.8pt},") lines.append(r" grid=major,") lines.append(r" major grid style={draw=gray!22, dashed},") lines.append(r" axis background/.style={fill=white},") lines.append(r" label style={font=\small},") lines.append(r" clip=false,") lines.append(r"]")
for boundary in range(len(model_order) - 1): x = boundary + 0.5 lines.append( r"\draw[gray!22, line width=0.6pt] (axis cs:" + _fmt(x) + r",0.0) -- (axis cs:" + _fmt(x) + r",1.0);" )
for payload, offset in zip(payloads, offsets): metric = str(payload["metric"]) color_name = COLOR_NAMES[metric] means = np.asarray(payload["mean"], dtype=float) q25 = np.asarray(payload["q25"], dtype=float) q75 = np.asarray(payload["q75"], dtype=float) vmin = np.asarray(payload["vmin"], dtype=float) vmax = np.asarray(payload["vmax"], dtype=float)
for idx in range(len(model_order)): if np.isnan(means[idx]): continue xpos = idx + offset left = xpos - box_width / 2.0 right = xpos + box_width / 2.0 low = vmin[idx] high = vmax[idx] cap_left = xpos - 0.045 cap_right = xpos + 0.045 box_bottom = q25[idx] box_top = max(q25[idx] + 1e-6, q75[idx]) mean = means[idx]
lines.append( r"\path[fill=" + color_name + r", fill opacity=0.28, draw=none] (axis cs:" + _fmt(left) + "," + _fmt(box_bottom) + r") rectangle (axis cs:" + _fmt(right) + "," + _fmt(box_top) + r");" ) lines.append( r"\draw[" + color_name + r", line width=1.15pt] (axis cs:" + _fmt(xpos) + "," + _fmt(low) + r") -- (axis cs:" + _fmt(xpos) + "," + _fmt(high) + r");" ) lines.append( r"\draw[" + color_name + r", line width=1.15pt] (axis cs:" + _fmt(cap_left) + "," + _fmt(low) + r") -- (axis cs:" + _fmt(cap_right) + "," + _fmt(low) + r");" ) lines.append( r"\draw[" + color_name + r", line width=1.15pt] (axis cs:" + _fmt(cap_left) + "," + _fmt(high) + r") -- (axis cs:" + _fmt(cap_right) + "," + _fmt(high) + r");" ) lines.append( r"\addplot[only marks, mark=square*, mark size=2.2pt, color=" + color_name + r"] coordinates {(" + _fmt(xpos) + "," + _fmt(mean) + r")};" )
lines.append( r"\node[anchor=west, font=\small] at (rel axis cs:0.01,1.035) {" r"\textcolor{tailsetmetric}{Tail set consistency}" r"\quad" r"\textcolor{tailmassmetric}{Tail mass similarity}" r"\quad" r"\textcolor{tailconcmetric}{Tail concentration consistency}" r"};" ) lines.append( r"\node[anchor=east, font=\small, text=gray!70!black] at (rel axis cs:0.995,1.035) {" r"square = mean \quad whisker = min--max \quad box = IQR" r"};" ) lines.append(r"\end{axis}") lines.append(r"\end{tikzpicture}") lines.append("") return "\n".join(lines)
def _build_standalone_tex(embedded_name: str) -> str: return "\n".join( [ r"\documentclass[tikz,border=6pt]{standalone}", r"\usepackage{pgfplots}", r"\pgfplotsset{compat=1.18}", r"\begin{document}", r"\input{" + embedded_name + r"}", r"\end{document}", "", ] )
def main() -> int: args = _build_parser().parse_args() df = _load_model_threshold(args.tables_dir) embedded_tex = _build_embedded_tex(df) _write(args.embedded_output, embedded_tex)
if args.paper_embedded_output: _write(args.paper_embedded_output, embedded_tex)
if args.standalone_output: standalone_tex = _build_standalone_tex(args.embedded_output.name) _write(args.standalone_output, standalone_tex)
return 0
if __name__ == "__main__": raise SystemExit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268#!/usr/bin/env python3"""Render six model-by-threshold metric figures for tail submetrics."""
from __future__ import annotations
import argparsefrom pathlib import Pathimport sys
import matplotlib
matplotlib.use("Agg")import matplotlib.pyplot as pltimport numpy as npimport pandas as pdfrom matplotlib import colors as mcolorsfrom matplotlib.lines import Line2Dfrom matplotlib.patches import Patch
PROJECT_ROOT = Path(__file__).resolve().parents[1]if str(PROJECT_ROOT) not in sys.path: sys.path.insert(0, str(PROJECT_ROOT))
from scripts.render_tail_stress_main_figure import MODEL_COLORS, THRESHOLD_ORDER
METRICS = [ ("tail_set_consistency", "Tail set consistency score"), ("tail_mass_similarity", "Tail mass similarity score"), ("tail_concentration_consistency", "Tail concentration consistency score"),]
def _build_parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--tables-dir", type=Path, required=True) parser.add_argument("--output-dir", type=Path, required=True) return parser
def _configure_style() -> None: plt.rcParams.update( { "font.family": "DejaVu Sans", "font.size": 8, "axes.titlesize": 10.0, "axes.labelsize": 9, "xtick.labelsize": 8, "ytick.labelsize": 8, "legend.fontsize": 8, "axes.facecolor": "white", "figure.facecolor": "white", "axes.edgecolor": "#444444", "axes.linewidth": 0.8, "grid.color": "#D9D9D9", "grid.linestyle": "--", "grid.linewidth": 0.7, "pdf.fonttype": 42, "ps.fonttype": 42, } )
def _blend_with_white(color: str, strength: float) -> tuple[float, float, float]: base = np.array(mcolors.to_rgb(color), dtype=float) white = np.array([1.0, 1.0, 1.0], dtype=float) mixed = base * (1.0 - strength) + white * strength return tuple(float(v) for v in mixed)
def _style_axis(ax: plt.Axes) -> None: ax.grid(axis="y") ax.grid(axis="x", visible=False) ax.set_axisbelow(True) ax.spines["top"].set_visible(False) ax.spines["right"].set_visible(False)
def _load_model_threshold(tables_dir: Path) -> pd.DataFrame: path = tables_dir / "model_threshold_summary.csv" df = pd.read_csv(path) df = df[df["model_label"].isin(MODEL_COLORS)].copy() df["threshold_label"] = pd.Categorical(df["threshold_label"], categories=THRESHOLD_ORDER, ordered=True) df = df.sort_values(["model_label", "threshold_label"]).reset_index(drop=True) return df
def _model_order(df: pd.DataFrame) -> list[str]: present = set(df["model_label"].dropna().unique().tolist()) return [label for label in MODEL_COLORS if label in present]
def _metric_pivot(df: pd.DataFrame, metric: str, model_order: list[str]) -> pd.DataFrame: pivot = ( df.pivot_table(index="model_label", columns="threshold_label", values=metric, aggfunc="mean") .reindex(index=model_order, columns=THRESHOLD_ORDER) .astype(float) ) return pivot
def _save(fig: plt.Figure, path: Path) -> None: path.parent.mkdir(parents=True, exist_ok=True) fig.savefig(path, dpi=300, facecolor="white") if path.suffix.lower() == ".png": fig.savefig(path.with_suffix(".pdf"), dpi=300, facecolor="white") plt.close(fig)
def _threshold_legend_handles() -> list[Patch]: samples = [("10%", 0.00), ("2%", 0.30), ("0.5%", 0.55), ("0.001%", 0.80)] return [ Patch(facecolor=_blend_with_white("#666666", strength), edgecolor="none", label=label) for label, strength in samples ]
def render_errorbar_style(df: pd.DataFrame, output_dir: Path) -> list[Path]: model_order = _model_order(df) x = np.arange(len(model_order)) outputs: list[Path] = []
for metric, ylabel in METRICS: pivot = _metric_pivot(df, metric, model_order) values = pivot.to_numpy(dtype=float) means = np.nanmean(values, axis=1) lows = means - np.nanmin(values, axis=1) highs = np.nanmax(values, axis=1) - means q25 = np.nanquantile(values, 0.25, axis=1) q75 = np.nanquantile(values, 0.75, axis=1)
fig, ax = plt.subplots(figsize=(8.3, 4.6), constrained_layout=True) for idx, model in enumerate(model_order): base = MODEL_COLORS[model] # IQR band ax.add_patch( plt.Rectangle( (x[idx] - 0.26, q25[idx]), 0.52, max(1e-6, q75[idx] - q25[idx]), facecolor=_blend_with_white(base, 0.55), edgecolor="none", alpha=0.85, zorder=1, ) ) ax.errorbar( x[idx], means[idx], yerr=np.array([[lows[idx]], [highs[idx]]]), fmt="s", color=base, markersize=4.8, elinewidth=1.7, capsize=4, capthick=1.2, zorder=3, )
ax.set_xticks(x, model_order, rotation=30, ha="right") ax.set_ylabel(ylabel) ax.set_xlabel("Model") ax.set_ylim(0.0, min(1.0, np.nanmax(values) + 0.08)) ax.set_title(f"{ylabel}: threshold sweep summarized as mean + range", loc="left", pad=6) _style_axis(ax)
legend_items = [ Line2D([0], [0], marker="s", color="#555555", linestyle="none", markersize=5, label="Mean over thresholds"), Line2D([0], [0], color="#555555", linewidth=1.7, label="Min-max over thresholds"), Patch(facecolor="#D9D9D9", edgecolor="none", label="IQR over thresholds"), ] ax.legend(handles=legend_items, loc="upper left", frameon=False, ncols=3) ax.text( 0.995, 0.02, "Each model summarizes the full 10-threshold sweep", transform=ax.transAxes, ha="right", va="bottom", fontsize=7.2, color="#666666", )
out = output_dir / f"{metric}__errorbar_summary.png" _save(fig, out) outputs.append(out)
return outputs
def render_layered_bar_style(df: pd.DataFrame, output_dir: Path) -> list[Path]: model_order = _model_order(df) x = np.arange(len(model_order)) shade_strengths = np.linspace(0.00, 0.82, len(THRESHOLD_ORDER)) outputs: list[Path] = []
for metric, ylabel in METRICS: pivot = _metric_pivot(df, metric, model_order) fig, ax = plt.subplots(figsize=(8.3, 4.8), constrained_layout=True)
for idx, model in enumerate(model_order): base = MODEL_COLORS[model] column = pivot.loc[model].to_list() # draw from light to dark so broader/taller bars remain visible for threshold_idx in range(len(THRESHOLD_ORDER) - 1, -1, -1): value = column[threshold_idx] if pd.isna(value): continue strength = float(shade_strengths[threshold_idx]) ax.bar( x[idx], float(value), width=0.72, color=_blend_with_white(base, strength), edgecolor="white", linewidth=0.55, zorder=2 + threshold_idx * 0.01, )
ax.set_xticks(x, model_order, rotation=30, ha="right") ax.set_ylabel(ylabel) ax.set_xlabel("Model") ax.set_ylim(0.0, min(1.0, float(np.nanmax(pivot.to_numpy(dtype=float))) + 0.08)) ax.set_title(f"{ylabel}: layered threshold bars", loc="left", pad=6) _style_axis(ax) legend = ax.legend( handles=_threshold_legend_handles(), title="Threshold shading", loc="upper left", frameon=False, ncols=4, ) legend.get_title().set_fontsize(8) ax.text( 0.995, 0.02, "Darker bars = broader tail threshold; lighter bars = rarer tail threshold", transform=ax.transAxes, ha="right", va="bottom", fontsize=7.2, color="#666666", )
out = output_dir / f"{metric}__layered_bars.png" _save(fig, out) outputs.append(out)
return outputs
def main() -> int: args = _build_parser().parse_args() _configure_style() df = _load_model_threshold(args.tables_dir) output_dir = args.output_dir output_dir.mkdir(parents=True, exist_ok=True)
outputs = [] outputs.extend(render_errorbar_style(df, output_dir)) outputs.extend(render_layered_bar_style(df, output_dir)) for path in outputs: print(path) return 0
if __name__ == "__main__": raise SystemExit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377#!/usr/bin/env python3"""Render a paper-ready multi-panel tail stress figure from summary CSVs."""
from __future__ import annotations
import argparsefrom pathlib import Path
import matplotlib
matplotlib.use("Agg")import matplotlib.pyplot as pltimport numpy as npimport pandas as pdfrom matplotlib import colors as mcolors
THRESHOLD_ORDER = ["10%", "8%", "6%", "4%", "2%", "1%", "0.5%", "0.1%", "0.01%", "0.001%"]
# Frozen paper color convention from README.md.MODEL_COLORS = { "RealTabFormer": "#332288", "TVAE": "#4477AA", "ForestDiffusion": "#228833", "TabDDPM": "#EE7733", "TabSyn": "#66CCEE", "TabDiff": "#AA3377", "CTGAN": "#EE6677", "ARF": "#777777", "BayesNet": "#CCBB44", "TabPFGen": "#009988", "TabbyFlow": "#882255",}
TAIL_COLOR = "#E4572E"HEAD_COLOR = "#4C78A8"DECOMP_COLORS = { "tail_set_consistency_mean": "#D1495B", "tail_mass_similarity_mean": "#2A9D8F", "tail_concentration_consistency_mean": "#6D597A",}DECOMP_LABELS = { "tail_set_consistency_mean": "Tail set consistency", "tail_mass_similarity_mean": "Tail mass similarity", "tail_concentration_consistency_mean": "Tail concentration consistency",}MODEL_LABEL_OFFSETS = { "ARF": (6, 8), "BayesNet": (6, -12), "CTGAN": (6, -10), "ForestDiffusion": (6, -10), "RealTabFormer": (6, 8), "TVAE": (6, 8), "TabDDPM": (6, -10), "TabDiff": (6, 8), "TabPFGen": (6, 8), "TabSyn": (6, 6), "TabbyFlow": (6, -10),}
def _build_parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument( "--tables-dir", type=Path, required=True, help="Directory containing tail-threshold summary CSV files.", ) parser.add_argument( "--output-dir", type=Path, required=True, help="Directory where the PNG/PDF figure will be written.", ) return parser
def _read_required_tables(tables_dir: Path) -> dict[str, pd.DataFrame]: file_map = { "global": "global_threshold_summary.csv", "model_fragility": "model_fragility_summary.csv", "model_threshold": "model_threshold_summary.csv", "prefix_threshold": "prefix_threshold_summary.csv", "dataset_threshold": "dataset_threshold_summary.csv", } tables: dict[str, pd.DataFrame] = {} for key, name in file_map.items(): path = tables_dir / name if not path.exists(): raise FileNotFoundError(f"Missing required input CSV: {path}") tables[key] = pd.read_csv(path) return tables
def _ordered(df: pd.DataFrame, label_col: str = "threshold_label") -> pd.DataFrame: ordered = df.copy() ordered[label_col] = pd.Categorical(ordered[label_col], categories=THRESHOLD_ORDER, ordered=True) ordered = ordered.sort_values(label_col).reset_index(drop=True) return ordered
def _configure_style() -> None: plt.rcParams.update( { "font.family": "DejaVu Sans", "font.size": 8, "axes.titlesize": 10.5, "axes.labelsize": 9, "xtick.labelsize": 8, "ytick.labelsize": 8, "legend.fontsize": 8, "axes.facecolor": "white", "figure.facecolor": "white", "axes.edgecolor": "#444444", "axes.linewidth": 0.8, "grid.color": "#D9D9D9", "grid.linestyle": "--", "grid.linewidth": 0.7, "pdf.fonttype": 42, "ps.fonttype": 42, } )
def _style_axis(ax: plt.Axes) -> None: ax.grid(axis="y") ax.grid(axis="x", visible=False) ax.set_axisbelow(True) ax.spines["top"].set_visible(False) ax.spines["right"].set_visible(False)
def _blend_with_white(color: str, strength: float) -> tuple[float, float, float]: base = np.array(mcolors.to_rgb(color), dtype=float) white = np.array([1.0, 1.0, 1.0], dtype=float) mixed = base * (1.0 - strength) + white * strength return tuple(float(v) for v in mixed)
def _shade_ultra_tail(ax: plt.Axes) -> None: ax.axvspan(6.5, 9.5, color="#EFEFEF", alpha=1.0, zorder=0) ax.axvline(6.5, color="#999999", linestyle="--", linewidth=1.0, zorder=1) ax.text( 7.95, 0.985, "Low-support\nultra-tail", transform=ax.get_xaxis_transform(), ha="center", va="top", fontsize=7.5, color="#555555", )
def _render_panel_a(ax: plt.Axes, global_df: pd.DataFrame) -> None: x = list(range(len(global_df))) tail = global_df["tail_overall_mean"].tolist() head = global_df["head_proxy_mean"].tolist()
_shade_ultra_tail(ax) ax.plot(x, tail, color=TAIL_COLOR, marker="o", linewidth=2.0, markersize=4.4, label="Tail score", zorder=3) ax.plot(x, head, color=HEAD_COLOR, marker="o", linewidth=2.0, markersize=4.4, label="Head proxy score", zorder=3)
ax.set_xticks(x, global_df["threshold_label"].tolist(), rotation=30, ha="right") ax.set_ylim(0.20, 0.60) ax.set_ylabel("Score") ax.set_xlabel("Tail threshold") ax.set_title("A. Tail degrades while head remains stable", loc="left", pad=6) _style_axis(ax)
ax.text( 0.03, 0.53, f"Tail: {tail[0]:.3f} -> {tail[6]:.3f}", transform=ax.transAxes, color=TAIL_COLOR, fontsize=8, fontweight="bold", bbox={"facecolor": "white", "edgecolor": "none", "alpha": 0.85, "pad": 2.5}, ) ax.text( 0.03, 0.45, f"Head: {head[0]:.3f} -> {head[-1]:.3f}", transform=ax.transAxes, color=HEAD_COLOR, fontsize=8, fontweight="bold", bbox={"facecolor": "white", "edgecolor": "none", "alpha": 0.85, "pad": 2.5}, ) ax.legend(loc="lower left", frameon=False, ncols=1, bbox_to_anchor=(0.005, 0.005))
def _render_panel_b(ax: plt.Axes, global_df: pd.DataFrame) -> None: x = list(range(len(global_df))) baseline = global_df.iloc[0]
for metric in ( "tail_set_consistency_mean", "tail_mass_similarity_mean", "tail_concentration_consistency_mean", ): base_value = float(baseline[metric]) values = [float(v) / base_value if base_value else 0.0 for v in global_df[metric].tolist()] ax.plot( x, values, marker="o", linewidth=2.0, markersize=4.2, color=DECOMP_COLORS[metric], label=DECOMP_LABELS[metric], )
_shade_ultra_tail(ax) ax.axhline(1.0, color="#888888", linestyle="--", linewidth=1.0) ax.set_xticks(x, global_df["threshold_label"].tolist(), rotation=30, ha="right") ax.set_ylim(0.60, 1.12) ax.set_ylabel("Relative score vs. 10% threshold") ax.set_xlabel("Tail threshold") ax.set_title("B. Tail set consistency and tail mass similarity break first", loc="left", pad=6) _style_axis(ax) ax.legend(loc="lower left", frameon=False)
def _render_panel_c(ax: plt.Axes, model_threshold_df: pd.DataFrame) -> None: ordered = _ordered(model_threshold_df) ordered = ordered[ordered["model_label"].isin(MODEL_COLORS)].copy() model_labels = [label for label in MODEL_COLORS if label in set(ordered["model_label"].dropna().unique().tolist())] shade_strengths = np.linspace(0.0, 0.78, len(THRESHOLD_ORDER))
x_all: list[float] = [] y_all: list[float] = []
for label in model_labels: subset = ordered[ordered["model_label"] == label].copy() subset = subset.dropna(subset=["tail_set_consistency", "tail_mass_similarity"]) if subset.empty: continue x_vals = subset["tail_set_consistency"].astype(float).tolist() y_vals = subset["tail_mass_similarity"].astype(float).tolist() x_all.extend(x_vals) y_all.extend(y_vals)
base_color = MODEL_COLORS[label] ax.plot(x_vals, y_vals, color=base_color, linewidth=1.0, alpha=0.38, zorder=1)
for idx, (_, row) in enumerate(subset.iterrows()): color = _blend_with_white(base_color, float(shade_strengths[idx])) size = 36 if idx == 0 else 28 ax.scatter( [float(row["tail_set_consistency"])], [float(row["tail_mass_similarity"])], s=size, color=color, edgecolor="white", linewidth=0.55, zorder=2 + idx * 0.01, )
first = subset.iloc[0] dx, dy = MODEL_LABEL_OFFSETS.get(label, (6, 6)) ax.annotate( label, (float(first["tail_set_consistency"]), float(first["tail_mass_similarity"])), xytext=(dx, dy), textcoords="offset points", fontsize=7.3, ha="left", va="center", color="#333333", bbox={"facecolor": "white", "edgecolor": "none", "alpha": 0.84, "pad": 1.2}, zorder=4, )
if not x_all or not y_all: ax.text(0.5, 0.5, "No paper-roster models available", ha="center", va="center", fontsize=9, color="#666666") ax.set_axis_off() return
ax.set_xlim(max(0.0, min(x_all) - 0.02), min(1.0, max(x_all) + 0.06)) ax.set_ylim(max(0.0, min(y_all) - 0.03), min(1.0, max(y_all) + 0.06)) ax.set_xlabel("Tail set consistency score") ax.set_ylabel("Tail mass similarity score") ax.set_title("C. Tail set consistency and tail mass similarity erode together", loc="left", pad=6) _style_axis(ax)
threshold_handles = [ plt.Line2D( [0], [0], marker="o", color="none", markerfacecolor=_blend_with_white("#666666", strength), markeredgecolor="white", markeredgewidth=0.5, markersize=5, label=label, ) for strength, label in [ (shade_strengths[0], "10%"), (shade_strengths[5], "1%"), (shade_strengths[-1], "0.001%"), ] ] legend = ax.legend( handles=threshold_handles, title="Threshold shading", loc="lower right", frameon=False, ncols=3, bbox_to_anchor=(1.0, 1.02), borderaxespad=0.0, handletextpad=0.4, columnspacing=0.9, ) legend.get_title().set_fontsize(7.8) ax.add_artist(legend) ax.text( 0.995, 0.03, "Same hue = same model\nlighter points = rarer threshold", transform=ax.transAxes, ha="right", va="bottom", fontsize=7.2, color="#666666", )
def render_main_figure(tables_dir: Path, output_dir: Path) -> tuple[Path, Path]: tables = _read_required_tables(tables_dir) global_df = _ordered(tables["global"])
_configure_style() fig = plt.figure(figsize=(7.1, 3.55), constrained_layout=True) fig.set_constrained_layout_pads(w_pad=0.02, h_pad=0.02, wspace=0.04, hspace=0.06) mosaic = fig.subplot_mosaic( [["T", "T"], ["A", "B"]], height_ratios=[0.18, 1.0], )
mosaic["T"].axis("off") mosaic["T"].text( 0.0, 0.72, "Tail stress testing reveals rare-event fragility", fontsize=10.5, fontweight="bold", ha="left", va="center", )
_render_panel_a(mosaic["A"], global_df) _render_panel_b(mosaic["B"], global_df)
output_dir.mkdir(parents=True, exist_ok=True) png_path = output_dir / "tail_stress_main_figure.png" pdf_path = output_dir / "tail_stress_main_figure.pdf" fig.savefig(png_path, dpi=300, facecolor="white") fig.savefig(pdf_path, dpi=300, facecolor="white") plt.close(fig) return png_path, pdf_path
def main() -> int: parser = _build_parser() args = parser.parse_args() png_path, pdf_path = render_main_figure(args.tables_dir, args.output_dir) print(png_path) print(pdf_path) return 0
if __name__ == "__main__": raise SystemExit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108#!/usr/bin/env python3"""Run the global tail-threshold sensitivity experiment."""
from __future__ import annotations
import argparseimport jsonimport sysfrom pathlib import Path
PROJECT_ROOT = Path(__file__).resolve().parents[1]if str(PROJECT_ROOT) not in sys.path: sys.path.insert(0, str(PROJECT_ROOT))
from src.eval.tail_threshold.runner import ( DEFAULT_THRESHOLD_PCTS, build_tail_threshold_preview, run_tail_threshold_experiment,)
def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser(description="Run global tail-threshold sensitivity diagnostics.") parser.add_argument("--run-tag", type=str, default=None, help="Optional output run tag.") parser.add_argument( "--datasets", type=str, default="", help="Optional comma-separated dataset ids. Empty means all datasets.", ) parser.add_argument( "--root-names", type=str, default="", help=( "Optional comma-separated synthetic root names. " "Example: TabQueryBench-SynDataSuccess-main" ), ) parser.add_argument( "--threshold-percentages", type=str, default=",".join(f"{value:g}" for value in DEFAULT_THRESHOLD_PCTS), help="Comma-separated tail thresholds in percentage points.", ) parser.add_argument( "--all-asset-runs", action="store_true", help="Disable latest-only filtering within the same model/server.", ) parser.add_argument( "--max-workers", type=int, default=4, help="Parallel workers across datasets.", ) parser.add_argument( "--representatives-per-prefix", type=int, default=2, help="How many representative datasets to keep for each prefix family.", ) parser.add_argument( "--plot-only-from-run-dir", type=Path, default=None, help="Instead of recomputing dataset outputs, rebuild summaries/figures from an existing run dir.", ) return parser.parse_args()
def _parse_threshold_percentages(text: str) -> list[float]: values: list[float] = [] for chunk in text.split(","): token = chunk.strip() if not token: continue values.append(float(token)) return values
def main() -> None: args = parse_args() datasets = [item.strip() for item in args.datasets.split(",") if item.strip()] or None root_names = [item.strip() for item in args.root_names.split(",") if item.strip()] or None if args.plot_only_from_run_dir is not None: manifest = build_tail_threshold_preview( source_run_dir=args.plot_only_from_run_dir, run_tag=args.run_tag, latest_only=not args.all_asset_runs, threshold_percentages=_parse_threshold_percentages(args.threshold_percentages), representatives_per_prefix=max(1, args.representatives_per_prefix), ) else: manifest = run_tail_threshold_experiment( run_tag=args.run_tag, datasets=datasets, latest_only=not args.all_asset_runs, root_names=root_names, threshold_percentages=_parse_threshold_percentages(args.threshold_percentages), max_workers=max(1, args.max_workers), representatives_per_prefix=max(1, args.representatives_per_prefix), ) print(json.dumps(manifest, ensure_ascii=False, indent=2))
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629"""Shared utilities for synthetic-data evaluation."""
from __future__ import annotations
import csvimport hashlibimport jsonimport mathimport osimport reimport sqlite3import timefrom collections import Counter, defaultdictfrom dataclasses import asdict, dataclassfrom datetime import datetime, timezonefrom pathlib import Pathfrom typing import Any, Iterable
from src.eval.subitem_workload_v2.paths import ( SUPPORTED_LINE_VERSIONS, normalize_line_version, registry_dir, run_manifest_dir, runs_root,)from src.eval.subitem_workload_v2.registry import load_registry_rows
PROJECT_ROOT = Path(__file__).resolve().parents[2]
def _env_path(name: str, default: Path) -> Path: value = os.environ.get(name, "").strip() return Path(value).expanduser() if value else default
DATA_ROOT = _env_path("EVAL_REAL_DATA_ROOT", PROJECT_ROOT / "data")LOGS_ROOT = _env_path("EVAL_LOGS_ROOT", PROJECT_ROOT / "logs" / "runs")OUTPUT_ROOT = _env_path("EVAL_OUTPUT_ROOT", PROJECT_ROOT / "Evaluation")SQL_RESULT_ROLE_ANNOTATION_ROOT = DATA_ROOT / "sql_result_role_annotations_v1" / "datasets"
PROVENANCE_CONTRACT_VERSION = "evaluation_source_provenance_v1"SQL_SOURCE_VERSION_ENV_VAR = "EVAL_SQL_SOURCE_VERSION"SQL_SOURCE_VERSION_V1 = "v1"SQL_SOURCE_VERSION_V2 = "v2"SQL_SOURCE_VERSION_V3 = "v3"SQL_SOURCE_VERSION_V4 = "v4"CURRENT_SQL_SOURCE_VERSIONS = tuple(SUPPORTED_LINE_VERSIONS)SQL_SOURCE_VERSION_CHOICES = ( SQL_SOURCE_VERSION_V1, *CURRENT_SQL_SOURCE_VERSIONS,)DEFAULT_SQL_SOURCE_VERSION = SQL_SOURCE_VERSION_V2
_SQL_SOURCE_LABELS = { SQL_SOURCE_VERSION_V1: "v1_legacy", SQL_SOURCE_VERSION_V2: "v2_current", SQL_SOURCE_VERSION_V3: "v3_current", SQL_SOURCE_VERSION_V4: "v4_current",}_SQL_SOURCE_DESCRIPTIONS = { SQL_SOURCE_VERSION_V1: "legacy grounded SQL runs under logs/runs/", SQL_SOURCE_VERSION_V2: "current registry-backed workload SQL under logs/subitem_workload_v2/", SQL_SOURCE_VERSION_V3: "current registry-backed workload SQL under logs/subitem_workload_v3/", SQL_SOURCE_VERSION_V4: "current registry-backed workload SQL under logs/subitem_workload_v4/",}_SQL_SOURCE_ALIASES = { "v1": SQL_SOURCE_VERSION_V1, "legacy": SQL_SOURCE_VERSION_V1, "v1_legacy": SQL_SOURCE_VERSION_V1, "logs/runs": SQL_SOURCE_VERSION_V1, "logs\\runs": SQL_SOURCE_VERSION_V1, "v2": SQL_SOURCE_VERSION_V2, "query_registry_v2": SQL_SOURCE_VERSION_V2, "current": SQL_SOURCE_VERSION_V2, "v2_current": SQL_SOURCE_VERSION_V2, "subitem_workload_v2": SQL_SOURCE_VERSION_V2, "logs/subitem_workload_v2": SQL_SOURCE_VERSION_V2, "logs\\subitem_workload_v2": SQL_SOURCE_VERSION_V2, "v3": SQL_SOURCE_VERSION_V3, "v3_current": SQL_SOURCE_VERSION_V3, "query_registry_v3": SQL_SOURCE_VERSION_V3, "subitem_workload_v3": SQL_SOURCE_VERSION_V3, "logs/subitem_workload_v3": SQL_SOURCE_VERSION_V3, "logs\\subitem_workload_v3": SQL_SOURCE_VERSION_V3, "v4": SQL_SOURCE_VERSION_V4, "v4_current": SQL_SOURCE_VERSION_V4, "query_registry_v4": SQL_SOURCE_VERSION_V4, "subitem_workload_v4": SQL_SOURCE_VERSION_V4, "logs/subitem_workload_v4": SQL_SOURCE_VERSION_V4, "logs\\subitem_workload_v4": SQL_SOURCE_VERSION_V4,}
ROOT_CONFIGS = { "SynOutput": { "path": _env_path("EVAL_SYNOUTPUT_ROOT", PROJECT_ROOT / "SynOutput"), "server_type": "rtx_pro_6000", "gpu_hour_ratio": 1.0, }, "SynOutput-5090": { "path": _env_path("EVAL_SYNOUTPUT_5090_ROOT", PROJECT_ROOT / "SynOutput-5090"), "server_type": "rtx_5090", "gpu_hour_ratio": 1.0, }, "Benchmark-trainonly-v1": { "path": _env_path("EVAL_BENCHMARK_TRAINONLY_ROOT", PROJECT_ROOT / "remote-output-Benchmark-trainonly-v1"), "server_type": "trainonly_serial", "gpu_hour_ratio": 1.0, }, "Hyperparameter-trainonly-v1": { "path": _env_path( "EVAL_HYPERPARAMETER_TRAINONLY_ROOT", PROJECT_ROOT / "hyperparameter" / "output-Benchmark-trainonly-v1", ), "server_type": "hyperparameter_trainonly", "gpu_hour_ratio": 1.0, }, "TabQueryBench-SynDataSuccess-main": { "path": _env_path( "EVAL_TABQUERYBENCH_MAIN_ROOT", Path("/data/jialinzhang/TabQueryBench/SynDataSuccess/main"), ), "server_type": "server_authoritative_main", "gpu_hour_ratio": 1.0, },}
USD_PER_GPU_HOUR = 1.0MAX_FALLBACK_GPU_SECONDS = 12 * 3600MISSING_TEXT = {"", "null", "none", "nan", "na", "n/a", "<null>"}TIMESTAMP_RE = re.compile(r"(\d{8}_\d{6})")RUNTIME_RESULT_RE = re.compile(r"(?P<prefix>.+?)__runtime_result\.json$", re.IGNORECASE)TRAIN_TIME_RE = re.compile( r"(?:totoal|total)\s+training\s+time\s*=\s*([0-9]+(?:\.[0-9]+)?)", re.IGNORECASE,)SAMPLE_TIME_RE = re.compile( r"(?:totoal|total)\s+sampling\s+time\s*=\s*([0-9]+(?:\.[0-9]+)?)", re.IGNORECASE,)GENERIC_SECONDS_RE = re.compile( r"(?:elapsed|duration|runtime|wall\s*time|completed\s+in|finished\s+in)\D+([0-9]+(?:\.[0-9]+)?)\s*(?:seconds|secs|s)?", re.IGNORECASE,)SUBITEM_RUNS_PATH_RE = re.compile( r"/logs/subitem_workload_(v[234])/runs/(?P<suffix>.+)$", re.IGNORECASE,)
@dataclassclass SyntheticAsset: dataset_id: str model_id: str server_type: str root_name: str root_path: str asset_dir: str run_id: str synthetic_csv_path: str metadata_paths: list[str] log_paths: list[str] discovered_via: str timestamp_utc: str | None synthetic_source_mtime_utc: str | None synthetic_source_size_bytes: int | None gpu_seconds_raw: float gpu_hours_equivalent: float gpu_hours_source: str cost_usd: float
@property def asset_key(self) -> str: return f"{self.dataset_id}__{self.server_type}__{self.model_id}__{self.run_id}"
@property def model_server_key(self) -> str: return f"{self.model_id}__{self.server_type}"
def to_dict(self) -> dict[str, Any]: row = asdict(self) row["asset_key"] = self.asset_key row["model_server_key"] = self.model_server_key row["provenance_contract_version"] = PROVENANCE_CONTRACT_VERSION row["synthetic_source_path"] = row["synthetic_csv_path"] row["synthetic_source_root_name"] = row["root_name"] row["synthetic_source_root_path"] = row["root_path"] row["synthetic_source_asset_dir"] = row["asset_dir"] row["synthetic_source_run_id"] = row["run_id"] row["synthetic_source_discovered_via"] = row["discovered_via"] return row
def now_run_tag() -> str: return datetime.now(timezone.utc).strftime("%Y%m%d_%H%M%S")
def read_json(path: Path, default: Any = None) -> Any: if not path.exists(): return default try: return json.loads(path.read_text(encoding="utf-8")) except Exception: return default
def write_json(path: Path, payload: Any) -> None: path.parent.mkdir(parents=True, exist_ok=True) path.write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8")
def write_jsonl(path: Path, rows: Iterable[dict[str, Any]]) -> None: path.parent.mkdir(parents=True, exist_ok=True) with path.open("w", encoding="utf-8") as f: for row in rows: f.write(json.dumps(row, ensure_ascii=False) + "\n")
def write_csv(path: Path, rows: list[dict[str, Any]], fieldnames: list[str] | None = None) -> None: path.parent.mkdir(parents=True, exist_ok=True) if fieldnames is None: keys: set[str] = set() for row in rows: keys.update(row.keys()) fieldnames = sorted(keys) with path.open("w", encoding="utf-8", newline="") as f: writer = csv.DictWriter(f, fieldnames=fieldnames) writer.writeheader() for row in rows: writer.writerow({key: row.get(key) for key in fieldnames})
def format_duration(seconds: float | int | None) -> str: if seconds is None: return "--:--:--" total_seconds = max(0, int(round(float(seconds)))) hours, rem = divmod(total_seconds, 3600) minutes, secs = divmod(rem, 60) return f"{hours:02d}:{minutes:02d}:{secs:02d}"
@dataclassclass TaskProgressTracker: task_name: str total_steps: int step_label: str = "datasets" substep_label: str = "assets" total_substeps: int = 0 completed_steps: int = 0 completed_substeps: int = 0
def __post_init__(self) -> None: self._start_ts = time.monotonic() self._last_print_ts = self._start_ts
def print_start(self, extra: str = "") -> None: parts = [ f"[{self.task_name}] start", f"{self.step_label}=0/{self.total_steps}", ] if self.total_substeps > 0: parts.append(f"{self.substep_label}=0/{self.total_substeps}") if extra: parts.append(extra) print(" | ".join(parts), flush=True)
def advance(self, *, step_name: str, substeps_done: int = 0, extra: str = "") -> None: self.completed_steps += 1 self.completed_substeps += max(0, int(substeps_done)) elapsed = time.monotonic() - self._start_ts avg_per_step = (elapsed / self.completed_steps) if self.completed_steps > 0 else None remaining_steps = max(0, self.total_steps - self.completed_steps) eta_seconds = (avg_per_step * remaining_steps) if avg_per_step is not None else None
parts = [ f"[{self.task_name}] {self.step_label}={self.completed_steps}/{self.total_steps}", ] if self.total_substeps > 0: parts.append(f"{self.substep_label}={self.completed_substeps}/{self.total_substeps}") parts.extend( [ f"elapsed={format_duration(elapsed)}", f"eta={format_duration(eta_seconds)}", f"done={step_name}", ] ) if extra: parts.append(extra) print(" | ".join(parts), flush=True)
def make_task_run_dir(task_name: str, run_tag: str) -> Path: run_dir = OUTPUT_ROOT / task_name / "runs" / run_tag run_dir.mkdir(parents=True, exist_ok=True) write_json(OUTPUT_ROOT / task_name / "LATEST_RUN.json", {"run_tag": run_tag, "run_dir": str(run_dir.resolve())}) return run_dir
def list_dataset_ids() -> list[str]: out: list[str] = [] if not DATA_ROOT.exists(): return out for path in sorted(DATA_ROOT.iterdir()): if not path.is_dir(): continue if path.name.startswith("."): continue train_csv = resolve_real_split_path(path.name, split="train") if train_csv.exists(): out.append(path.name) return out
def resolve_dataset_dir(dataset_id: str) -> Path: return DATA_ROOT / dataset_id
def resolve_real_split_path(dataset_id: str, split: str = "train") -> Path: candidates = [ DATA_ROOT / dataset_id / f"{dataset_id}-{split}.csv", DATA_ROOT / dataset_id / "raw" / f"{dataset_id}-{split}.csv", ] for path in candidates: if path.exists(): return path return candidates[0]
def resolve_field_registry_path(dataset_id: str) -> Path | None: candidates = [ DATA_ROOT / dataset_id / "metadata_core" / "field_registry.json", DATA_ROOT / dataset_id / "metadata" / "field_registry.json", ] for path in candidates: if path.exists(): return path return None
def load_field_registry(dataset_id: str) -> dict[str, Any]: path = resolve_field_registry_path(dataset_id) if path is None: return {} return read_json(path, {}) or {}
def load_field_type_hints(dataset_id: str) -> dict[str, str]: payload = load_field_registry(dataset_id) hints: dict[str, str] = {} for item in payload.get("fields", []) if isinstance(payload, dict) else []: if not isinstance(item, dict): continue name = str(item.get("name") or "").strip() if not name: continue semantic = str(item.get("semantic_type") or "").strip().lower() declared = str(item.get("declared_type") or "").strip().lower() hints[name] = semantic or declared return hints
def resolve_sql_result_role_annotation_path(dataset_id: str) -> Path: return SQL_RESULT_ROLE_ANNOTATION_ROOT / dataset_id / "outputs" / "sql_result_roles_ai_v1.json"
def load_sql_result_role_annotations( dataset_id: str, *, sql_source_version: str | None = None,) -> dict[tuple[str, str], dict[str, Any]]: path = resolve_sql_result_role_annotation_path(dataset_id) payload = read_json(path, {}) or {} query_annotations = payload.get("query_annotations") if isinstance(payload, dict) else [] requested_version = normalize_sql_source_version(sql_source_version) if sql_source_version else None
output: dict[tuple[str, str], dict[str, Any]] = {} if not isinstance(query_annotations, list): return output
for item in query_annotations: if not isinstance(item, dict): continue version_text = str(item.get("sql_source_version") or "").strip() query_id = str(item.get("query_id") or "").strip() if not query_id: continue try: normalized_version = normalize_sql_source_version(version_text or requested_version or DEFAULT_SQL_SOURCE_VERSION) except Exception: continue if requested_version and normalized_version != requested_version: continue output[(normalized_version, query_id)] = item return output
def parse_timestamp_text(value: str | None) -> datetime | None: if not value: return None text = str(value).strip() try: if text.endswith("Z"): text = text[:-1] + "+00:00" parsed = datetime.fromisoformat(text) if parsed.tzinfo is None: parsed = parsed.replace(tzinfo=timezone.utc) return parsed.astimezone(timezone.utc) except Exception: pass match = TIMESTAMP_RE.search(text) if not match: return None try: return datetime.strptime(match.group(1), "%Y%m%d_%H%M%S").replace(tzinfo=timezone.utc) except Exception: return None
def _candidate_timestamps(*values: str | Path | None) -> list[datetime]: out: list[datetime] = [] for value in values: if value is None: continue parsed = parse_timestamp_text(str(value)) if parsed is not None: out.append(parsed) return out
def _stat_mtime_ts(path: Path | None) -> datetime | None: if path is None or not path.exists(): return None try: return datetime.fromtimestamp(path.stat().st_mtime, tz=timezone.utc) except Exception: return None
def _stat_size_bytes(path: Path | None) -> int | None: if path is None or not path.exists(): return None try: return int(path.stat().st_size) except Exception: return None
def _resolved_path_text(path: Path | None) -> str: if path is None: return "" try: return str(path.expanduser().resolve()) except Exception: return str(path)
def _path_provenance_fields(prefix: str, path: Path | None) -> dict[str, Any]: mtime = _stat_mtime_ts(path) return { f"{prefix}_path": _resolved_path_text(path), f"{prefix}_exists": bool(path and path.exists()), f"{prefix}_mtime_utc": (mtime.isoformat() if mtime is not None else None), f"{prefix}_size_bytes": _stat_size_bytes(path), }
def _sha256_text(text: str) -> str: return hashlib.sha256(text.encode("utf-8")).hexdigest()
def _resolve_registry_backed_path(raw_path: str | Path | None) -> Path: text = str(raw_path or "").strip() if not text: return Path("") candidate = Path(text).expanduser() if candidate.exists(): return candidate
normalized = text.replace("\\", "/") marker = "/SQLagent/" if marker in normalized: suffix = normalized.split(marker, 1)[1].lstrip("/") rebased = (PROJECT_ROOT / suffix).resolve() if rebased.exists(): return rebased
if normalized.startswith("SQLagent/"): rebased = (PROJECT_ROOT / normalized[len("SQLagent/"):]).resolve() if rebased.exists(): return rebased
match = SUBITEM_RUNS_PATH_RE.search(normalized) if match: version = match.group(1).lower() suffix = match.group("suffix").lstrip("/") rebased = (runs_root(version) / suffix).resolve() if rebased.exists(): return rebased
return candidate
def sql_source_family(version: str | None) -> str: normalized = normalize_sql_source_version(version) return "legacy" if normalized == SQL_SOURCE_VERSION_V1 else "current"
def sql_source_line_version(version: str | None) -> str: normalized = normalize_sql_source_version(version) return normalized if normalized in CURRENT_SQL_SOURCE_VERSIONS else ""
def sql_source_registry_root(version: str | None) -> Path | None: normalized = normalize_sql_source_version(version) if normalized == SQL_SOURCE_VERSION_V1: return None return registry_dir(normalized)
def is_current_sql_source_version(version: str | None) -> bool: return normalize_sql_source_version(version) in CURRENT_SQL_SOURCE_VERSIONS
def real_split_provenance(dataset_id: str, split: str = "train") -> dict[str, Any]: real_path = resolve_real_split_path(dataset_id, split=split) return { "provenance_contract_version": PROVENANCE_CONTRACT_VERSION, "real_reference_split": split, "real_source_kind": "reference_split_csv", "real_source_dataset_id": dataset_id, "real_source_split": split, **_path_provenance_fields("real_source", real_path), }
def resolve_latest_task_run_dir(task_name: str) -> Path | None: latest_path = OUTPUT_ROOT / task_name / "LATEST_RUN.json" payload = read_json(latest_path, {}) or {} run_dir = payload.get("run_dir") if not run_dir: return None candidate = Path(str(run_dir)) return candidate if candidate.exists() else None
def resolve_requested_sql_source_version( task_name: str | None = None, default: str = DEFAULT_SQL_SOURCE_VERSION,) -> str: override = str(os.environ.get(SQL_SOURCE_VERSION_ENV_VAR) or "").strip() if override: return normalize_sql_source_version(override) if task_name: return resolve_latest_task_sql_source_version(task_name, default=default) return normalize_sql_source_version(default)
def resolve_latest_task_sql_source_version(task_name: str, default: str = DEFAULT_SQL_SOURCE_VERSION) -> str: run_dir = resolve_latest_task_run_dir(task_name) if run_dir is None: return normalize_sql_source_version(default) manifest = read_json(run_dir / "manifest.json", {}) or {} try: return normalize_sql_source_version(str(manifest.get("sql_source_version") or default)) except Exception: return normalize_sql_source_version(default)
def resolve_task_run_dir_for_sql_source( task_name: str, sql_source_version: str | None = None, *, default: str = DEFAULT_SQL_SOURCE_VERSION,) -> Path | None: requested = resolve_requested_sql_source_version(task_name=task_name, default=default) target_version = normalize_sql_source_version(sql_source_version or requested) latest_run_dir = resolve_latest_task_run_dir(task_name) if latest_run_dir is not None: latest_manifest = read_json(latest_run_dir / "manifest.json", {}) or {} latest_version = str(latest_manifest.get("sql_source_version") or "").strip() if latest_version: try: if normalize_sql_source_version(latest_version) == target_version: return latest_run_dir except Exception: pass
runs_root_dir = OUTPUT_ROOT / task_name / "runs" if not runs_root_dir.exists(): return None
ranked: list[tuple[int, int, str, Path]] = [] for candidate in runs_root_dir.iterdir(): if not candidate.is_dir(): continue manifest_path = candidate / "manifest.json" if not manifest_path.exists(): continue manifest = read_json(manifest_path, {}) or {} manifest_version = str(manifest.get("sql_source_version") or "").strip() if not manifest_version: continue try: if normalize_sql_source_version(manifest_version) != target_version: continue except Exception: continue ranked.append( ( int(manifest.get("dataset_count") or 0), int(manifest.get("asset_count") or 0), candidate.name, candidate.resolve(), ) ) if not ranked: return None ranked.sort(reverse=True) return ranked[0][3]
def build_sql_source_provenance( *, sql_source_version: str, sql_source_kind: str, sql_source_selection_mode: str, source_run_id: str = "", sql_file_path: Path | None = None, manifest_path: Path | None = None, registry_path: Path | None = None, run_dir: Path | None = None, dataset_dir: Path | None = None, registry_version: str = "", declared_version: str = "", declared_label: str = "", sql_file_sha256: str = "",) -> dict[str, Any]: normalized = normalize_sql_source_version(sql_source_version) registry_root = sql_source_registry_root(normalized) return { "provenance_contract_version": PROVENANCE_CONTRACT_VERSION, "sql_source_family": sql_source_family(normalized), "sql_source_line_version": sql_source_line_version(normalized), "sql_source_version": normalized, "sql_source_label": sql_source_label(normalized), "sql_source_description": sql_source_description(normalized), "sql_source_root": _resolved_path_text(sql_source_root(normalized)), "sql_source_registry_root": _resolved_path_text(registry_root), "sql_source_kind": sql_source_kind, "sql_source_selection_mode": sql_source_selection_mode, "sql_source_registry_version": str(registry_version or ""), "sql_source_declared_version": str(declared_version or ""), "sql_source_declared_label": str(declared_label or ""), "sql_source_file_sha256": str(sql_file_sha256 or ""), "source_run_id": str(source_run_id or ""), "sql_origin_path": _resolved_path_text(sql_file_path), **_path_provenance_fields("sql_source_file", sql_file_path), **_path_provenance_fields("sql_source_manifest", manifest_path), **_path_provenance_fields("sql_source_registry", registry_path), **_path_provenance_fields("sql_source_run_dir", run_dir), **_path_provenance_fields("sql_source_dataset_dir", dataset_dir), }
def _find_local_artifact_by_name(search_root: Path, name: str) -> Path | None: if not name: return None for path in search_root.rglob(name): if path.is_file(): return path return None
def _choose_synthetic_csv(candidates: list[Path]) -> Path | None: filtered = _list_synthetic_csv_candidates(candidates) if not filtered: return None filtered.sort(key=lambda p: (parse_timestamp_text(p.name) or _stat_mtime_ts(p) or datetime.min.replace(tzinfo=timezone.utc))) return filtered[-1]
def _list_synthetic_csv_candidates(candidates: Iterable[Path]) -> list[Path]: return [path for path in candidates if _is_synthetic_candidate_csv(path)]
def _is_synthetic_candidate_csv(path: Path) -> bool: lname = path.name.lower() stem = path.stem.lower() if "train_continuous_imputed" in lname: return False for suffix in ("real", "test", "val", "train"): if f"__{suffix}.csv" in lname or lname.endswith(f"_{suffix}.csv") or stem.endswith(f"_{suffix}"): return False return True
def _synthetic_candidate_sort_key(path: Path) -> datetime: return parse_timestamp_text(path.name) or _stat_mtime_ts(path) or datetime.min.replace(tzinfo=timezone.utc)
def _runtime_result_prefix(path: Path) -> str: match = RUNTIME_RESULT_RE.match(path.name) if match: return str(match.group("prefix") or "").strip() return path.stem
def _match_runtime_payload_for_synthetic_csv(runtime_files: list[Path], synthetic_csv_path: Path) -> tuple[dict[str, Any], Path | None]: synthetic_name = synthetic_csv_path.name for runtime_file in sorted(runtime_files, reverse=True): prefix = _runtime_result_prefix(runtime_file) if prefix and synthetic_name.startswith(prefix): return read_json(runtime_file, {}) or {}, runtime_file if runtime_files: chosen = sorted(runtime_files)[-1] return read_json(chosen, {}) or {}, chosen return {}, None
def _derive_run_id_for_candidate(runtime_run_id: str, synthetic_csv_path: Path) -> str: stem = synthetic_csv_path.stem if runtime_run_id and runtime_run_id in stem: suffix = stem.split(runtime_run_id, 1)[1].strip("_-") if suffix: return f"{runtime_run_id}__{suffix}" return runtime_run_id if runtime_run_id: return runtime_run_id return stem
def _extract_gpu_seconds_from_logs(log_paths: list[Path], synthetic_csv_path: Path | None = None) -> tuple[float, str]: explicit_seconds = 0.0 saw_explicit = False for path in log_paths: try: text = path.read_text(encoding="utf-8", errors="ignore") except Exception: continue for regex in [TRAIN_TIME_RE, SAMPLE_TIME_RE, GENERIC_SECONDS_RE]: for match in regex.findall(text): try: explicit_seconds += float(match) saw_explicit = True except Exception: continue if saw_explicit and explicit_seconds > 0: return explicit_seconds, "explicit_log_seconds"
inferred_seconds = 0.0 for path in log_paths: start_ts = parse_timestamp_text(path.name) or parse_timestamp_text(path.stem) end_ts = _stat_mtime_ts(path) if start_ts is not None and end_ts is not None: delta = (end_ts - start_ts).total_seconds() if 0 < delta <= MAX_FALLBACK_GPU_SECONDS: inferred_seconds += delta if inferred_seconds > 0: return inferred_seconds, "log_mtime_fallback"
if log_paths and synthetic_csv_path is not None and synthetic_csv_path.exists(): start_candidates = [parse_timestamp_text(path.name) for path in log_paths] start_candidates = [item for item in start_candidates if item is not None] end_ts = _stat_mtime_ts(synthetic_csv_path) if start_candidates and end_ts is not None: delta = (end_ts - min(start_candidates)).total_seconds() if 0 < delta <= MAX_FALLBACK_GPU_SECONDS: return delta, "artifact_mtime_fallback"
return 0.0, "unavailable_zero"
def _extract_gpu_seconds_from_runtime_payload(runtime_payload: dict[str, Any] | None) -> tuple[float, str] | None: if not isinstance(runtime_payload, dict): return None timings = runtime_payload.get("timings") if not isinstance(timings, dict): return None total_seconds = 0.0 saw_duration = False for stage_name in ("train", "generate"): stage_payload = timings.get(stage_name) if not isinstance(stage_payload, dict): continue raw_value = stage_payload.get("duration_sec") if raw_value is None: continue try: duration_sec = float(raw_value) except Exception: continue if duration_sec > 0: total_seconds += duration_sec saw_duration = True if saw_duration: return total_seconds, "runtime_result_timings" return None
def _hyperparameter_tabsyn_is_consistent_batch(env_overrides: dict[str, Any]) -> bool: # Accept any successful Tabsyn hyperparameter run that explicitly varies # training knobs. Older code only admitted one very specific sweep shape, # which filtered out newer smoke/BO runs (e.g. smaller batch sizes). keys = {str(k): v for k, v in env_overrides.items()} has_batch = any( str(keys.get(name) or "").strip() for name in ( "TABSYN_VAE_BATCH_SIZE", "TABSYN_DIFFUSION_BATCH_SIZE", "TABSYN_VAE_ENCODE_BATCH_SIZE", "TABSYN_VAE_EVAL_BATCH_SIZE", "TABSYN_VAE_INFER_BATCH_SIZE", ) ) has_epoch = any( str(keys.get(name) or "").strip() for name in ( "TABSYN_VAE_EPOCHS", "TABSYN_DIFFUSION_MAX_EPOCHS", ) ) if not (has_batch and has_epoch): return False num_workers = str(keys.get("TABSYN_VAE_NUM_WORKERS") or "").strip() if num_workers and num_workers != "0": return False return True
def _should_keep_hyperparameter_run(*, model_id: str, run_config_payload: dict[str, Any], runtime_payload: dict[str, Any]) -> bool: if str(runtime_payload.get("train_status") or "").strip().lower() != "success": return False if str(runtime_payload.get("generate_status") or "").strip().lower() != "success": return False env_overrides = run_config_payload.get("env_overrides") if not isinstance(env_overrides, dict) or not env_overrides: return False if str(model_id or "").strip().lower() == "tabsyn": if _hyperparameter_tabsyn_is_consistent_batch(env_overrides): return True cli_args = run_config_payload.get("cli_args") cli_args = cli_args if isinstance(cli_args, dict) else {} has_epoch_signal = bool(str(cli_args.get("epochs") or "").strip()) or any( str(env_overrides.get(name) or "").strip() for name in ("TABSYN_VAE_EPOCHS", "TABSYN_DIFFUSION_MAX_EPOCHS") ) has_batch_signal = any( str(env_overrides.get(name) or "").strip() for name in ( "TABSYN_VAE_BATCH_SIZE", "TABSYN_DIFFUSION_BATCH_SIZE", "TABSYN_VAE_ENCODE_BATCH_SIZE", "TABSYN_VAE_EVAL_BATCH_SIZE", "TABSYN_VAE_INFER_BATCH_SIZE", ) ) return has_epoch_signal and has_batch_signal return True
def _has_substantive_hyperparameter_overrides(env_overrides: dict[str, Any]) -> bool: for key, value in env_overrides.items(): if str(key).startswith("BENCHMARK_"): continue if value is None: continue if str(value).strip(): return True return False
def _build_asset( *, dataset_id: str, model_id: str, root_name: str, asset_dir: Path, run_id: str, synthetic_csv_path: Path, metadata_paths: list[Path], log_paths: list[Path], discovered_via: str, runtime_payload: dict[str, Any] | None = None,) -> SyntheticAsset: cfg = ROOT_CONFIGS[root_name] timestamp_candidates = [] timestamp_candidates.extend(_candidate_timestamps(run_id, synthetic_csv_path.name)) timestamp_candidates.extend(item for item in (_stat_mtime_ts(synthetic_csv_path), _stat_mtime_ts(asset_dir)) if item is not None) timestamp = max(timestamp_candidates) if timestamp_candidates else None runtime_timing = _extract_gpu_seconds_from_runtime_payload(runtime_payload) if runtime_timing is not None: gpu_seconds_raw, gpu_source = runtime_timing else: gpu_seconds_raw, gpu_source = _extract_gpu_seconds_from_logs(log_paths, synthetic_csv_path) gpu_hours_equivalent = (gpu_seconds_raw / 3600.0) * float(cfg["gpu_hour_ratio"]) return SyntheticAsset( dataset_id=dataset_id, model_id=model_id, server_type=str(cfg["server_type"]), root_name=root_name, root_path=str(Path(cfg["path"]).resolve()), asset_dir=str(asset_dir.resolve()), run_id=run_id, synthetic_csv_path=str(synthetic_csv_path.resolve()), metadata_paths=[str(path.resolve()) for path in metadata_paths], log_paths=[str(path.resolve()) for path in log_paths], discovered_via=discovered_via, timestamp_utc=(timestamp.isoformat() if timestamp is not None else None), synthetic_source_mtime_utc=(_stat_mtime_ts(synthetic_csv_path).isoformat() if _stat_mtime_ts(synthetic_csv_path) is not None else None), synthetic_source_size_bytes=_stat_size_bytes(synthetic_csv_path), gpu_seconds_raw=round(gpu_seconds_raw, 6), gpu_hours_equivalent=round(gpu_hours_equivalent, 6), gpu_hours_source=gpu_source, cost_usd=round(gpu_hours_equivalent * USD_PER_GPU_HOUR, 6), )
def _discover_assets_in_synoutput(dataset_id: str, root_name: str) -> list[SyntheticAsset]: root = Path(ROOT_CONFIGS[root_name]["path"]) dataset_root = root / dataset_id if not dataset_root.exists(): return [] assets: list[SyntheticAsset] = [] for model_dir in sorted(path for path in dataset_root.iterdir() if path.is_dir()): model_id = model_dir.name for run_dir in sorted(path for path in model_dir.iterdir() if path.is_dir()): manifest_path = run_dir / "manifest.json" if not manifest_path.exists(): continue manifest = read_json(manifest_path, {}) or {} runtime_result = manifest.get("runtime_result") if isinstance(manifest, dict) else {} artifacts = runtime_result.get("artifacts") if isinstance(runtime_result, dict) else {} desired_name = Path(str(artifacts.get("synthetic_csv") or "")).name synthetic_csv_path = _find_local_artifact_by_name(run_dir, desired_name) if desired_name else None if synthetic_csv_path is None: synthetic_csv_path = _choose_synthetic_csv(list((run_dir / "synthetic").glob("*.csv"))) if synthetic_csv_path is None: continue run_id = str(runtime_result.get("run_id") or manifest.get("run_id") or run_dir.name) log_paths = sorted((run_dir / "logs").glob("*.log")) metadata_paths = [manifest_path] + sorted((run_dir / "meta").glob("*.json")) assets.append( _build_asset( dataset_id=dataset_id, model_id=model_id, root_name=root_name, asset_dir=run_dir, run_id=run_id, synthetic_csv_path=synthetic_csv_path, metadata_paths=metadata_paths, log_paths=log_paths, discovered_via="manifest_json", ) ) return assets
def _discover_assets_in_synoutput_5090(dataset_id: str, root_name: str) -> list[SyntheticAsset]: root = Path(ROOT_CONFIGS[root_name]["path"]) dataset_root = root / dataset_id if not dataset_root.exists(): return [] assets: list[SyntheticAsset] = [] for model_dir in sorted(path for path in dataset_root.iterdir() if path.is_dir()): model_id = model_dir.name runtime_files = sorted((model_dir / "metadata").glob("*__runtime_result.json")) synthetic_candidates = sorted( _list_synthetic_csv_candidates((model_dir / "synthetic_data").glob("*.csv")), key=_synthetic_candidate_sort_key, ) if not synthetic_candidates: continue metadata_paths_all = sorted((model_dir / "metadata").glob("*.json")) log_paths = sorted((model_dir / "logs").glob("*.log"))
for synthetic_csv_path in synthetic_candidates: runtime_payload, matched_runtime = _match_runtime_payload_for_synthetic_csv(runtime_files, synthetic_csv_path) runtime_run_id = str(runtime_payload.get("run_id") or model_dir.name) run_id = _derive_run_id_for_candidate(runtime_run_id, synthetic_csv_path) metadata_paths = list(metadata_paths_all) if matched_runtime is not None and matched_runtime not in metadata_paths: metadata_paths = [matched_runtime] + metadata_paths assets.append( _build_asset( dataset_id=dataset_id, model_id=model_id, root_name=root_name, asset_dir=model_dir, run_id=run_id, synthetic_csv_path=synthetic_csv_path, metadata_paths=metadata_paths, log_paths=log_paths, discovered_via=("runtime_result_json_matched" if matched_runtime is not None else "synthetic_csv_scan"), ) ) return assets
def _discover_assets_in_trainonly_root(dataset_id: str, root_name: str) -> list[SyntheticAsset]: root = Path(ROOT_CONFIGS[root_name]["path"]) dataset_root = root / dataset_id if not dataset_root.exists(): return [] assets: list[SyntheticAsset] = [] for model_dir in sorted(path for path in dataset_root.iterdir() if path.is_dir()): model_id = model_dir.name for run_dir in sorted(path for path in model_dir.iterdir() if path.is_dir()): runtime_path = run_dir / "runtime_result.json" runtime_payload = read_json(runtime_path, {}) or {} if not isinstance(runtime_payload, dict): continue artifacts = runtime_payload.get("artifacts") if isinstance(runtime_payload.get("artifacts"), dict) else {} desired_name = Path(str(artifacts.get("synthetic_csv") or "")).name candidate_files = list(run_dir.glob("*.csv")) synthetic_csv_path = _find_local_artifact_by_name(run_dir, desired_name) if desired_name else None if synthetic_csv_path is None: synthetic_csv_path = _choose_synthetic_csv(candidate_files) if synthetic_csv_path is None: continue
run_id = str(runtime_payload.get("run_id") or run_dir.name) log_paths = sorted(run_dir.glob("*.log")) metadata_paths = [runtime_path] if runtime_path.exists() else [] for extra in [ run_dir / "input_snapshot.json", run_dir / "run_config.json", run_dir / "public_gate" / "public_gate_report.json", run_dir / "public_gate" / "normalized_schema_snapshot.json", run_dir / "public_gate" / "staged_input_manifest.json", ]: if extra.exists() and extra not in metadata_paths: metadata_paths.append(extra) assets.append( _build_asset( dataset_id=dataset_id, model_id=model_id, root_name=root_name, asset_dir=run_dir, run_id=run_id, synthetic_csv_path=synthetic_csv_path, metadata_paths=metadata_paths, log_paths=log_paths, discovered_via="runtime_result_json", runtime_payload=runtime_payload, ) ) return assets
def _discover_assets_in_hyperparameter_trainonly_root(dataset_id: str, root_name: str) -> list[SyntheticAsset]: root = Path(ROOT_CONFIGS[root_name]["path"]) dataset_root = root / dataset_id if not dataset_root.exists(): return [] assets: list[SyntheticAsset] = [] for model_dir in sorted(path for path in dataset_root.iterdir() if path.is_dir()): model_id = model_dir.name candidate_runs: list[tuple[Path, dict[str, Any], dict[str, Any], bool]] = [] for run_dir in sorted(path for path in model_dir.iterdir() if path.is_dir()): runtime_path = run_dir / "runtime_result.json" run_config_path = run_dir / "run_config.json" runtime_payload = read_json(runtime_path, {}) or {} run_config_payload = read_json(run_config_path, {}) or {} if not isinstance(runtime_payload, dict) or not isinstance(run_config_payload, dict): continue if not _should_keep_hyperparameter_run( model_id=model_id, run_config_payload=run_config_payload, runtime_payload=runtime_payload, ): continue env_overrides = run_config_payload.get("env_overrides") env_overrides = env_overrides if isinstance(env_overrides, dict) else {} candidate_runs.append( ( run_dir, runtime_payload, run_config_payload, _has_substantive_hyperparameter_overrides(env_overrides), ) )
if not candidate_runs: continue keep_only_substantive = any(item[3] for item in candidate_runs) for run_dir, runtime_payload, run_config_payload, has_substantive_overrides in candidate_runs: if keep_only_substantive and not has_substantive_overrides: continue artifacts = runtime_payload.get("artifacts") if isinstance(runtime_payload.get("artifacts"), dict) else {} desired_name = Path(str(artifacts.get("synthetic_csv") or "")).name candidate_files = list(run_dir.glob("*.csv")) synthetic_csv_path = _find_local_artifact_by_name(run_dir, desired_name) if desired_name else None if synthetic_csv_path is None: synthetic_csv_path = _choose_synthetic_csv(candidate_files) if synthetic_csv_path is None: continue
run_id = str(runtime_payload.get("run_id") or run_dir.name) log_paths = sorted(run_dir.glob("*.log")) metadata_paths = [runtime_path] if runtime_path.exists() else [] for extra in [ run_config_path, run_dir / "input_snapshot.json", run_dir / "public_gate" / "public_gate_report.json", run_dir / "public_gate" / "normalized_schema_snapshot.json", run_dir / "public_gate" / "staged_input_manifest.json", ]: if extra.exists() and extra not in metadata_paths: metadata_paths.append(extra) assets.append( _build_asset( dataset_id=dataset_id, model_id=model_id, root_name=root_name, asset_dir=run_dir, run_id=run_id, synthetic_csv_path=synthetic_csv_path, metadata_paths=metadata_paths, log_paths=log_paths, discovered_via="runtime_result_json_hyperparameter", runtime_payload=runtime_payload, ) ) return assets
def discover_synthetic_assets( *, datasets: list[str] | None = None, latest_only: bool = True, root_names: list[str] | tuple[str, ...] | None = None,) -> list[SyntheticAsset]: dataset_ids = datasets or list_dataset_ids() requested_roots = [str(item).strip() for item in (root_names or []) if str(item).strip()] if requested_roots: invalid = sorted(set(requested_roots) - set(ROOT_CONFIGS.keys())) if invalid: raise ValueError(f"Unsupported synthetic root names: {invalid}. Available: {sorted(ROOT_CONFIGS.keys())}") active_roots = requested_roots or list(ROOT_CONFIGS.keys()) assets: list[SyntheticAsset] = [] for dataset_id in dataset_ids: for root_name in active_roots: if root_name == "SynOutput": assets.extend(_discover_assets_in_synoutput(dataset_id, root_name)) elif root_name == "SynOutput-5090": assets.extend(_discover_assets_in_synoutput_5090(dataset_id, root_name)) elif root_name == "Benchmark-trainonly-v1": assets.extend(_discover_assets_in_trainonly_root(dataset_id, root_name)) elif root_name == "Hyperparameter-trainonly-v1": assets.extend(_discover_assets_in_hyperparameter_trainonly_root(dataset_id, root_name)) elif root_name == "TabQueryBench-SynDataSuccess-main": assets.extend(_discover_assets_in_trainonly_root(dataset_id, root_name)) if not latest_only: return sorted(assets, key=lambda item: (item.dataset_id, item.server_type, item.model_id, item.timestamp_utc or ""))
latest_map: dict[tuple[str, str, str], SyntheticAsset] = {} for asset in assets: key = (asset.dataset_id, asset.server_type, asset.model_id) current = latest_map.get(key) asset_ts = parse_timestamp_text(asset.timestamp_utc or "") current_ts = parse_timestamp_text(current.timestamp_utc or "") if current else None if current is None or ((asset_ts or datetime.min.replace(tzinfo=timezone.utc)) >= (current_ts or datetime.min.replace(tzinfo=timezone.utc))): latest_map[key] = asset return sorted(latest_map.values(), key=lambda item: (item.dataset_id, item.server_type, item.model_id))
def split_sql_statements(sql_text: str) -> list[str]: statements: list[str] = [] buf: list[str] = [] in_single = False in_double = False prev = "" for ch in sql_text: if ch == "'" and not in_double and prev != "\\": in_single = not in_single elif ch == '"' and not in_single and prev != "\\": in_double = not in_double if ch == ";" and not in_single and not in_double: stmt = "".join(buf).strip() if stmt: statements.append(stmt) buf = [] else: buf.append(ch) prev = ch tail = "".join(buf).strip() if tail: statements.append(tail) cleaned = [] for stmt in statements: lines = [line for line in stmt.splitlines() if not line.strip().startswith("--")] candidate = "\n".join(lines).strip() if candidate: cleaned.append(candidate) return cleaned
def normalize_sql_source_version(value: str | None) -> str: text = str(value or "").strip().lower() if not text: return DEFAULT_SQL_SOURCE_VERSION match = re.search(r"(v[1-4])", text) if match and match.group(1) in SQL_SOURCE_VERSION_CHOICES: candidate = match.group(1) if candidate == SQL_SOURCE_VERSION_V1 and "subitem_workload" in text: candidate = "" if candidate: return candidate version = _SQL_SOURCE_ALIASES.get(text) if version is None: raise ValueError( f"Unsupported sql source version: {value!r}. Expected one of: {', '.join(SQL_SOURCE_VERSION_CHOICES)}" ) return version
def sql_source_label(version: str | None) -> str: normalized = normalize_sql_source_version(version) return _SQL_SOURCE_LABELS[normalized]
def sql_source_description(version: str | None) -> str: normalized = normalize_sql_source_version(version) return _SQL_SOURCE_DESCRIPTIONS[normalized]
def sql_source_root(version: str | None) -> Path: normalized = normalize_sql_source_version(version) if normalized == SQL_SOURCE_VERSION_V1: return LOGS_ROOT if normalized in CURRENT_SQL_SOURCE_VERSIONS: return runs_root(normalized) raise ValueError(f"Unsupported sql source version: {version!r}")
def resolve_sql_run_dir(*, sql_source_version: str, run_id: str, dataset_id: str | None = None) -> Path: normalized = normalize_sql_source_version(sql_source_version) if normalized == SQL_SOURCE_VERSION_V1: return LOGS_ROOT / run_id if not dataset_id: raise ValueError("dataset_id is required when resolving a current workload run directory.") return runs_root(normalized) / run_id / dataset_id
def _load_latest_v1_sql_query_groups( *, dataset_ids: Iterable[str] | None = None, engines: tuple[str, ...] = ("cli",),) -> dict[tuple[str, str], dict[str, Any]]: grouped: dict[tuple[str, str], dict[str, Any]] = {} if not LOGS_ROOT.exists(): return grouped
dataset_filter = {str(item).strip() for item in dataset_ids or [] if str(item).strip()} for manifest_path in LOGS_ROOT.rglob("run_manifest.json"): payload = read_json(manifest_path, {}) or {} if str(payload.get("status") or "") != "completed": continue if str(payload.get("mode") or "") != "template_grounded_sql_qa": continue dataset_id = str(payload.get("dataset_id") or "").strip() if not dataset_id: continue if dataset_filter and dataset_id not in dataset_filter: continue engine = str(payload.get("engine") or "").strip() if engines and engine not in engines: continue question_record = payload.get("question_record") if not isinstance(question_record, dict): continue question_id = str(question_record.get("question_id") or "").strip() if not question_id: continue sql_path = manifest_path.parent / "generated_sql.sql" if not sql_path.exists(): continue ended_at = str(payload.get("ended_at") or payload.get("started_at") or "") key = (dataset_id, question_id) current = grouped.get(key) if current is None: grouped[key] = { "payload": payload, "sql_path": sql_path, "sort_dt": parse_timestamp_text(ended_at) or _stat_mtime_ts(sql_path) or datetime.min.replace(tzinfo=timezone.utc), "manifest_path": manifest_path, } continue new_dt = parse_timestamp_text(ended_at) or _stat_mtime_ts(sql_path) or datetime.min.replace(tzinfo=timezone.utc) if new_dt >= current.get("sort_dt", datetime.min.replace(tzinfo=timezone.utc)): grouped[key] = { "payload": payload, "sql_path": sql_path, "sort_dt": new_dt, "manifest_path": manifest_path, } return grouped
def _current_query_manifest_path( *, run_id: str, dataset_id: str, query_record_id: str, sql_source_version: str,) -> Path: normalized = normalize_line_version(sql_source_version) return run_manifest_dir(run_id, dataset_id, line_version=normalized) / query_record_id / "run_manifest.json"
def _load_latest_current_sql_query_groups( *, sql_source_version: str, dataset_ids: Iterable[str] | None = None, engines: tuple[str, ...] = ("cli",), require_accepted_for_eval: bool = True,) -> dict[tuple[str, str], dict[str, Any]]: grouped: dict[tuple[str, str], dict[str, Any]] = {} normalized = normalize_sql_source_version(sql_source_version) registry_root = registry_dir(normalized) if not registry_root.exists(): return grouped
dataset_filter = {str(item).strip() for item in dataset_ids or [] if str(item).strip()} for registry_path in sorted(registry_root.glob(f"*_query_registry_{normalized}.jsonl")): for row in load_registry_rows(registry_path): dataset_id = str(row.get("dataset_id") or "").strip() if not dataset_id: continue if dataset_filter and dataset_id not in dataset_filter: continue engine = str(row.get("engine") or "").strip() if engines and engine not in engines: continue if require_accepted_for_eval and not bool(row.get("accepted_for_eval")): continue query_record_id = str(row.get("query_record_id") or "").strip() if not query_record_id: continue sql_path = _resolve_registry_backed_path(row.get("sql_path")) if not sql_path.exists(): continue run_id = str(row.get("round_id") or "").strip() manifest_path = _current_query_manifest_path( run_id=run_id, dataset_id=dataset_id, query_record_id=query_record_id, sql_source_version=normalized, ) manifest = read_json(manifest_path, {}) or {} sort_dt = ( parse_timestamp_text(str(manifest.get("ended_at") or manifest.get("started_at") or "")) or _stat_mtime_ts(sql_path) or _stat_mtime_ts(manifest_path) or _stat_mtime_ts(registry_path) or datetime.min.replace(tzinfo=timezone.utc) ) key = (dataset_id, query_record_id) current = grouped.get(key) if current is None or sort_dt >= current.get("sort_dt", datetime.min.replace(tzinfo=timezone.utc)): grouped[key] = { "row": row, "sql_path": sql_path, "registry_path": registry_path, "manifest_path": manifest_path, "manifest": manifest, "sql_source_version": normalized, "sort_dt": sort_dt, } return grouped
def load_latest_sql_queries_by_dataset( *, dataset_ids: Iterable[str], engines: tuple[str, ...] = ("cli",), include_all_statements: bool = True, sql_source_version: str = DEFAULT_SQL_SOURCE_VERSION,) -> dict[str, list[dict[str, Any]]]: dataset_ids = [str(item).strip() for item in dataset_ids if str(item).strip()] normalized_source = normalize_sql_source_version(sql_source_version) rows_by_dataset: dict[str, list[dict[str, Any]]] = defaultdict(list) if normalized_source == SQL_SOURCE_VERSION_V1: grouped = _load_latest_v1_sql_query_groups(dataset_ids=dataset_ids, engines=engines) for (dataset_id, question_id), item in sorted(grouped.items()): payload = item["payload"] sql_text = item["sql_path"].read_text(encoding="utf-8", errors="ignore") sql_file_hash = _sha256_text(sql_text) statements = split_sql_statements(sql_text) if not statements: continue if not include_all_statements: statements = statements[:1] question_record = payload.get("question_record") or {} provenance = build_sql_source_provenance( sql_source_version=SQL_SOURCE_VERSION_V1, sql_source_kind="legacy_grounded_run_manifest", sql_source_selection_mode="latest_per_question_id", source_run_id=str(payload.get("run_id") or ""), sql_file_path=item["sql_path"], manifest_path=item["manifest_path"], run_dir=item["manifest_path"].parent, declared_version=str(payload.get("sql_source_version") or ""), declared_label=str(payload.get("sql_source_label") or ""), sql_file_sha256=sql_file_hash, ) for idx, statement in enumerate(statements, start=1): rows_by_dataset[dataset_id].append( { "dataset_id": dataset_id, "question_id": question_id, "query_id": f"{question_id}__sql{idx}", "sql_index": idx, "question": str(payload.get("question") or question_record.get("question") or ""), "template_id": str(question_record.get("template_id") or ""), "template_name": str(question_record.get("template_name") or ""), "family_id": str(question_record.get("primary_family") or ""), "canonical_subitem_id": str(question_record.get("canonical_subitem_id") or ""), "intended_facet_id": str(question_record.get("intended_facet_id") or ""), "variant_semantic_role": str(question_record.get("variant_semantic_role") or ""), "stable_question_id": str(question_record.get("stable_question_id") or ""), "query_identity_stable_key": str(question_record.get("query_identity_stable_key") or ""), "source_run_id": str(payload.get("run_id") or ""), "engine": str(payload.get("engine") or ""), "model": str(payload.get("model") or ""), "sql": statement, **provenance, } ) else: grouped = _load_latest_current_sql_query_groups( sql_source_version=normalized_source, dataset_ids=dataset_ids, engines=engines, require_accepted_for_eval=True, ) for (dataset_id, query_record_id), item in sorted(grouped.items()): row = item["row"] manifest = item["manifest"] if isinstance(item.get("manifest"), dict) else {} question_record = manifest.get("question_record") if isinstance(manifest, dict) else {} sql_text = item["sql_path"].read_text(encoding="utf-8", errors="ignore") sql_file_hash = str(row.get("sql_sha256") or "") or _sha256_text(sql_text) statements = split_sql_statements(sql_text) if not statements: continue if not include_all_statements: statements = statements[:1] declared_version = str(row.get("sql_source_version") or manifest.get("sql_source_version") or "") declared_label = str(row.get("sql_source_label") or manifest.get("sql_source_label") or "") run_id = str(row.get("round_id") or "") current_runs_root = runs_root(normalized_source) run_root = current_runs_root / run_id dataset_dir = run_root / dataset_id provenance = build_sql_source_provenance( sql_source_version=normalized_source, sql_source_kind="current_query_registry", sql_source_selection_mode="latest_per_query_record_id", source_run_id=run_id, sql_file_path=item["sql_path"], manifest_path=item["manifest_path"], registry_path=item["registry_path"], run_dir=run_root, dataset_dir=dataset_dir, registry_version=str(row.get("registry_version") or ""), declared_version=declared_version, declared_label=declared_label, sql_file_sha256=sql_file_hash, ) for idx, statement in enumerate(statements, start=1): query_id = query_record_id if len(statements) == 1 else f"{query_record_id}__sql{idx}" rows_by_dataset[dataset_id].append( { "dataset_id": dataset_id, "question_id": query_record_id, "query_id": query_id, "sql_index": idx, "question": str(row.get("question_text") or question_record.get("question") or ""), "template_id": str(row.get("template_id") or question_record.get("template_id") or ""), "template_name": str(row.get("template_name") or question_record.get("template_name") or ""), "family_id": str(row.get("family_id") or question_record.get("family_id") or ""), "canonical_subitem_id": str(row.get("canonical_subitem_id") or question_record.get("canonical_subitem_id") or ""), "intended_facet_id": str(row.get("intended_facet_id") or question_record.get("intended_facet_id") or ""), "variant_semantic_role": str(row.get("variant_semantic_role") or question_record.get("variant_semantic_role") or ""), "stable_question_id": query_record_id, "query_identity_stable_key": str(row.get("query_identity_stable_key") or f"{dataset_id}::{query_record_id}"), "source_run_id": run_id, "engine": str(row.get("engine") or manifest.get("engine") or ""), "model": str(manifest.get("model") or ""), "sql": statement, "accepted_for_eval": bool(row.get("accepted_for_eval")), **provenance, } ) return {dataset_id: rows_by_dataset.get(dataset_id, []) for dataset_id in dataset_ids}
def load_latest_sql_queries( *, dataset_id: str, engines: tuple[str, ...] = ("cli",), include_all_statements: bool = True, sql_source_version: str = DEFAULT_SQL_SOURCE_VERSION,) -> list[dict[str, Any]]: return load_latest_sql_queries_by_dataset( dataset_ids=[dataset_id], engines=engines, include_all_statements=include_all_statements, sql_source_version=sql_source_version, ).get(dataset_id, [])
def materialize_csv_to_sqlite(csv_path: Path, sqlite_path: Path, table_name: str) -> None: if sqlite_path.exists(): sqlite_path.unlink() sqlite_path.parent.mkdir(parents=True, exist_ok=True)
def _sqlite_ident(name: str) -> str: return f'"{str(name).replace("\"", "\"\"")}"'
def _sniff_delimiter(path: Path) -> str: try: with path.open("r", encoding="utf-8-sig", newline="") as handle: sample = handle.read(4096) dialect = csv.Sniffer().sniff(sample, delimiters=",;\t|") return dialect.delimiter except Exception: return ","
def _repair_single_field_row(row: list[str], delimiter: str) -> list[str]: if len(row) != 1: return row cell = str(row[0] or "") if delimiter not in cell: return row repaired = cell.strip() if repaired.startswith('"') and repaired.endswith('"') and len(repaired) >= 2: repaired = repaired[1:-1] repaired = repaired.replace('""', '"') try: return next(csv.reader([repaired], delimiter=delimiter)) except Exception: return repaired.split(delimiter)
def _infer_header_from_synthetic(dataset_id: str, width: int) -> list[str] | None: try: assets = discover_synthetic_assets( datasets=[dataset_id], root_names=["TabQueryBench-SynDataSuccess-main"], ) except Exception: return None for asset in assets: synthetic_path = Path(asset.synthetic_csv_path) if not synthetic_path.exists(): continue try: delimiter = _sniff_delimiter(synthetic_path) with synthetic_path.open("r", encoding="utf-8-sig", newline="") as synthetic_file: synthetic_reader = csv.reader(synthetic_file, delimiter=delimiter) synthetic_headers = next(synthetic_reader, []) except Exception: continue normalized = [str(header or "").strip() for header in synthetic_headers] if len(normalized) == width and all(normalized): return normalized return None
def _normalize_headers(first_row: list[str]) -> tuple[list[str], bool]: cleaned = [str(header or "").strip() for header in first_row] counts = Counter(cleaned) has_duplicates = any(name and count > 1 for name, count in counts.items()) has_empty = any(not name for name in cleaned) if has_duplicates or has_empty: inferred = _infer_header_from_synthetic(table_name, len(first_row)) if inferred: return inferred, True return [f"col_{idx}" for idx in range(1, len(first_row) + 1)], True return cleaned, False
conn = sqlite3.connect(sqlite_path) try: cur = conn.cursor() delimiter = _sniff_delimiter(csv_path) with csv_path.open("r", encoding="utf-8-sig", newline="") as f: reader = csv.reader(f, delimiter=delimiter) first_row = _repair_single_field_row(next(reader, []), delimiter) if not first_row: raise ValueError(f"Empty header: {csv_path}") headers, headerless = _normalize_headers(first_row) col_defs = ", ".join([f"{_sqlite_ident(header)} TEXT" for header in headers]) cur.execute(f"DROP TABLE IF EXISTS {_sqlite_ident(table_name)}") cur.execute(f"CREATE TABLE {_sqlite_ident(table_name)} ({col_defs})") placeholders = ",".join(["?" for _ in headers]) insert_sql = f"INSERT INTO {_sqlite_ident(table_name)} VALUES ({placeholders})" batch: list[list[str]] = [] if headerless: row = list(first_row) if len(row) < len(headers): row = row + [""] * (len(headers) - len(row)) elif len(row) > len(headers): row = row[: len(headers)] batch.append(row) for row in reader: row = _repair_single_field_row(row, delimiter) if len(row) < len(headers): row = row + [""] * (len(headers) - len(row)) elif len(row) > len(headers): row = row[: len(headers)] batch.append(row) if len(batch) >= 1000: cur.executemany(insert_sql, batch) batch.clear() if batch: cur.executemany(insert_sql, batch) conn.commit() finally: conn.close()
def normalize_missing(value: Any) -> bool: if value is None: return True return str(value).strip().lower() in MISSING_TEXT
def mean_or_none(values: Iterable[float | None]) -> float | None: cleaned = [float(value) for value in values if value is not None and not math.isnan(float(value))] if not cleaned: return None return sum(cleaned) / len(cleaned)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562"""Run global tail-threshold sensitivity diagnostics and visualizations."""
from __future__ import annotations
import csvimport mathimport refrom collections import Counter, defaultdictfrom concurrent.futures import ProcessPoolExecutor, as_completedfrom dataclasses import dataclassfrom pathlib import Pathfrom statistics import meanfrom typing import Any
import matplotlib
matplotlib.use("Agg")import matplotlib.pyplot as pltimport numpy as npfrom matplotlib.colors import LinearSegmentedColormap
from src.eval.common import ( SyntheticAsset, TaskProgressTracker, discover_synthetic_assets, list_dataset_ids, make_task_run_dir, now_run_tag, resolve_real_split_path, write_csv, write_json,)
PROJECT_ROOT = Path(__file__).resolve().parents[3]EVALUATION_ROOT = PROJECT_ROOT / "Evaluation"TAIL_THRESHOLD_ROOT = EVALUATION_ROOT / "tail_threshold"
DEFAULT_THRESHOLD_PCTS = [10.0, 8.0, 6.0, 4.0, 2.0, 1.0, 0.5, 0.1, 0.01, 0.001]DEFAULT_NUMERIC_BINS = 10DEFAULT_MAX_WORKERS = 4DEFAULT_REPRESENTATIVES_PER_PREFIX = 2
MODEL_LABELS = { "arf": "ARF", "bayesnet": "BayesNet", "cdtd": "CDTD", "codi": "CoDi", "ctgan": "CTGAN", "forestdiffusion": "ForestDiffusion", "goggle": "GOGGLE", "realtabformer": "RealTabFormer", "rtf": "RealTabFormer", "tabbyflow": "TabbyFlow", "tabddpm": "TabDDPM", "tabdiff": "TabDiff", "tabpfgen": "TabPFGen", "tabsyn": "TabSyn", "tvae": "TVAE",}
TAIL_COLOR = "#E76F51"HEAD_COLOR = "#4C78A8"SUBMETRIC_COLORS = { "tail_set_consistency": "#C8553D", "tail_mass_similarity": "#2A9D8F", "tail_concentration_consistency": "#6D597A", "tail_anchor_coverage": "#577590",}PREFIX_COLORS = {"c": "#577590", "m": "#43AA8B", "n": "#F3722C"}REPRESENTATIVE_KIND_COLORS = {"fragility": "#E76F51", "hardness": "#6D597A"}
@dataclass(frozen=True)class ThresholdSpec: index: int pct: float ratio: float label: str subgroup_keep_ratio: float
def _threshold_specs(percentages: list[float] | None = None) -> list[ThresholdSpec]: values = percentages or DEFAULT_THRESHOLD_PCTS specs: list[ThresholdSpec] = [] for idx, pct in enumerate(values): pct_value = float(pct) ratio = pct_value / 100.0 label = f"{pct_value:g}%" specs.append( ThresholdSpec( index=idx, pct=pct_value, ratio=ratio, label=label, subgroup_keep_ratio=max(0.0, 1.0 - ratio), ) ) return specs
def _threshold_label_token(label: str) -> str: token = re.sub(r"[^0-9A-Za-z]+", "_", str(label or "").strip()).strip("_").lower() return token or "threshold"
def _closest_threshold_label( threshold_specs: list[ThresholdSpec], target_pct: float, *, exclude: set[str] | None = None,) -> str | None: blocked = exclude or set() candidates = [spec for spec in threshold_specs if spec.label not in blocked] if not candidates: return None ranked = sorted(candidates, key=lambda spec: (abs(float(spec.pct) - float(target_pct)), -float(spec.pct), spec.index)) return ranked[0].label
def _fragility_anchor_plan(threshold_specs: list[ThresholdSpec]) -> dict[str, Any]: labels = [spec.label for spec in threshold_specs] if not labels: return { "anchor_label": None, "primary_label": None, "secondary_label": None, "rarest_label": None, "comparison_labels": [], }
anchor_label = labels[0] rarest_label = labels[-1] used = {anchor_label} primary_label = _closest_threshold_label(threshold_specs, 0.5, exclude=used) if primary_label: used.add(primary_label) secondary_label = _closest_threshold_label(threshold_specs, 0.1, exclude=used) if secondary_label: used.add(secondary_label)
comparison_labels: list[str] = [] for label in [primary_label, secondary_label, rarest_label]: if label and label != anchor_label and label not in comparison_labels: comparison_labels.append(label)
return { "anchor_label": anchor_label, "primary_label": primary_label, "secondary_label": secondary_label, "rarest_label": rarest_label, "comparison_labels": comparison_labels, }
def _score_lookup(entries: dict[str, dict[str, Any]], label: str | None) -> float | None: if not label: return None return _to_float((entries.get(label) or {}).get("tail_overall_score"))
def _attach_legacy_fragility_fields(payload: dict[str, Any], entries: dict[str, dict[str, Any]]) -> None: legacy_score_fields = { "10%": "tail_10pct", "0.5%": "tail_0_5pct", "0.1%": "tail_0_1pct", "0.001%": "tail_0_001pct", } for label, field_name in legacy_score_fields.items(): payload[field_name] = _score_lookup(entries, label)
tail_10 = payload.get("tail_10pct") tail_05 = payload.get("tail_0_5pct") tail_01 = payload.get("tail_0_1pct") tail_0001 = payload.get("tail_0_001pct") payload["fragility_10_to_0_5"] = round(float(tail_10) - float(tail_05), 6) if tail_10 is not None and tail_05 is not None else None payload["fragility_10_to_0_1"] = round(float(tail_10) - float(tail_01), 6) if tail_10 is not None and tail_01 is not None else None payload["fragility_10_to_0_001"] = ( round(float(tail_10) - float(tail_0001), 6) if tail_10 is not None and tail_0001 is not None else None )
def _read_csv_rows(path: Path) -> tuple[list[str], list[dict[str, str]]]: with path.open("r", encoding="utf-8-sig", newline="") as handle: reader = csv.DictReader(handle) rows = [dict(row) for row in reader] columns = [str(col) for col in (reader.fieldnames or [])] return columns, rows
def _to_float(value: Any) -> float | None: if value is None: return None text = str(value).strip() if not text or text.lower() in {"nan", "null", "none"}: return None try: return float(text) except Exception: return None
def _mean(values: list[float | None]) -> float | None: cleaned = [float(value) for value in values if value is not None] if not cleaned: return None return round(sum(cleaned) / len(cleaned), 6)
def _is_missing(value: Any) -> bool: if value is None: return True text = str(value).strip().lower() return text in {"", "nan", "none", "null", "na", "n/a"}
def _safe_float(value: Any) -> float | None: try: if _is_missing(value): return None return float(str(value).strip()) except Exception: return None
def _is_id_like(name: str) -> bool: text = str(name).strip().lower() return text in {"id", "row_id", "index"} or text.endswith("_id")
def _load_target_column(dataset_id: str, columns: list[str]) -> str: semantics_path = PROJECT_ROOT / "data" / dataset_id / "metadata" / "dataset_semantics.yaml" if semantics_path.exists(): for raw in semantics_path.read_text(encoding="utf-8").splitlines(): line = raw.strip() if line.startswith("target_column:"): target = line.split(":", 1)[1].strip() if target in columns: return target priors = ["class", "target", "label", "y", "outcome"] lower_map = {col.lower(): col for col in columns} for prior in priors: if prior in lower_map: return lower_map[prior] return columns[-1]
def _quantile_edges(values: list[float], bins: int) -> list[float]: if not values: return [] arr = np.asarray(values, dtype=float) quantiles = np.linspace(0, 1, bins + 1) edges = np.quantile(arr, quantiles).tolist() deduped: list[float] = [] for value in edges: current = float(value) if not deduped or abs(current - deduped[-1]) > 1e-12: deduped.append(current) return deduped
def _bin_numeric(value: float, edges: list[float]) -> str: if not edges or len(edges) < 2: return "q1" for idx in range(len(edges) - 1): left = edges[idx] right = edges[idx + 1] if idx == len(edges) - 2: if left <= value <= right: return f"q{idx + 1}" if left <= value < right: return f"q{idx + 1}" if value < edges[0]: return "below_q1" return f"above_q{len(edges) - 1}"
def _build_transformers( rows_real: list[dict[str, str]], feature_columns: list[str], numeric_bins: int,) -> dict[str, dict[str, Any]]: transformers: dict[str, dict[str, Any]] = {} for column in feature_columns: raw_values = [row.get(column) for row in rows_real] total = max(1, len(raw_values)) numeric_values = [value for value in (_safe_float(item) for item in raw_values) if value is not None] numeric_ratio = len(numeric_values) / total unique_numeric = len({round(value, 8) for value in numeric_values}) is_continuous_numeric = numeric_ratio >= 0.95 and unique_numeric >= 20 if is_continuous_numeric: transformers[column] = {"mode": "numeric_bin", "edges": _quantile_edges(numeric_values, bins=numeric_bins)} else: transformers[column] = {"mode": "categorical"} return transformers
def _tokenize(value: Any, rule: dict[str, Any]) -> str: if _is_missing(value): return "__MISSING__" mode = str(rule.get("mode") or "categorical") text = str(value).strip() if mode == "numeric_bin": numeric_value = _safe_float(value) if numeric_value is None: return "__MISSING__" return _bin_numeric(numeric_value, rule.get("edges") or []) return text
def _build_key_counter( rows: list[dict[str, str]], feature_columns: list[str], transformers: dict[str, dict[str, Any]],) -> Counter[str]: counter: Counter[str] = Counter() for row in rows: for column in feature_columns: token = _tokenize(row.get(column), transformers[column]) counter[f"{column}::{token}"] += 1 return counter
def _sorted_support_items(counter: Counter[str], *, reverse: bool) -> list[tuple[str, int]]: if reverse: return sorted(((key, int(value)) for key, value in counter.items() if int(value) > 0), key=lambda item: (-item[1], item[0])) return sorted(((key, int(value)) for key, value in counter.items() if int(value) > 0), key=lambda item: (item[1], item[0]))
def _select_bottom_band(items: list[tuple[str, int]], ratio: float) -> tuple[set[str], int]: if not items: return set(), 0 keep_n = max(1, int(math.ceil(len(items) * max(0.0, float(ratio))))) selected = items[:keep_n] gate = int(selected[-1][1]) if selected else 0 return {key for key, _ in selected}, gate
def _select_top_band(items: list[tuple[str, int]], keep_ratio: float) -> tuple[set[str], int]: if not items: return set(), 0 keep_n = max(1, int(math.ceil(len(items) * max(0.0, float(keep_ratio))))) selected = items[:keep_n] gate = int(selected[-1][1]) if selected else 0 return {key for key, _ in selected}, gate
def _tv_similarity_over_keys(real_counts: Counter[str], syn_counts: Counter[str], keys: set[str]) -> float: if not keys: return 1.0 real_total = sum(real_counts.get(key, 0) for key in keys) syn_total = sum(syn_counts.get(key, 0) for key in keys) if real_total <= 0 and syn_total <= 0: return 1.0 if real_total <= 0 or syn_total <= 0: return 0.0 tv = 0.0 for key in keys: pr = real_counts.get(key, 0) / real_total ps = syn_counts.get(key, 0) / syn_total tv += abs(pr - ps) return max(0.0, min(1.0, 1.0 - 0.5 * tv))
def _band_metrics( *, real_counts: Counter[str], syn_counts: Counter[str], n_real: int, n_syn: int, real_keys: set[str], syn_keys: set[str], effective_gate_real: int, effective_gate_syn: int,) -> dict[str, float]: union_keys = real_keys | syn_keys inter_keys = real_keys & syn_keys set_consistency = (len(inter_keys) / len(union_keys)) if union_keys else 1.0
mass_real = (sum(real_counts.get(key, 0) for key in real_keys) / max(1, n_real)) if real_keys else 0.0 mass_syn_on_real = (sum(syn_counts.get(key, 0) for key in real_keys) / max(1, n_syn)) if real_keys else 0.0 if mass_real <= 1e-12: mass_similarity = 1.0 if mass_syn_on_real <= 1e-12 else 0.0 else: mass_similarity = 1.0 - abs(mass_syn_on_real - mass_real) / mass_real mass_similarity = max(0.0, min(1.0, mass_similarity))
concentration_consistency = _tv_similarity_over_keys(real_counts, syn_counts, union_keys) anchor_coverage = (sum(1 for key in real_keys if syn_counts.get(key, 0) > 0) / len(real_keys)) if real_keys else 1.0
return { "set_consistency": float(set_consistency), "mass_similarity": float(mass_similarity), "concentration_consistency": float(concentration_consistency), "anchor_coverage": float(anchor_coverage), "real_key_count": float(len(real_keys)), "syn_key_count": float(len(syn_keys)), "union_key_count": float(len(union_keys)), "effective_gate_real": float(effective_gate_real), "effective_gate_syn": float(effective_gate_syn), }
def _normalize_model_id(model_id: str) -> str: key = str(model_id or "").strip().lower() if key == "rtf": return "realtabformer" return key
def _model_label(model_id: str) -> str: key = _normalize_model_id(model_id) return MODEL_LABELS.get(key, key or "unknown")
def _natural_key(text: str) -> list[Any]: return [int(chunk) if chunk.isdigit() else chunk.lower() for chunk in re.split(r"(\d+)", text)]
def _model_sort_key(model_id: str) -> tuple[int, Any]: return (0, _natural_key(_model_label(model_id)))
def _dataset_prefix(dataset_id: str) -> str: return str(dataset_id or "").strip().lower()[:1]
def _asset_payload(asset: SyntheticAsset) -> dict[str, Any]: payload = asset.to_dict() raw_model_id = str(payload.get("model_id") or "") payload["model_id_raw"] = raw_model_id payload["model_id"] = _normalize_model_id(raw_model_id) payload["model_label"] = _model_label(payload["model_id"]) return payload
def _run_dataset_threshold_sweep( dataset_id: str, dataset_assets: list[SyntheticAsset], threshold_specs: list[ThresholdSpec], numeric_bins: int,) -> tuple[str, list[dict[str, Any]], list[dict[str, Any]], dict[str, Any]]: real_csv = resolve_real_split_path(dataset_id, split="train") if not real_csv.exists(): return dataset_id, [], [], {"dataset_id": dataset_id, "status": "missing_real_csv", "asset_count": len(dataset_assets)}
columns, rows_real = _read_csv_rows(real_csv) if not columns or not rows_real: return dataset_id, [], [], {"dataset_id": dataset_id, "status": "empty_real_csv", "asset_count": len(dataset_assets)}
target_column = _load_target_column(dataset_id, columns) feature_columns = [column for column in columns if column != target_column and not _is_id_like(column)] if not feature_columns: return dataset_id, [], [], {"dataset_id": dataset_id, "status": "no_feature_columns", "asset_count": len(dataset_assets)}
transformers = _build_transformers(rows_real, feature_columns, numeric_bins=numeric_bins) real_counts = _build_key_counter(rows_real, feature_columns, transformers) real_tail_items = _sorted_support_items(real_counts, reverse=False) real_head_items = _sorted_support_items(real_counts, reverse=True) n_real = len(rows_real)
real_band_map: dict[str, dict[str, Any]] = {} real_diagnostic_rows: list[dict[str, Any]] = [] for spec in threshold_specs: tail_real_keys, tail_real_gate = _select_bottom_band(real_tail_items, spec.ratio) head_real_keys, head_real_gate = _select_top_band(real_head_items, spec.subgroup_keep_ratio) real_tail_mass = (sum(real_counts.get(key, 0) for key in tail_real_keys) / max(1, n_real)) if tail_real_keys else 0.0 real_head_mass = (sum(real_counts.get(key, 0) for key in head_real_keys) / max(1, n_real)) if head_real_keys else 0.0 real_band_map[spec.label] = { "tail_real_keys": tail_real_keys, "tail_real_gate": tail_real_gate, "head_real_keys": head_real_keys, "head_real_gate": head_real_gate, } real_diagnostic_rows.append( { "dataset_id": dataset_id, "dataset_prefix": _dataset_prefix(dataset_id), "threshold_label": spec.label, "threshold_pct": spec.pct, "tail_ratio": spec.ratio, "subgroup_keep_ratio": spec.subgroup_keep_ratio, "real_row_count": n_real, "real_total_key_count": len(real_tail_items), "real_tail_key_count": len(tail_real_keys), "real_head_key_count": len(head_real_keys), "real_tail_mass": round(real_tail_mass, 6), "real_head_mass": round(real_head_mass, 6), "tail_effective_gate_real": tail_real_gate, "head_effective_gate_real": head_real_gate, } )
asset_rows: list[dict[str, Any]] = [] for asset in dataset_assets: asset_payload = _asset_payload(asset) _, rows_syn = _read_csv_rows(Path(asset.synthetic_csv_path)) syn_counts = _build_key_counter(rows_syn, feature_columns, transformers) syn_tail_items = _sorted_support_items(syn_counts, reverse=False) syn_head_items = _sorted_support_items(syn_counts, reverse=True) n_syn = len(rows_syn)
for spec in threshold_specs: real_band = real_band_map[spec.label] tail_syn_keys, tail_syn_gate = _select_bottom_band(syn_tail_items, spec.ratio) head_syn_keys, head_syn_gate = _select_top_band(syn_head_items, spec.subgroup_keep_ratio)
tail_metrics = _band_metrics( real_counts=real_counts, syn_counts=syn_counts, n_real=n_real, n_syn=n_syn, real_keys=real_band["tail_real_keys"], syn_keys=tail_syn_keys, effective_gate_real=int(real_band["tail_real_gate"]), effective_gate_syn=tail_syn_gate, ) head_metrics = _band_metrics( real_counts=real_counts, syn_counts=syn_counts, n_real=n_real, n_syn=n_syn, real_keys=real_band["head_real_keys"], syn_keys=head_syn_keys, effective_gate_real=int(real_band["head_real_gate"]), effective_gate_syn=head_syn_gate, )
tail_overall_score = _mean( [ tail_metrics["set_consistency"], tail_metrics["mass_similarity"], tail_metrics["concentration_consistency"], ] ) head_overall_score = _mean( [ head_metrics["set_consistency"], head_metrics["mass_similarity"], head_metrics["concentration_consistency"], ] )
asset_rows.append( { **asset_payload, "dataset_id": dataset_id, "dataset_prefix": _dataset_prefix(dataset_id), "threshold_label": spec.label, "threshold_pct": spec.pct, "tail_ratio": spec.ratio, "subgroup_keep_ratio": spec.subgroup_keep_ratio, "real_row_count": n_real, "synthetic_row_count": n_syn, "feature_column_count": len(feature_columns), "tail_set_consistency": round(tail_metrics["set_consistency"], 6), "tail_mass_similarity": round(tail_metrics["mass_similarity"], 6), "tail_concentration_consistency": round(tail_metrics["concentration_consistency"], 6), "tail_anchor_coverage": round(tail_metrics["anchor_coverage"], 6), "tail_overall_score": tail_overall_score, "tail_real_key_count": int(tail_metrics["real_key_count"]), "tail_syn_key_count": int(tail_metrics["syn_key_count"]), "tail_union_key_count": int(tail_metrics["union_key_count"]), "tail_effective_gate_real": int(tail_metrics["effective_gate_real"]), "tail_effective_gate_syn": int(tail_metrics["effective_gate_syn"]), "head_set_consistency": round(head_metrics["set_consistency"], 6), "head_mass_similarity": round(head_metrics["mass_similarity"], 6), "head_concentration_consistency": round(head_metrics["concentration_consistency"], 6), "head_anchor_coverage": round(head_metrics["anchor_coverage"], 6), "head_proxy_overall_score": head_overall_score, "head_real_key_count": int(head_metrics["real_key_count"]), "head_syn_key_count": int(head_metrics["syn_key_count"]), "head_union_key_count": int(head_metrics["union_key_count"]), "head_effective_gate_real": int(head_metrics["effective_gate_real"]), "head_effective_gate_syn": int(head_metrics["effective_gate_syn"]), "tail_head_gap": round((head_overall_score or 0.0) - (tail_overall_score or 0.0), 6) if head_overall_score is not None and tail_overall_score is not None else None, } )
manifest_row = { "dataset_id": dataset_id, "status": "ok", "asset_count": len(dataset_assets), "real_row_count": n_real, "feature_column_count": len(feature_columns), "real_total_key_count": len(real_tail_items), } return dataset_id, asset_rows, real_diagnostic_rows, manifest_row
def _score_cmap() -> LinearSegmentedColormap: cmap = LinearSegmentedColormap.from_list( "tail_threshold_scores", ["#FFF7EC", "#FDD49E", "#FC8D59", "#D7301F", "#7F0000"], ) cmap.set_bad("#ECEFF3") return cmap
def _save(fig: plt.Figure, path: Path) -> None: path.parent.mkdir(parents=True, exist_ok=True) fig.tight_layout() fig.savefig(path, dpi=240, bbox_inches="tight") plt.close(fig)
def _threshold_axis(ax: plt.Axes, specs: list[ThresholdSpec], *, xlabel: str = "Tail threshold (% of keys)") -> None: xs = [spec.pct for spec in specs] ax.set_xscale("log") ax.invert_xaxis() ax.set_xticks(xs) ax.set_xticklabels([spec.label for spec in specs], rotation=0) ax.set_xlabel(xlabel)
def _quantile(values: list[float], q: float) -> float: if not values: return float("nan") return float(np.quantile(np.asarray(values, dtype=float), q))
def _aggregate_group_mean( rows: list[dict[str, Any]], *, group_keys: list[str], value_fields: list[str],) -> list[dict[str, Any]]: grouped: dict[tuple[Any, ...], list[dict[str, Any]]] = defaultdict(list) for row in rows: grouped[tuple(row.get(key) for key in group_keys)].append(row)
out: list[dict[str, Any]] = [] for key_tuple, items in sorted(grouped.items()): payload = {group_key: key_tuple[idx] for idx, group_key in enumerate(group_keys)} for field in value_fields: payload[field] = _mean([_to_float(item.get(field)) for item in items]) payload["asset_count"] = len(items) out.append(payload) return out
def _build_global_threshold_summary( asset_rows: list[dict[str, Any]], threshold_specs: list[ThresholdSpec],) -> list[dict[str, Any]]: out: list[dict[str, Any]] = [] for spec in threshold_specs: items = [row for row in asset_rows if row.get("threshold_label") == spec.label] if not items: continue tail_scores = [_to_float(row.get("tail_overall_score")) for row in items] head_scores = [_to_float(row.get("head_proxy_overall_score")) for row in items] tail_clean = [float(value) for value in tail_scores if value is not None] head_clean = [float(value) for value in head_scores if value is not None] out.append( { "threshold_label": spec.label, "threshold_pct": spec.pct, "tail_ratio": spec.ratio, "subgroup_keep_ratio": spec.subgroup_keep_ratio, "tail_overall_mean": _mean(tail_scores), "tail_overall_median": round(_quantile(tail_clean, 0.5), 6) if tail_clean else None, "tail_overall_p25": round(_quantile(tail_clean, 0.25), 6) if tail_clean else None, "tail_overall_p75": round(_quantile(tail_clean, 0.75), 6) if tail_clean else None, "head_proxy_mean": _mean(head_scores), "head_proxy_median": round(_quantile(head_clean, 0.5), 6) if head_clean else None, "tail_head_gap_mean": _mean([_to_float(row.get("tail_head_gap")) for row in items]), "tail_set_consistency_mean": _mean([_to_float(row.get("tail_set_consistency")) for row in items]), "tail_mass_similarity_mean": _mean([_to_float(row.get("tail_mass_similarity")) for row in items]), "tail_concentration_consistency_mean": _mean( [_to_float(row.get("tail_concentration_consistency")) for row in items] ), "tail_anchor_coverage_mean": _mean([_to_float(row.get("tail_anchor_coverage")) for row in items]), "asset_count": len(items), } ) return out
def _compute_model_fragility( model_summary_rows: list[dict[str, Any]], threshold_specs: list[ThresholdSpec],) -> list[dict[str, Any]]: by_model: dict[str, dict[str, dict[str, Any]]] = defaultdict(dict) for row in model_summary_rows: by_model[str(row.get("model_id") or "")][str(row.get("threshold_label") or "")] = row
plan = _fragility_anchor_plan(threshold_specs) anchor_label = plan["anchor_label"] comparison_labels = list(plan["comparison_labels"]) labels_to_capture = [label for label in [anchor_label, *comparison_labels] if label] out: list[dict[str, Any]] = [] for model_id in sorted(by_model.keys(), key=_model_sort_key): entries = by_model[model_id] payload = { "model_id": model_id, "model_label": _model_label(model_id), "anchor_threshold_label": anchor_label, "primary_comparison_label": plan["primary_label"], "secondary_comparison_label": plan["secondary_label"], "rarest_threshold_label": plan["rarest_label"], } for label in labels_to_capture: payload[f"tail_at_{_threshold_label_token(label)}"] = _score_lookup(entries, label)
anchor_score = _score_lookup(entries, anchor_label) payload["anchor_tail_score"] = anchor_score primary_score = _score_lookup(entries, plan["primary_label"]) secondary_score = _score_lookup(entries, plan["secondary_label"]) rarest_score = _score_lookup(entries, plan["rarest_label"]) payload["primary_comparison_tail_score"] = primary_score payload["secondary_comparison_tail_score"] = secondary_score payload["rarest_tail_score"] = rarest_score payload["primary_fragility_drop"] = ( round(float(anchor_score) - float(primary_score), 6) if anchor_score is not None and primary_score is not None else None ) payload["secondary_fragility_drop"] = ( round(float(anchor_score) - float(secondary_score), 6) if anchor_score is not None and secondary_score is not None else None ) payload["anchor_to_rarest_fragility_drop"] = ( round(float(anchor_score) - float(rarest_score), 6) if anchor_score is not None and rarest_score is not None else None ) for label in comparison_labels: compare_score = _score_lookup(entries, label) payload[f"fragility_{_threshold_label_token(anchor_label)}_to_{_threshold_label_token(label)}"] = ( round(float(anchor_score) - float(compare_score), 6) if anchor_score is not None and compare_score is not None else None ) _attach_legacy_fragility_fields(payload, entries) out.append(payload) return out
def _compute_dataset_fragility( dataset_summary_rows: list[dict[str, Any]], threshold_specs: list[ThresholdSpec],) -> list[dict[str, Any]]: by_dataset: dict[str, dict[str, dict[str, Any]]] = defaultdict(dict) for row in dataset_summary_rows: by_dataset[str(row.get("dataset_id") or "")][str(row.get("threshold_label") or "")] = row
plan = _fragility_anchor_plan(threshold_specs) anchor_label = plan["anchor_label"] comparison_labels = list(plan["comparison_labels"]) out: list[dict[str, Any]] = [] for dataset_id, entries in sorted(by_dataset.items()): anchor_score = _score_lookup(entries, anchor_label) if anchor_score is None: continue primary_score = _score_lookup(entries, plan["primary_label"]) secondary_score = _score_lookup(entries, plan["secondary_label"]) rarest_score = _score_lookup(entries, plan["rarest_label"]) payload = { "dataset_id": dataset_id, "dataset_prefix": _dataset_prefix(dataset_id), "anchor_threshold_label": anchor_label, "primary_comparison_label": plan["primary_label"], "secondary_comparison_label": plan["secondary_label"], "rarest_threshold_label": plan["rarest_label"], "anchor_tail_score": anchor_score, "primary_comparison_tail_score": primary_score, "secondary_comparison_tail_score": secondary_score, "rarest_tail_score": rarest_score, "primary_fragility_drop": round(anchor_score - primary_score, 6) if primary_score is not None else None, "secondary_fragility_drop": round(anchor_score - secondary_score, 6) if secondary_score is not None else None, "anchor_to_rarest_fragility_drop": round(anchor_score - rarest_score, 6) if rarest_score is not None else None, } for label in [anchor_label, *comparison_labels]: if label: payload[f"tail_at_{_threshold_label_token(label)}"] = _score_lookup(entries, label) for label in comparison_labels: compare_score = _score_lookup(entries, label) payload[f"fragility_{_threshold_label_token(anchor_label)}_to_{_threshold_label_token(label)}"] = ( round(anchor_score - compare_score, 6) if compare_score is not None else None ) _attach_legacy_fragility_fields(payload, entries) out.append( payload ) return out
def _select_representative_datasets( dataset_fragility_rows: list[dict[str, Any]], per_prefix: int,) -> list[dict[str, Any]]: by_prefix: dict[str, list[dict[str, Any]]] = defaultdict(list) for row in dataset_fragility_rows: by_prefix[str(row.get("dataset_prefix") or "?")].append(row)
selected: list[dict[str, Any]] = [] used: set[str] = set() for prefix in sorted(by_prefix.keys()): pool = by_prefix[prefix] fragility_candidates = sorted( [row for row in pool if row.get("primary_fragility_drop") is not None], key=lambda row: float(row["primary_fragility_drop"]), reverse=True, ) hardness_candidates = sorted( [row for row in pool if row.get("anchor_tail_score") is not None], key=lambda row: float(row["anchor_tail_score"]), )
picks: list[tuple[str, dict[str, Any]]] = [] if fragility_candidates: picks.append(("fragility", fragility_candidates[0])) for candidate in hardness_candidates: if not picks or candidate["dataset_id"] != picks[0][1]["dataset_id"]: picks.append(("hardness", candidate)) break
extra_candidates = [] for candidate in fragility_candidates: if candidate["dataset_id"] not in {row["dataset_id"] for _, row in picks}: extra_candidates.append(("fragility", candidate)) for candidate in hardness_candidates: if candidate["dataset_id"] not in {row["dataset_id"] for _, row in picks}: extra_candidates.append(("hardness", candidate))
picks = picks[:per_prefix] for kind, row in extra_candidates: if len(picks) >= per_prefix: break picks.append((kind, row))
for kind, row in picks: dataset_id = str(row["dataset_id"]) if dataset_id in used: continue used.add(dataset_id) selected.append( { **row, "selection_kind": kind, "selection_reason": ( f"largest drop from {row.get('anchor_threshold_label')} to {row.get('primary_comparison_label')}" if kind == "fragility" else f"lowest tail score already at {row.get('anchor_threshold_label')}" ), } ) return selected
def _plot_global_tail_vs_head( summary_rows: list[dict[str, Any]], threshold_specs: list[ThresholdSpec], out_path: Path,) -> None: x = [spec.pct for spec in threshold_specs] tail = [float((next(row for row in summary_rows if row["threshold_label"] == spec.label))["tail_overall_mean"]) for spec in threshold_specs] head = [float((next(row for row in summary_rows if row["threshold_label"] == spec.label))["head_proxy_mean"]) for spec in threshold_specs] p25 = [float((next(row for row in summary_rows if row["threshold_label"] == spec.label))["tail_overall_p25"]) for spec in threshold_specs] p75 = [float((next(row for row in summary_rows if row["threshold_label"] == spec.label))["tail_overall_p75"]) for spec in threshold_specs]
fig, ax = plt.subplots(figsize=(10.5, 6.0)) ax.fill_between(x, p25, p75, color=TAIL_COLOR, alpha=0.14, label="Tail IQR") ax.plot(x, tail, marker="o", linewidth=2.6, color=TAIL_COLOR, label="Tail score") ax.plot(x, head, marker="o", linewidth=2.4, color=HEAD_COLOR, label="Head proxy score") _threshold_axis(ax, threshold_specs) ax.set_ylim(0, 1.02) ax.set_ylabel("Score") ax.set_title("Global tail fragility: tail degrades faster than the head support band") ax.grid(axis="y", linestyle="--", alpha=0.28) ax.legend() _save(fig, out_path)
def _plot_global_tail_submetrics( summary_rows: list[dict[str, Any]], threshold_specs: list[ThresholdSpec], out_path: Path,) -> None: metric_fields = [ ("tail_set_consistency_mean", "Tail set consistency"), ("tail_mass_similarity_mean", "Tail mass similarity"), ("tail_concentration_consistency_mean", "Tail concentration consistency"), ("tail_anchor_coverage_mean", "Tail anchor coverage"), ] x = [spec.pct for spec in threshold_specs] fig, ax = plt.subplots(figsize=(10.5, 6.0)) for metric_field, label in metric_fields: y = [float((next(row for row in summary_rows if row["threshold_label"] == spec.label))[metric_field]) for spec in threshold_specs] ax.plot(x, y, marker="o", linewidth=2.3, label=label, color=SUBMETRIC_COLORS.get(metric_field.replace("_mean", ""), None)) _threshold_axis(ax, threshold_specs) ax.set_ylim(0, 1.02) ax.set_ylabel("Score") ax.set_title("Which tail behaviors break first as the threshold gets rarer?") ax.grid(axis="y", linestyle="--", alpha=0.28) ax.legend(loc="lower left") _save(fig, out_path)
def _plot_tail_distribution_boxplot( asset_rows: list[dict[str, Any]], threshold_specs: list[ThresholdSpec], out_path: Path,) -> None: labels = [spec.label for spec in threshold_specs] data = [ [float(row["tail_overall_score"]) for row in asset_rows if row.get("threshold_label") == spec.label and row.get("tail_overall_score") is not None] for spec in threshold_specs ] fig, ax = plt.subplots(figsize=(11.0, 6.2)) box = ax.boxplot(data, patch_artist=True, showfliers=False, widths=0.58) for patch in box["boxes"]: patch.set_facecolor("#F4A261") patch.set_alpha(0.55) patch.set_edgecolor("#9C4F2F") for median_line in box["medians"]: median_line.set_color("#7F0000") median_line.set_linewidth(1.8) ax.set_xticks(np.arange(1, len(labels) + 1)) ax.set_xticklabels(labels, rotation=25, ha="right") ax.set_ylim(0, 1.02) ax.set_ylabel("Tail overall score") ax.set_title("Asset-level tail score distribution across thresholds") ax.grid(axis="y", linestyle="--", alpha=0.25) _save(fig, out_path)
def _plot_threshold_key_diagnostics( diagnostic_rows: list[dict[str, Any]], threshold_specs: list[ThresholdSpec], out_path: Path,) -> None: x = [spec.pct for spec in threshold_specs] key_medians: list[float] = [] key_means: list[float] = [] frac_le_one: list[float] = [] frac_le_two: list[float] = [] tail_mass_medians: list[float] = [] for spec in threshold_specs: rows = [row for row in diagnostic_rows if row.get("threshold_label") == spec.label] key_counts = [float(row["real_tail_key_count"]) for row in rows] tail_masses = [float(row["real_tail_mass"]) for row in rows] key_medians.append(float(np.median(key_counts)) if key_counts else 0.0) key_means.append(float(np.mean(key_counts)) if key_counts else 0.0) frac_le_one.append((sum(1 for value in key_counts if value <= 1.0) / len(key_counts)) if key_counts else 0.0) frac_le_two.append((sum(1 for value in key_counts if value <= 2.0) / len(key_counts)) if key_counts else 0.0) tail_mass_medians.append(float(np.median(tail_masses)) if tail_masses else 0.0)
fig, axes = plt.subplots(1, 2, figsize=(13.0, 5.2))
axes[0].plot(x, key_medians, marker="o", linewidth=2.4, color="#264653", label="Median tail key count") axes[0].plot(x, key_means, marker="o", linewidth=2.0, color="#2A9D8F", label="Mean tail key count") axes[0].plot(x, tail_mass_medians, marker="o", linewidth=2.0, color="#E9C46A", label="Median real tail mass") _threshold_axis(axes[0], threshold_specs) axes[0].set_ylabel("Count / mass") axes[0].set_title("How much tail evidence is left?") axes[0].grid(axis="y", linestyle="--", alpha=0.25) axes[0].legend()
axes[1].plot(x, frac_le_one, marker="o", linewidth=2.4, color="#C8553D", label="Datasets with <= 1 tail key") axes[1].plot(x, frac_le_two, marker="o", linewidth=2.2, color="#6D597A", label="Datasets with <= 2 tail keys") _threshold_axis(axes[1], threshold_specs) axes[1].set_ylim(0, 1.02) axes[1].set_ylabel("Fraction of datasets") axes[1].set_title("When does the tail become statistically tiny?") axes[1].grid(axis="y", linestyle="--", alpha=0.25) axes[1].legend()
_save(fig, out_path)
def _plot_model_heatmap( model_summary_rows: list[dict[str, Any]], threshold_specs: list[ThresholdSpec], out_path: Path,) -> None: model_ids = sorted({str(row.get("model_id") or "") for row in model_summary_rows}, key=_model_sort_key) lookup = {(str(row["model_id"]), str(row["threshold_label"])): _to_float(row.get("tail_overall_score")) for row in model_summary_rows} mat = np.full((len(model_ids), len(threshold_specs)), np.nan, dtype=float) for row_idx, model_id in enumerate(model_ids): for col_idx, spec in enumerate(threshold_specs): value = lookup.get((model_id, spec.label)) if value is not None: mat[row_idx, col_idx] = float(value)
fig, ax = plt.subplots(figsize=(11.8, 6.6)) im = ax.imshow(mat, aspect="auto", cmap=_score_cmap(), vmin=0.0, vmax=1.0) ax.set_xticks(np.arange(len(threshold_specs))) ax.set_xticklabels([spec.label for spec in threshold_specs], rotation=25, ha="right") ax.set_yticks(np.arange(len(model_ids))) ax.set_yticklabels([_model_label(model_id) for model_id in model_ids]) ax.set_title("Model-by-threshold heatmap of tail fidelity") for row_idx in range(mat.shape[0]): for col_idx in range(mat.shape[1]): value = mat[row_idx, col_idx] if np.isnan(value): continue ax.text( col_idx, row_idx, f"{value:.2f}", ha="center", va="center", fontsize=7.5, color="white" if value >= 0.52 else "black", ) fig.colorbar(im, ax=ax, fraction=0.03, pad=0.02) _save(fig, out_path)
def _plot_model_fragility_bar( model_fragility_rows: list[dict[str, Any]], out_path: Path,) -> None: rows = [row for row in model_fragility_rows if row.get("primary_fragility_drop") is not None] if not rows: return rows = sorted(rows, key=lambda row: float(row["primary_fragility_drop"]), reverse=True) labels = [str(row["model_label"]) for row in rows] values = [float(row["primary_fragility_drop"]) for row in rows] colors = [TAIL_COLOR if value >= 0 else "#4C78A8" for value in values] anchor_label = str(rows[0].get("anchor_threshold_label") or "anchor") compare_label = str(rows[0].get("primary_comparison_label") or "comparison")
fig, ax = plt.subplots(figsize=(11.0, 6.0)) bars = ax.bar(np.arange(len(rows)), values, color=colors, alpha=0.82) ax.set_xticks(np.arange(len(rows))) ax.set_xticklabels(labels, rotation=35, ha="right") ax.set_ylabel(f"Tail fragility: score({anchor_label}) - score({compare_label})") ax.set_title("Which models lose the most once the tail becomes rarer?") ax.axhline(0.0, color="#333333", linewidth=1.0) ax.grid(axis="y", linestyle="--", alpha=0.24) for bar, value in zip(bars, values): ax.text(bar.get_x() + bar.get_width() / 2.0, value + 0.01, f"{value:.2f}", ha="center", va="bottom", fontsize=8) _save(fig, out_path)
def _plot_dataset_heatmap( dataset_summary_rows: list[dict[str, Any]], dataset_fragility_rows: list[dict[str, Any]], threshold_specs: list[ThresholdSpec], out_path: Path,) -> None: ordered_datasets = [ row["dataset_id"] for row in sorted( dataset_fragility_rows, key=lambda row: ( -float(row["primary_fragility_drop"]) if row.get("primary_fragility_drop") is not None else 0.0, str(row["dataset_id"]), ), ) ] lookup = {(str(row["dataset_id"]), str(row["threshold_label"])): _to_float(row.get("tail_overall_score")) for row in dataset_summary_rows} mat = np.full((len(ordered_datasets), len(threshold_specs)), np.nan, dtype=float) for row_idx, dataset_id in enumerate(ordered_datasets): for col_idx, spec in enumerate(threshold_specs): value = lookup.get((dataset_id, spec.label)) if value is not None: mat[row_idx, col_idx] = float(value)
fig_h = max(12.0, len(ordered_datasets) * 0.24) fig, ax = plt.subplots(figsize=(10.8, fig_h)) im = ax.imshow(mat, aspect="auto", cmap=_score_cmap(), vmin=0.0, vmax=1.0) ax.set_xticks(np.arange(len(threshold_specs))) ax.set_xticklabels([spec.label for spec in threshold_specs], rotation=25, ha="right") ax.set_yticks(np.arange(len(ordered_datasets))) ax.set_yticklabels([dataset_id.upper() for dataset_id in ordered_datasets], fontsize=8) ax.set_title("Dataset-by-threshold heatmap ordered by tail fragility") fig.colorbar(im, ax=ax, fraction=0.03, pad=0.02) _save(fig, out_path)
def _plot_prefix_lines( prefix_summary_rows: list[dict[str, Any]], threshold_specs: list[ThresholdSpec], out_path: Path,) -> None: x = [spec.pct for spec in threshold_specs] fig, ax = plt.subplots(figsize=(10.6, 6.0)) for prefix in ["c", "m", "n"]: rows = [row for row in prefix_summary_rows if row.get("dataset_prefix") == prefix] if not rows: continue lookup = {str(row["threshold_label"]): row for row in rows} y = [float(lookup[spec.label]["tail_overall_score"]) for spec in threshold_specs if lookup.get(spec.label)] x_used = [spec.pct for spec in threshold_specs if lookup.get(spec.label)] ax.plot(x_used, y, marker="o", linewidth=2.4, label=prefix.upper(), color=PREFIX_COLORS[prefix]) _threshold_axis(ax, threshold_specs) ax.set_ylim(0, 1.02) ax.set_ylabel("Tail score") ax.set_title("Tail fragility differs by dataset family") ax.grid(axis="y", linestyle="--", alpha=0.25) ax.legend(title="Dataset prefix") _save(fig, out_path)
def _plot_representative_grid( representative_rows: list[dict[str, Any]], dataset_summary_rows: list[dict[str, Any]], diagnostic_rows: list[dict[str, Any]], threshold_specs: list[ThresholdSpec], out_path: Path,) -> None: if not representative_rows: return selected_ids = [str(row["dataset_id"]) for row in representative_rows] ncols = 2 nrows = int(math.ceil(len(selected_ids) / ncols)) fig, axes = plt.subplots(nrows, ncols, figsize=(13.0, max(4.6 * nrows, 5.0))) axes_list = np.atleast_1d(axes).reshape(-1)
summary_lookup: dict[tuple[str, str], dict[str, Any]] = { (str(row["dataset_id"]), str(row["threshold_label"])): row for row in dataset_summary_rows } diag_lookup: dict[tuple[str, str], dict[str, Any]] = { (str(row["dataset_id"]), str(row["threshold_label"])): row for row in diagnostic_rows } primary_handles: list[Any] = [] primary_labels: list[str] = [] secondary_handles: list[Any] = [] secondary_labels: list[str] = []
for ax, rep in zip(axes_list, representative_rows): dataset_id = str(rep["dataset_id"]) x = [spec.pct for spec in threshold_specs] tail = [float(summary_lookup[(dataset_id, spec.label)]["tail_overall_score"]) for spec in threshold_specs] head = [float(summary_lookup[(dataset_id, spec.label)]["head_proxy_overall_score"]) for spec in threshold_specs] key_count = [float(diag_lookup[(dataset_id, spec.label)]["real_tail_key_count"]) for spec in threshold_specs] ax.plot(x, tail, marker="o", linewidth=2.4, color=TAIL_COLOR, label="Tail") ax.plot(x, head, marker="o", linewidth=2.1, color=HEAD_COLOR, label="Head proxy") _threshold_axis(ax, threshold_specs) ax.set_ylim(0, 1.02) ax.grid(axis="y", linestyle="--", alpha=0.22) ax.set_title(f"{dataset_id.upper()} | {rep['selection_kind']}: {rep['selection_reason']}") ax2 = ax.twinx() ax2.plot(x, key_count, marker="s", linewidth=1.6, color="#6D597A", alpha=0.8, label="Tail keys") ax2.set_ylabel("Real tail keys", color="#6D597A") ax2.tick_params(axis="y", labelcolor="#6D597A") if not primary_handles: primary_handles, primary_labels = ax.get_legend_handles_labels() secondary_handles, secondary_labels = ax2.get_legend_handles_labels()
for ax in axes_list[len(representative_rows) :]: ax.axis("off")
if primary_handles or secondary_handles: fig.legend(primary_handles + secondary_handles, primary_labels + secondary_labels, loc="upper center", ncol=3, frameon=False) fig.suptitle("Representative datasets where tail fidelity is especially fragile", y=1.02, fontsize=13) _save(fig, out_path)
def _plot_representative_model_lines( representative_rows: list[dict[str, Any]], model_summary_rows: list[dict[str, Any]], threshold_specs: list[ThresholdSpec], out_dir: Path,) -> list[str]: if not representative_rows: return []
figures: list[str] = [] model_lookup: dict[tuple[str, str, str], dict[str, Any]] = { (str(row["dataset_id"]), str(row["model_id"]), str(row["threshold_label"])): row for row in model_summary_rows } for rep in representative_rows: dataset_id = str(rep["dataset_id"]) dataset_rows = [row for row in model_summary_rows if row.get("dataset_id") == dataset_id] model_ids = sorted({str(row["model_id"]) for row in dataset_rows}, key=_model_sort_key) x = [spec.pct for spec in threshold_specs] fig, ax = plt.subplots(figsize=(10.8, 6.0)) for model_id in model_ids: y = [] x_used = [] for spec in threshold_specs: row = model_lookup.get((dataset_id, model_id, spec.label)) if row is None or row.get("tail_overall_score") is None: continue x_used.append(spec.pct) y.append(float(row["tail_overall_score"])) if not y: continue linewidth = 2.6 if model_id in {"realtabformer", "bayesnet", "ctgan", "tvae"} else 1.5 alpha = 0.95 if linewidth > 2.0 else 0.7 ax.plot(x_used, y, marker="o", linewidth=linewidth, alpha=alpha, label=_model_label(model_id)) _threshold_axis(ax, threshold_specs) ax.set_ylim(0, 1.02) ax.set_ylabel("Tail score") ax.set_title(f"{dataset_id.upper()} model lines across tail thresholds") ax.grid(axis="y", linestyle="--", alpha=0.24) ax.legend(ncol=2, fontsize=8) path = out_dir / f"{dataset_id}_model_lines.png" _save(fig, path) figures.append(str(path.resolve())) return figures
def _build_dataset_model_summary(asset_rows: list[dict[str, Any]]) -> list[dict[str, Any]]: grouped: dict[tuple[str, str, str], list[dict[str, Any]]] = defaultdict(list) for row in asset_rows: grouped[(str(row["dataset_id"]), str(row["model_id"]), str(row["threshold_label"]))].append(row)
out: list[dict[str, Any]] = [] for (dataset_id, model_id, threshold_label), items in sorted(grouped.items()): base = items[0] out.append( { "dataset_id": dataset_id, "dataset_prefix": base.get("dataset_prefix"), "model_id": model_id, "model_label": _model_label(model_id), "threshold_label": threshold_label, "threshold_pct": base.get("threshold_pct"), "tail_ratio": base.get("tail_ratio"), "tail_overall_score": _mean([_to_float(item.get("tail_overall_score")) for item in items]), "head_proxy_overall_score": _mean([_to_float(item.get("head_proxy_overall_score")) for item in items]), "tail_set_consistency": _mean([_to_float(item.get("tail_set_consistency")) for item in items]), "tail_mass_similarity": _mean([_to_float(item.get("tail_mass_similarity")) for item in items]), "tail_concentration_consistency": _mean( [_to_float(item.get("tail_concentration_consistency")) for item in items] ), "asset_count": len(items), } ) return out
def _load_existing_dataset_outputs(source_run_dir: Path) -> tuple[list[dict[str, Any]], list[dict[str, Any]], list[dict[str, Any]]]: asset_rows: list[dict[str, Any]] = [] diagnostic_rows: list[dict[str, Any]] = [] manifest_rows: list[dict[str, Any]] = []
datasets_dir = source_run_dir / "datasets" if not datasets_dir.exists(): return asset_rows, diagnostic_rows, manifest_rows
for dataset_dir in sorted(path for path in datasets_dir.iterdir() if path.is_dir()): dataset_id = dataset_dir.name asset_files = sorted(dataset_dir.glob("tail_threshold_asset_scores__*.csv")) diagnostic_files = sorted(dataset_dir.glob("tail_threshold_real_diagnostics__*.csv")) dataset_asset_rows: list[dict[str, Any]] = [] dataset_diagnostic_rows: list[dict[str, Any]] = [] for path in asset_files: _, rows = _read_csv_rows(path) dataset_asset_rows.extend(rows) for path in diagnostic_files: _, rows = _read_csv_rows(path) dataset_diagnostic_rows.extend(rows) asset_rows.extend(dataset_asset_rows) diagnostic_rows.extend(dataset_diagnostic_rows) manifest_rows.append( { "dataset_id": dataset_id, "status": "ok" if dataset_asset_rows or dataset_diagnostic_rows else "empty", "asset_count": len({str(row.get("asset_key") or "") for row in dataset_asset_rows if row.get("asset_key")}), "row_count": len(dataset_asset_rows), } )
return asset_rows, diagnostic_rows, manifest_rows
def _infer_threshold_specs_from_rows( asset_rows: list[dict[str, Any]], fallback_percentages: list[float] | None = None,) -> list[ThresholdSpec]: pairs: list[tuple[float, str]] = [] seen: set[tuple[float, str]] = set() for row in asset_rows: pct = _to_float(row.get("threshold_pct")) label = str(row.get("threshold_label") or "").strip() if pct is None or not label: continue key = (float(pct), label) if key in seen: continue seen.add(key) pairs.append(key) if not pairs: return _threshold_specs(fallback_percentages) pairs = sorted(pairs, key=lambda item: float(item[0]), reverse=True) return [ ThresholdSpec( index=idx, pct=float(pct), ratio=float(pct) / 100.0, label=label, subgroup_keep_ratio=max(0.0, 1.0 - (float(pct) / 100.0)), ) for idx, (pct, label) in enumerate(pairs) ]
def _materialize_tail_threshold_outputs( *, run_dir: Path, asset_rows: list[dict[str, Any]], diagnostic_rows: list[dict[str, Any]], dataset_manifest_rows: list[dict[str, Any]], threshold_specs: list[ThresholdSpec], latest_only: bool, representatives_per_prefix: int, source_run_dir: Path | None = None, synthetic_root_filter: tuple[str, ...] | list[str] | None = None,) -> dict[str, Any]: threshold_summary_rows = _build_global_threshold_summary(asset_rows, threshold_specs) model_summary_rows = _aggregate_group_mean( asset_rows, group_keys=["model_id", "model_label", "threshold_label", "threshold_pct", "tail_ratio"], value_fields=[ "tail_overall_score", "head_proxy_overall_score", "tail_set_consistency", "tail_mass_similarity", "tail_concentration_consistency", "tail_anchor_coverage", "tail_head_gap", ], ) dataset_summary_rows = _aggregate_group_mean( asset_rows, group_keys=["dataset_id", "dataset_prefix", "threshold_label", "threshold_pct", "tail_ratio"], value_fields=[ "tail_overall_score", "head_proxy_overall_score", "tail_set_consistency", "tail_mass_similarity", "tail_concentration_consistency", "tail_anchor_coverage", "tail_head_gap", ], ) prefix_summary_rows = _aggregate_group_mean( asset_rows, group_keys=["dataset_prefix", "threshold_label", "threshold_pct", "tail_ratio"], value_fields=[ "tail_overall_score", "head_proxy_overall_score", "tail_set_consistency", "tail_mass_similarity", "tail_concentration_consistency", "tail_anchor_coverage", "tail_head_gap", ], ) dataset_model_summary_rows = _build_dataset_model_summary(asset_rows) model_fragility_rows = _compute_model_fragility(model_summary_rows, threshold_specs) dataset_fragility_rows = _compute_dataset_fragility(dataset_summary_rows, threshold_specs) representative_rows = _select_representative_datasets(dataset_fragility_rows, representatives_per_prefix)
summary_dir = run_dir / "summaries" tables_dir = run_dir / "tables" figures_dir = run_dir / "figures" representatives_dir = figures_dir / "representatives" representatives_dir.mkdir(parents=True, exist_ok=True)
write_csv(summary_dir / "tail_threshold_asset_scores__all_datasets.csv", asset_rows) write_csv(summary_dir / "tail_threshold_real_diagnostics__all_datasets.csv", diagnostic_rows) write_csv(summary_dir / "tail_threshold_dataset_manifest__all_datasets.csv", dataset_manifest_rows)
write_csv(tables_dir / "global_threshold_summary.csv", threshold_summary_rows) write_csv(tables_dir / "model_threshold_summary.csv", model_summary_rows) write_csv(tables_dir / "dataset_threshold_summary.csv", dataset_summary_rows) write_csv(tables_dir / "prefix_threshold_summary.csv", prefix_summary_rows) write_csv(tables_dir / "dataset_model_threshold_summary.csv", dataset_model_summary_rows) write_csv(tables_dir / "model_fragility_summary.csv", model_fragility_rows) write_csv(tables_dir / "dataset_fragility_summary.csv", dataset_fragility_rows) write_csv(tables_dir / "representative_datasets.csv", representative_rows)
figure_paths: list[str] = []
global_tail_head = figures_dir / "01_global_tail_vs_head_proxy.png" _plot_global_tail_vs_head(threshold_summary_rows, threshold_specs, global_tail_head) figure_paths.append(str(global_tail_head.resolve()))
global_tail_submetrics = figures_dir / "02_global_tail_submetrics.png" _plot_global_tail_submetrics(threshold_summary_rows, threshold_specs, global_tail_submetrics) figure_paths.append(str(global_tail_submetrics.resolve()))
distribution_boxplot = figures_dir / "03_tail_score_distribution_boxplot.png" _plot_tail_distribution_boxplot(asset_rows, threshold_specs, distribution_boxplot) figure_paths.append(str(distribution_boxplot.resolve()))
diagnostics_plot = figures_dir / "04_threshold_key_diagnostics.png" _plot_threshold_key_diagnostics(diagnostic_rows, threshold_specs, diagnostics_plot) figure_paths.append(str(diagnostics_plot.resolve()))
model_heatmap = figures_dir / "05_model_threshold_heatmap.png" _plot_model_heatmap(model_summary_rows, threshold_specs, model_heatmap) figure_paths.append(str(model_heatmap.resolve()))
model_fragility_bar = figures_dir / "06_model_fragility_bar.png" _plot_model_fragility_bar(model_fragility_rows, model_fragility_bar) figure_paths.append(str(model_fragility_bar.resolve()))
dataset_heatmap = figures_dir / "07_dataset_threshold_heatmap.png" _plot_dataset_heatmap(dataset_summary_rows, dataset_fragility_rows, threshold_specs, dataset_heatmap) figure_paths.append(str(dataset_heatmap.resolve()))
prefix_lines = figures_dir / "08_prefix_threshold_lines.png" _plot_prefix_lines(prefix_summary_rows, threshold_specs, prefix_lines) figure_paths.append(str(prefix_lines.resolve()))
representative_grid = figures_dir / "09_representative_dataset_grid.png" _plot_representative_grid(representative_rows, dataset_summary_rows, diagnostic_rows, threshold_specs, representative_grid) if representative_grid.exists(): figure_paths.append(str(representative_grid.resolve()))
figure_paths.extend(_plot_representative_model_lines(representative_rows, dataset_model_summary_rows, threshold_specs, representatives_dir))
manifest = { "task": "tail_threshold", "run_tag": run_dir.name, "run_dir": str(run_dir.resolve()), "dataset_count": len({str(row.get('dataset_id') or '') for row in asset_rows if row.get('dataset_id')}), "asset_count": len(asset_rows), "latest_only": latest_only, "synthetic_root_filter": [str(item) for item in (synthetic_root_filter or []) if str(item).strip()], "threshold_percentages": [spec.pct for spec in threshold_specs], "threshold_labels": [spec.label for spec in threshold_specs], "representative_dataset_count": len(representative_rows), "representative_datasets": representative_rows, "source_run_dir": str(source_run_dir.resolve()) if source_run_dir is not None else None, "figure_count": len(figure_paths), "figures": figure_paths, } write_json(run_dir / "manifest.json", manifest) return manifest
def build_tail_threshold_preview( *, source_run_dir: Path, run_tag: str | None = None, latest_only: bool = True, threshold_percentages: list[float] | None = None, representatives_per_prefix: int = DEFAULT_REPRESENTATIVES_PER_PREFIX,) -> dict[str, Any]: source_dir = source_run_dir.expanduser().resolve() asset_rows, diagnostic_rows, dataset_manifest_rows = _load_existing_dataset_outputs(source_dir) if not asset_rows: raise FileNotFoundError(f"No dataset-level tail-threshold outputs found under: {source_dir}") threshold_specs = _infer_threshold_specs_from_rows(asset_rows, fallback_percentages=threshold_percentages) out_run_dir = make_task_run_dir("tail_threshold", run_tag or f"{source_dir.name}__preview") return _materialize_tail_threshold_outputs( run_dir=out_run_dir, asset_rows=asset_rows, diagnostic_rows=diagnostic_rows, dataset_manifest_rows=dataset_manifest_rows, threshold_specs=threshold_specs, latest_only=latest_only, representatives_per_prefix=representatives_per_prefix, source_run_dir=source_dir, synthetic_root_filter=None, )
def run_tail_threshold_experiment( *, run_tag: str | None = None, datasets: list[str] | None = None, latest_only: bool = True, root_names: tuple[str, ...] | list[str] | None = None, threshold_percentages: list[float] | None = None, max_workers: int = DEFAULT_MAX_WORKERS, numeric_bins: int = DEFAULT_NUMERIC_BINS, representatives_per_prefix: int = DEFAULT_REPRESENTATIVES_PER_PREFIX,) -> dict[str, Any]: dataset_ids = datasets or list_dataset_ids() threshold_specs = _threshold_specs(threshold_percentages) run_dir = make_task_run_dir("tail_threshold", run_tag or now_run_tag()) normalized_root_names = tuple(str(item).strip() for item in (root_names or []) if str(item).strip()) assets = discover_synthetic_assets( datasets=dataset_ids, latest_only=latest_only, root_names=normalized_root_names, )
asset_rows: list[dict[str, Any]] = [] diagnostic_rows: list[dict[str, Any]] = [] dataset_manifest_rows: list[dict[str, Any]] = []
dataset_asset_map = {dataset_id: [asset for asset in assets if asset.dataset_id == dataset_id] for dataset_id in dataset_ids} progress = TaskProgressTracker( task_name="tail_threshold", total_steps=len(dataset_ids), step_label="datasets", substep_label="assets", total_substeps=sum(len(dataset_asset_map.get(dataset_id, [])) for dataset_id in dataset_ids), ) progress.print_start( extra=( f"run_dir={run_dir.resolve()} | thresholds={','.join(spec.label for spec in threshold_specs)} " f"| latest_only={latest_only}" f" | roots={','.join(normalized_root_names) if normalized_root_names else 'all'}" ) )
def _consume( dataset_id: str, dataset_asset_rows: list[dict[str, Any]], dataset_diagnostic_rows: list[dict[str, Any]], manifest_row: dict[str, Any], ) -> None: dataset_manifest_rows.append(manifest_row) progress.advance( step_name=dataset_id, substeps_done=int(manifest_row.get("asset_count") or 0), extra=f"status={manifest_row.get('status')}", ) asset_rows.extend(dataset_asset_rows) diagnostic_rows.extend(dataset_diagnostic_rows) if dataset_asset_rows: write_csv( run_dir / "datasets" / dataset_id / f"tail_threshold_asset_scores__{dataset_id}.csv", dataset_asset_rows, ) if dataset_diagnostic_rows: write_csv( run_dir / "datasets" / dataset_id / f"tail_threshold_real_diagnostics__{dataset_id}.csv", dataset_diagnostic_rows, )
if max_workers > 1 and len(dataset_ids) > 1: with ProcessPoolExecutor(max_workers=max_workers) as executor: futures = { executor.submit( _run_dataset_threshold_sweep, dataset_id, dataset_asset_map.get(dataset_id, []), threshold_specs, numeric_bins, ): dataset_id for dataset_id in dataset_ids } for future in as_completed(futures): _consume(*future.result()) else: for dataset_id in dataset_ids: _consume( *_run_dataset_threshold_sweep( dataset_id, dataset_asset_map.get(dataset_id, []), threshold_specs, numeric_bins, ) )
return _materialize_tail_threshold_outputs( run_dir=run_dir, asset_rows=asset_rows, diagnostic_rows=diagnostic_rows, dataset_manifest_rows=dataset_manifest_rows, threshold_specs=threshold_specs, latest_only=latest_only, representatives_per_prefix=representatives_per_prefix, source_run_dir=None, synthetic_root_filter=normalized_root_names, )evaluation/tail/tail_threshold_code/README.mdAdded+18
evaluation/tail/tail_threshold_code/manifest.jsonAdded+17
evaluation/tail/tail_threshold_code/scripts/render_tail_metric_combined_tikz.pyAdded+245
evaluation/tail/tail_threshold_code/scripts/render_tail_metric_model_grid.pyAdded+268
evaluation/tail/tail_threshold_code/scripts/render_tail_stress_main_figure.pyAdded+377
evaluation/tail/tail_threshold_code/scripts/run_tail_threshold.pyAdded+108
evaluation/tail/tail_threshold_code/src/eval/common.pyAdded+1629
evaluation/tail/tail_threshold_code/src/eval/tail_threshold/runner.pyAdded+1562