TabQueryBench commited on
Commit
d259d61
·
verified ·
1 Parent(s): 8e333e4

Add tail threshold v2 code (numeric quantile tails, no concentration)

Browse files
evaluation/tail/tail_threshold_code_v2/src/eval/tail_threshold_v2/runner.py ADDED
@@ -0,0 +1,652 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tail-threshold v2 diagnostics with numeric-tail quantile ranges.
2
+
3
+ This implementation preserves the legacy categorical-tail logic while
4
+ introducing a true quantile-range view for numerical columns:
5
+
6
+ - categorical coverage: Jaccard over rare-support token sets
7
+ - categorical size: legacy mass-similarity on real tail states
8
+ - numerical coverage: interval-overlap consistency between real and synthetic
9
+ low/high tail ranges
10
+ - numerical size: synthetic mass captured beyond real low/high cutoffs
11
+
12
+ The legacy concentration component is intentionally removed.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import csv
18
+ import math
19
+ from collections import Counter, defaultdict
20
+ from concurrent.futures import ProcessPoolExecutor, as_completed
21
+ from dataclasses import dataclass
22
+ from pathlib import Path
23
+ from typing import Any
24
+
25
+ import numpy as np
26
+
27
+ from src.eval.common import (
28
+ SyntheticAsset,
29
+ TaskProgressTracker,
30
+ discover_synthetic_assets,
31
+ list_dataset_ids,
32
+ make_task_run_dir,
33
+ now_run_tag,
34
+ resolve_real_split_path,
35
+ write_csv,
36
+ write_json,
37
+ )
38
+ from src.eval.tail_threshold.runner import MODEL_LABELS
39
+
40
+ PROJECT_ROOT = Path(__file__).resolve().parents[3]
41
+ EVALUATION_ROOT = PROJECT_ROOT / "Evaluation"
42
+ TAIL_THRESHOLD_ROOT = EVALUATION_ROOT / "tail_threshold_v2"
43
+
44
+ DEFAULT_THRESHOLD_PCTS = [10.0, 8.0, 6.0, 4.0, 3.0, 2.0, 1.0, 0.5, 0.1]
45
+ DEFAULT_NUMERIC_BINS = 10
46
+ DEFAULT_MAX_WORKERS = 4
47
+
48
+
49
+ @dataclass(frozen=True)
50
+ class ThresholdSpec:
51
+ index: int
52
+ pct: float
53
+ ratio: float
54
+ label: str
55
+
56
+
57
+ def _threshold_specs(percentages: list[float] | None = None) -> list[ThresholdSpec]:
58
+ values = percentages or DEFAULT_THRESHOLD_PCTS
59
+ out: list[ThresholdSpec] = []
60
+ for idx, pct in enumerate(values):
61
+ value = float(pct)
62
+ out.append(ThresholdSpec(index=idx, pct=value, ratio=value / 100.0, label=f"{value:g}%"))
63
+ return out
64
+
65
+
66
+ def _to_float(value: Any) -> float | None:
67
+ if value is None:
68
+ return None
69
+ text = str(value).strip()
70
+ if not text or text.lower() in {"nan", "null", "none"}:
71
+ return None
72
+ try:
73
+ return float(text)
74
+ except Exception:
75
+ return None
76
+
77
+
78
+ def _mean(values: list[float | None]) -> float | None:
79
+ clean = [float(v) for v in values if v is not None]
80
+ if not clean:
81
+ return None
82
+ return round(sum(clean) / len(clean), 6)
83
+
84
+
85
+ def _is_missing(value: Any) -> bool:
86
+ if value is None:
87
+ return True
88
+ return str(value).strip().lower() in {"", "nan", "null", "none", "na", "n/a"}
89
+
90
+
91
+ def _safe_float(value: Any) -> float | None:
92
+ if _is_missing(value):
93
+ return None
94
+ try:
95
+ return float(str(value).strip())
96
+ except Exception:
97
+ return None
98
+
99
+
100
+ def _is_id_like(name: str) -> bool:
101
+ text = str(name).strip().lower()
102
+ return text in {"id", "row_id", "index"} or text.endswith("_id")
103
+
104
+
105
+ def _normalize_model_id(model_id: str) -> str:
106
+ key = str(model_id or "").strip().lower()
107
+ if key == "rtf":
108
+ return "realtabformer"
109
+ return key
110
+
111
+
112
+ def _model_label(model_id: str) -> str:
113
+ key = _normalize_model_id(model_id)
114
+ return MODEL_LABELS.get(key, key or "unknown")
115
+
116
+
117
+ def _dataset_prefix(dataset_id: str) -> str:
118
+ return str(dataset_id or "").strip().lower()[:1]
119
+
120
+
121
+ def _asset_payload(asset: SyntheticAsset) -> dict[str, Any]:
122
+ payload = asset.to_dict()
123
+ raw_model_id = str(payload.get("model_id") or "")
124
+ payload["model_id_raw"] = raw_model_id
125
+ payload["model_id"] = _normalize_model_id(raw_model_id)
126
+ payload["model_label"] = _model_label(payload["model_id"])
127
+ return payload
128
+
129
+
130
+ def _sniff_delimiter(path: Path) -> str:
131
+ try:
132
+ with path.open("r", encoding="utf-8-sig", newline="") as handle:
133
+ sample = handle.read(4096)
134
+ dialect = csv.Sniffer().sniff(sample, delimiters=",;\t|")
135
+ return dialect.delimiter
136
+ except Exception:
137
+ return ","
138
+
139
+
140
+ def _read_csv_rows(path: Path) -> tuple[list[str], list[dict[str, str]]]:
141
+ delimiter = _sniff_delimiter(path)
142
+ with path.open("r", encoding="utf-8-sig", newline="") as handle:
143
+ reader = csv.DictReader(handle, delimiter=delimiter)
144
+ rows = [dict(row) for row in reader]
145
+ columns = [str(col) for col in (reader.fieldnames or [])]
146
+ return columns, rows
147
+
148
+
149
+ def _load_target_column(dataset_id: str, columns: list[str]) -> str:
150
+ semantics_path = PROJECT_ROOT / "data" / dataset_id / "metadata" / "dataset_semantics.yaml"
151
+ if semantics_path.exists():
152
+ for raw in semantics_path.read_text(encoding="utf-8").splitlines():
153
+ line = raw.strip()
154
+ if line.startswith("target_column:"):
155
+ target = line.split(":", 1)[1].strip()
156
+ if target in columns:
157
+ return target
158
+ priors = ["class", "target", "label", "y", "outcome"]
159
+ lower_map = {col.lower(): col for col in columns}
160
+ for prior in priors:
161
+ if prior in lower_map:
162
+ return lower_map[prior]
163
+ return columns[-1]
164
+
165
+
166
+ def _quantile_edges(values: list[float], bins: int) -> list[float]:
167
+ if not values:
168
+ return []
169
+ arr = np.asarray(values, dtype=float)
170
+ quantiles = np.linspace(0, 1, bins + 1)
171
+ edges = np.quantile(arr, quantiles).tolist()
172
+ deduped: list[float] = []
173
+ for value in edges:
174
+ current = float(value)
175
+ if not deduped or abs(current - deduped[-1]) > 1e-12:
176
+ deduped.append(current)
177
+ return deduped
178
+
179
+
180
+ def _build_transformers(
181
+ rows_real: list[dict[str, str]],
182
+ feature_columns: list[str],
183
+ numeric_bins: int,
184
+ ) -> dict[str, dict[str, Any]]:
185
+ transformers: dict[str, dict[str, Any]] = {}
186
+ for column in feature_columns:
187
+ raw_values = [row.get(column) for row in rows_real]
188
+ total = max(1, len(raw_values))
189
+ numeric_values = [value for value in (_safe_float(item) for item in raw_values) if value is not None]
190
+ numeric_ratio = len(numeric_values) / total
191
+ unique_numeric = len({round(value, 8) for value in numeric_values})
192
+ is_continuous_numeric = numeric_ratio >= 0.95 and unique_numeric >= 20
193
+ if is_continuous_numeric:
194
+ transformers[column] = {"mode": "numeric", "edges": _quantile_edges(numeric_values, bins=numeric_bins)}
195
+ else:
196
+ transformers[column] = {"mode": "categorical"}
197
+ return transformers
198
+
199
+
200
+ def _tokenize_categorical(value: Any) -> str:
201
+ if _is_missing(value):
202
+ return "__MISSING__"
203
+ return str(value).strip()
204
+
205
+
206
+ def _sorted_support_items(counter: Counter[str], *, reverse: bool) -> list[tuple[str, int]]:
207
+ if reverse:
208
+ return sorted(((key, int(value)) for key, value in counter.items() if int(value) > 0), key=lambda item: (-item[1], item[0]))
209
+ return sorted(((key, int(value)) for key, value in counter.items() if int(value) > 0), key=lambda item: (item[1], item[0]))
210
+
211
+
212
+ def _select_bottom_band(items: list[tuple[str, int]], ratio: float) -> tuple[set[str], int]:
213
+ if not items:
214
+ return set(), 0
215
+ keep_n = max(1, int(math.ceil(len(items) * max(0.0, float(ratio)))))
216
+ selected = items[:keep_n]
217
+ gate = int(selected[-1][1]) if selected else 0
218
+ return {key for key, _ in selected}, gate
219
+
220
+
221
+ def _categorical_metrics(real_tokens: list[str], syn_tokens: list[str], ratio: float) -> dict[str, Any]:
222
+ real_counts = Counter(real_tokens)
223
+ syn_counts = Counter(syn_tokens)
224
+ real_items = _sorted_support_items(real_counts, reverse=False)
225
+ syn_items = _sorted_support_items(syn_counts, reverse=False)
226
+ real_keys, real_gate = _select_bottom_band(real_items, ratio)
227
+ syn_keys, syn_gate = _select_bottom_band(syn_items, ratio)
228
+ union_keys = real_keys | syn_keys
229
+ inter_keys = real_keys & syn_keys
230
+ coverage = (len(inter_keys) / len(union_keys)) if union_keys else 1.0
231
+ mass_real = (sum(real_counts.get(key, 0) for key in real_keys) / max(1, len(real_tokens))) if real_keys else 0.0
232
+ mass_syn_on_real = (sum(syn_counts.get(key, 0) for key in real_keys) / max(1, len(syn_tokens))) if real_keys else 0.0
233
+ if mass_real <= 1e-12:
234
+ size = 1.0 if mass_syn_on_real <= 1e-12 else 0.0
235
+ else:
236
+ size = 1.0 - abs(mass_syn_on_real - mass_real) / mass_real
237
+ size = max(0.0, min(1.0, size))
238
+ return {
239
+ "coverage": float(coverage),
240
+ "size": float(size),
241
+ "real_tail_token_count": len(real_keys),
242
+ "syn_tail_token_count": len(syn_keys),
243
+ "effective_gate_real": real_gate,
244
+ "effective_gate_syn": syn_gate,
245
+ "real_tail_mass": float(mass_real),
246
+ "syn_tail_mass_on_real": float(mass_syn_on_real),
247
+ }
248
+
249
+
250
+ def _interval_overlap_score(a0: float, a1: float, b0: float, b1: float) -> float:
251
+ left = max(min(a0, a1), min(b0, b1))
252
+ right = min(max(a0, a1), max(b0, b1))
253
+ overlap = max(0.0, right - left)
254
+ union_left = min(a0, a1, b0, b1)
255
+ union_right = max(a0, a1, b0, b1)
256
+ union = max(0.0, union_right - union_left)
257
+ if union <= 1e-12:
258
+ return 1.0 if abs(a0 - b0) <= 1e-12 and abs(a1 - b1) <= 1e-12 else 0.0
259
+ return max(0.0, min(1.0, overlap / union))
260
+
261
+
262
+ def _numeric_metrics(real_values: list[float], syn_values: list[float], ratio: float) -> dict[str, Any]:
263
+ real_arr = np.asarray(real_values, dtype=float)
264
+ syn_arr = np.asarray(syn_values, dtype=float)
265
+ q_real_low = float(np.quantile(real_arr, ratio))
266
+ q_real_high = float(np.quantile(real_arr, 1.0 - ratio))
267
+ q_syn_low = float(np.quantile(syn_arr, ratio))
268
+ q_syn_high = float(np.quantile(syn_arr, 1.0 - ratio))
269
+ real_min = float(np.min(real_arr))
270
+ real_max = float(np.max(real_arr))
271
+ syn_min = float(np.min(syn_arr))
272
+ syn_max = float(np.max(syn_arr))
273
+
274
+ coverage_low = _interval_overlap_score(real_min, q_real_low, syn_min, q_syn_low)
275
+ coverage_high = _interval_overlap_score(q_real_high, real_max, q_syn_high, syn_max)
276
+ coverage = 0.5 * (coverage_low + coverage_high)
277
+
278
+ syn_low_mass = float(np.mean(syn_arr <= q_real_low))
279
+ syn_high_mass = float(np.mean(syn_arr >= q_real_high))
280
+ size_low = min(syn_low_mass / ratio, 1.0) if ratio > 0 else 1.0
281
+ size_high = min(syn_high_mass / ratio, 1.0) if ratio > 0 else 1.0
282
+ size = 0.5 * (size_low + size_high)
283
+
284
+ return {
285
+ "coverage": float(max(0.0, min(1.0, coverage))),
286
+ "size": float(max(0.0, min(1.0, size))),
287
+ "coverage_low": float(coverage_low),
288
+ "coverage_high": float(coverage_high),
289
+ "size_low": float(size_low),
290
+ "size_high": float(size_high),
291
+ "real_low_cutoff": q_real_low,
292
+ "real_high_cutoff": q_real_high,
293
+ "syn_low_cutoff": q_syn_low,
294
+ "syn_high_cutoff": q_syn_high,
295
+ "real_min": real_min,
296
+ "real_max": real_max,
297
+ "syn_min": syn_min,
298
+ "syn_max": syn_max,
299
+ "syn_low_mass_at_real_cutoff": syn_low_mass,
300
+ "syn_high_mass_at_real_cutoff": syn_high_mass,
301
+ }
302
+
303
+
304
+ def _run_dataset_threshold_sweep(
305
+ dataset_id: str,
306
+ dataset_assets: list[SyntheticAsset],
307
+ threshold_specs: list[ThresholdSpec],
308
+ numeric_bins: int,
309
+ ) -> tuple[str, list[dict[str, Any]], list[dict[str, Any]], list[dict[str, Any]], dict[str, Any]]:
310
+ real_csv = resolve_real_split_path(dataset_id, split="train")
311
+ if not real_csv.exists():
312
+ return dataset_id, [], [], [], {"dataset_id": dataset_id, "status": "missing_real_csv", "asset_count": len(dataset_assets)}
313
+
314
+ columns, rows_real = _read_csv_rows(real_csv)
315
+ if not columns or not rows_real:
316
+ return dataset_id, [], [], [], {"dataset_id": dataset_id, "status": "empty_real_csv", "asset_count": len(dataset_assets)}
317
+
318
+ target_column = _load_target_column(dataset_id, columns)
319
+ feature_columns = [column for column in columns if column != target_column and not _is_id_like(column)]
320
+ if not feature_columns:
321
+ return dataset_id, [], [], [], {"dataset_id": dataset_id, "status": "no_feature_columns", "asset_count": len(dataset_assets)}
322
+
323
+ transformers = _build_transformers(rows_real, feature_columns, numeric_bins=numeric_bins)
324
+ n_real = len(rows_real)
325
+
326
+ real_column_cache: dict[str, dict[str, Any]] = {}
327
+ for column in feature_columns:
328
+ mode = str(transformers[column].get("mode") or "categorical")
329
+ if mode == "numeric":
330
+ values = [v for v in (_safe_float(row.get(column)) for row in rows_real) if v is not None]
331
+ real_column_cache[column] = {"mode": "numeric", "values": values}
332
+ else:
333
+ real_column_cache[column] = {
334
+ "mode": "categorical",
335
+ "tokens": [_tokenize_categorical(row.get(column)) for row in rows_real],
336
+ }
337
+
338
+ asset_rows: list[dict[str, Any]] = []
339
+ column_rows: list[dict[str, Any]] = []
340
+ real_diagnostic_rows: list[dict[str, Any]] = []
341
+
342
+ for asset in dataset_assets:
343
+ asset_payload = _asset_payload(asset)
344
+ _, rows_syn = _read_csv_rows(Path(asset.synthetic_csv_path))
345
+ n_syn = len(rows_syn)
346
+
347
+ syn_column_cache: dict[str, dict[str, Any]] = {}
348
+ for column in feature_columns:
349
+ mode = str(transformers[column].get("mode") or "categorical")
350
+ if mode == "numeric":
351
+ values = [v for v in (_safe_float(row.get(column)) for row in rows_syn) if v is not None]
352
+ syn_column_cache[column] = {"mode": "numeric", "values": values}
353
+ else:
354
+ syn_column_cache[column] = {
355
+ "mode": "categorical",
356
+ "tokens": [_tokenize_categorical(row.get(column)) for row in rows_syn],
357
+ }
358
+
359
+ for spec in threshold_specs:
360
+ coverage_values: list[float] = []
361
+ size_values: list[float] = []
362
+ cat_coverage_values: list[float] = []
363
+ cat_size_values: list[float] = []
364
+ num_coverage_values: list[float] = []
365
+ num_size_values: list[float] = []
366
+ active_cat = 0
367
+ active_num = 0
368
+
369
+ for column in feature_columns:
370
+ real_meta = real_column_cache[column]
371
+ syn_meta = syn_column_cache[column]
372
+ mode = str(real_meta.get("mode") or "categorical")
373
+ if mode == "numeric":
374
+ real_values = list(real_meta.get("values") or [])
375
+ syn_values = list(syn_meta.get("values") or [])
376
+ if len(real_values) < 2 or len(syn_values) < 2:
377
+ continue
378
+ metrics = _numeric_metrics(real_values, syn_values, spec.ratio)
379
+ active_num += 1
380
+ num_coverage_values.append(metrics["coverage"])
381
+ num_size_values.append(metrics["size"])
382
+ else:
383
+ real_tokens = list(real_meta.get("tokens") or [])
384
+ syn_tokens = list(syn_meta.get("tokens") or [])
385
+ if not real_tokens or not syn_tokens:
386
+ continue
387
+ metrics = _categorical_metrics(real_tokens, syn_tokens, spec.ratio)
388
+ active_cat += 1
389
+ cat_coverage_values.append(metrics["coverage"])
390
+ cat_size_values.append(metrics["size"])
391
+
392
+ coverage_values.append(metrics["coverage"])
393
+ size_values.append(metrics["size"])
394
+ column_rows.append(
395
+ {
396
+ **asset_payload,
397
+ "dataset_id": dataset_id,
398
+ "dataset_prefix": _dataset_prefix(dataset_id),
399
+ "threshold_label": spec.label,
400
+ "threshold_pct": spec.pct,
401
+ "tail_ratio": spec.ratio,
402
+ "column_name": column,
403
+ "column_mode": mode,
404
+ "coverage_score": round(float(metrics["coverage"]), 6),
405
+ "size_score": round(float(metrics["size"]), 6),
406
+ **{key: (round(float(value), 6) if isinstance(value, float) else value) for key, value in metrics.items()},
407
+ }
408
+ )
409
+
410
+ tail_coverage = _mean(coverage_values)
411
+ tail_size = _mean(size_values)
412
+ tail_overall = _mean([tail_coverage, tail_size])
413
+ asset_rows.append(
414
+ {
415
+ **asset_payload,
416
+ "dataset_id": dataset_id,
417
+ "dataset_prefix": _dataset_prefix(dataset_id),
418
+ "threshold_label": spec.label,
419
+ "threshold_pct": spec.pct,
420
+ "tail_ratio": spec.ratio,
421
+ "real_row_count": n_real,
422
+ "synthetic_row_count": n_syn,
423
+ "feature_column_count": len(feature_columns),
424
+ "active_categorical_columns": active_cat,
425
+ "active_numeric_columns": active_num,
426
+ "tail_coverage_score": tail_coverage,
427
+ "tail_size_score": tail_size,
428
+ "tail_overall_score": tail_overall,
429
+ "categorical_coverage_score": _mean(cat_coverage_values),
430
+ "categorical_size_score": _mean(cat_size_values),
431
+ "numerical_coverage_score": _mean(num_coverage_values),
432
+ "numerical_size_score": _mean(num_size_values),
433
+ }
434
+ )
435
+
436
+ for spec in threshold_specs:
437
+ items = [row for row in asset_rows if row.get("threshold_label") == spec.label]
438
+ real_diagnostic_rows.append(
439
+ {
440
+ "dataset_id": dataset_id,
441
+ "dataset_prefix": _dataset_prefix(dataset_id),
442
+ "threshold_label": spec.label,
443
+ "threshold_pct": spec.pct,
444
+ "tail_ratio": spec.ratio,
445
+ "real_row_count": n_real,
446
+ "feature_column_count": len(feature_columns),
447
+ "asset_count": len(items),
448
+ "tail_overall_mean": _mean([_to_float(row.get("tail_overall_score")) for row in items]),
449
+ "tail_coverage_mean": _mean([_to_float(row.get("tail_coverage_score")) for row in items]),
450
+ "tail_size_mean": _mean([_to_float(row.get("tail_size_score")) for row in items]),
451
+ "categorical_coverage_mean": _mean([_to_float(row.get("categorical_coverage_score")) for row in items]),
452
+ "categorical_size_mean": _mean([_to_float(row.get("categorical_size_score")) for row in items]),
453
+ "numerical_coverage_mean": _mean([_to_float(row.get("numerical_coverage_score")) for row in items]),
454
+ "numerical_size_mean": _mean([_to_float(row.get("numerical_size_score")) for row in items]),
455
+ }
456
+ )
457
+
458
+ manifest_row = {
459
+ "dataset_id": dataset_id,
460
+ "status": "ok",
461
+ "asset_count": len(dataset_assets),
462
+ "real_row_count": n_real,
463
+ "feature_column_count": len(feature_columns),
464
+ }
465
+ return dataset_id, asset_rows, column_rows, real_diagnostic_rows, manifest_row
466
+
467
+
468
+ def _aggregate_group_mean(
469
+ rows: list[dict[str, Any]],
470
+ *,
471
+ group_keys: list[str],
472
+ value_fields: list[str],
473
+ ) -> list[dict[str, Any]]:
474
+ grouped: dict[tuple[Any, ...], list[dict[str, Any]]] = defaultdict(list)
475
+ for row in rows:
476
+ grouped[tuple(row.get(key) for key in group_keys)].append(row)
477
+ out: list[dict[str, Any]] = []
478
+ for key_tuple, items in sorted(grouped.items()):
479
+ payload = {group_key: key_tuple[idx] for idx, group_key in enumerate(group_keys)}
480
+ for field in value_fields:
481
+ payload[field] = _mean([_to_float(item.get(field)) for item in items])
482
+ payload["asset_count"] = len(items)
483
+ out.append(payload)
484
+ return out
485
+
486
+
487
+ def _build_global_threshold_summary(asset_rows: list[dict[str, Any]], threshold_specs: list[ThresholdSpec]) -> list[dict[str, Any]]:
488
+ out: list[dict[str, Any]] = []
489
+ for spec in threshold_specs:
490
+ items = [row for row in asset_rows if row.get("threshold_label") == spec.label]
491
+ if not items:
492
+ continue
493
+ out.append(
494
+ {
495
+ "threshold_label": spec.label,
496
+ "threshold_pct": spec.pct,
497
+ "tail_ratio": spec.ratio,
498
+ "tail_overall_mean": _mean([_to_float(row.get("tail_overall_score")) for row in items]),
499
+ "tail_coverage_mean": _mean([_to_float(row.get("tail_coverage_score")) for row in items]),
500
+ "tail_size_mean": _mean([_to_float(row.get("tail_size_score")) for row in items]),
501
+ "categorical_coverage_mean": _mean([_to_float(row.get("categorical_coverage_score")) for row in items]),
502
+ "categorical_size_mean": _mean([_to_float(row.get("categorical_size_score")) for row in items]),
503
+ "numerical_coverage_mean": _mean([_to_float(row.get("numerical_coverage_score")) for row in items]),
504
+ "numerical_size_mean": _mean([_to_float(row.get("numerical_size_score")) for row in items]),
505
+ "asset_count": len(items),
506
+ }
507
+ )
508
+ return out
509
+
510
+
511
+ def run_tail_threshold_experiment_v2(
512
+ *,
513
+ run_tag: str | None = None,
514
+ datasets: list[str] | None = None,
515
+ latest_only: bool = True,
516
+ root_names: list[str] | None = None,
517
+ threshold_percentages: list[float] | None = None,
518
+ max_workers: int = DEFAULT_MAX_WORKERS,
519
+ numeric_bins: int = DEFAULT_NUMERIC_BINS,
520
+ ) -> dict[str, Any]:
521
+ dataset_ids = datasets or list_dataset_ids()
522
+ threshold_specs = _threshold_specs(threshold_percentages)
523
+ resolved_run_tag = run_tag or f"{now_run_tag()}_tail_threshold_v2"
524
+ run_dir = make_task_run_dir("tail_threshold_v2", resolved_run_tag)
525
+ data_dir = run_dir / "data"
526
+ datasets_dir = run_dir / "datasets"
527
+ summaries_dir = run_dir / "summaries"
528
+
529
+ assets = discover_synthetic_assets(datasets=dataset_ids, latest_only=latest_only, root_names=root_names)
530
+ by_dataset: dict[str, list[SyntheticAsset]] = defaultdict(list)
531
+ for asset in assets:
532
+ by_dataset[asset.dataset_id].append(asset)
533
+
534
+ tracker = TaskProgressTracker(
535
+ task_name="tail_threshold_v2",
536
+ total_steps=len(dataset_ids),
537
+ step_label="datasets",
538
+ substep_label="assets",
539
+ total_substeps=len(assets),
540
+ )
541
+ tracker.print_start(extra=f"run_tag={resolved_run_tag}")
542
+
543
+ asset_rows_all: list[dict[str, Any]] = []
544
+ column_rows_all: list[dict[str, Any]] = []
545
+ real_diagnostic_rows_all: list[dict[str, Any]] = []
546
+ dataset_manifest_rows: list[dict[str, Any]] = []
547
+
548
+ with ProcessPoolExecutor(max_workers=max(1, int(max_workers))) as pool:
549
+ future_map = {
550
+ pool.submit(
551
+ _run_dataset_threshold_sweep,
552
+ dataset_id,
553
+ by_dataset.get(dataset_id, []),
554
+ threshold_specs,
555
+ numeric_bins,
556
+ ): dataset_id
557
+ for dataset_id in dataset_ids
558
+ }
559
+ for future in as_completed(future_map):
560
+ dataset_id = future_map[future]
561
+ asset_rows, column_rows, real_rows, manifest_row = [], [], [], {}
562
+ try:
563
+ _, asset_rows, column_rows, real_rows, manifest_row = future.result()
564
+ except Exception as exc:
565
+ manifest_row = {"dataset_id": dataset_id, "status": "error", "error": repr(exc), "asset_count": len(by_dataset.get(dataset_id, []))}
566
+
567
+ asset_rows_all.extend(asset_rows)
568
+ column_rows_all.extend(column_rows)
569
+ real_diagnostic_rows_all.extend(real_rows)
570
+ dataset_manifest_rows.append(manifest_row)
571
+
572
+ dataset_dir = datasets_dir / dataset_id
573
+ if asset_rows:
574
+ write_csv(dataset_dir / f"tail_threshold_v2_asset_scores__{dataset_id}.csv", asset_rows)
575
+ if column_rows:
576
+ write_csv(dataset_dir / f"tail_threshold_v2_column_scores__{dataset_id}.csv", column_rows)
577
+ if real_rows:
578
+ write_csv(dataset_dir / f"tail_threshold_v2_dataset_summary__{dataset_id}.csv", real_rows)
579
+ write_json(dataset_dir / "manifest.json", manifest_row)
580
+
581
+ tracker.advance(
582
+ step_name=dataset_id,
583
+ substeps_done=int(manifest_row.get("asset_count") or 0),
584
+ extra=f"status={manifest_row.get('status', 'ok')}",
585
+ )
586
+
587
+ asset_rows_all.sort(key=lambda row: (str(row.get("dataset_id") or ""), str(row.get("model_id") or ""), float(row.get("threshold_pct") or 0.0)))
588
+ column_rows_all.sort(key=lambda row: (str(row.get("dataset_id") or ""), str(row.get("model_id") or ""), str(row.get("column_name") or ""), float(row.get("threshold_pct") or 0.0)))
589
+ real_diagnostic_rows_all.sort(key=lambda row: (str(row.get("dataset_id") or ""), float(row.get("threshold_pct") or 0.0)))
590
+ dataset_manifest_rows.sort(key=lambda row: str(row.get("dataset_id") or ""))
591
+
592
+ global_summary_rows = _build_global_threshold_summary(asset_rows_all, threshold_specs)
593
+ model_summary_rows = _aggregate_group_mean(
594
+ asset_rows_all,
595
+ group_keys=["model_id", "model_label", "threshold_label", "threshold_pct"],
596
+ value_fields=[
597
+ "tail_overall_score",
598
+ "tail_coverage_score",
599
+ "tail_size_score",
600
+ "categorical_coverage_score",
601
+ "categorical_size_score",
602
+ "numerical_coverage_score",
603
+ "numerical_size_score",
604
+ ],
605
+ )
606
+ dataset_summary_rows = _aggregate_group_mean(
607
+ asset_rows_all,
608
+ group_keys=["dataset_id", "dataset_prefix", "threshold_label", "threshold_pct"],
609
+ value_fields=[
610
+ "tail_overall_score",
611
+ "tail_coverage_score",
612
+ "tail_size_score",
613
+ "categorical_coverage_score",
614
+ "categorical_size_score",
615
+ "numerical_coverage_score",
616
+ "numerical_size_score",
617
+ ],
618
+ )
619
+
620
+ write_csv(data_dir / "tail_threshold_v2_asset_scores.csv", asset_rows_all)
621
+ write_csv(data_dir / "tail_threshold_v2_column_scores.csv", column_rows_all)
622
+ write_csv(data_dir / "tail_threshold_v2_dataset_diagnostics.csv", real_diagnostic_rows_all)
623
+ write_csv(summaries_dir / "tail_threshold_v2_global_summary.csv", global_summary_rows)
624
+ write_csv(summaries_dir / "tail_threshold_v2_model_summary.csv", model_summary_rows)
625
+ write_csv(summaries_dir / "tail_threshold_v2_dataset_summary.csv", dataset_summary_rows)
626
+ write_csv(run_dir / "dataset_manifest.csv", dataset_manifest_rows)
627
+
628
+ manifest = {
629
+ "task": "tail_threshold_v2",
630
+ "run_tag": resolved_run_tag,
631
+ "run_dir": str(run_dir.resolve()),
632
+ "dataset_count": len(dataset_ids),
633
+ "asset_count": len(assets),
634
+ "latest_only": bool(latest_only),
635
+ "root_names": list(root_names or []),
636
+ "threshold_percentages": [spec.pct for spec in threshold_specs],
637
+ "threshold_labels": [spec.label for spec in threshold_specs],
638
+ "numeric_bins": int(numeric_bins),
639
+ "max_workers": int(max_workers),
640
+ "outputs": {
641
+ "asset_scores_csv": str((data_dir / "tail_threshold_v2_asset_scores.csv").resolve()),
642
+ "column_scores_csv": str((data_dir / "tail_threshold_v2_column_scores.csv").resolve()),
643
+ "dataset_diagnostics_csv": str((data_dir / "tail_threshold_v2_dataset_diagnostics.csv").resolve()),
644
+ "global_summary_csv": str((summaries_dir / "tail_threshold_v2_global_summary.csv").resolve()),
645
+ "model_summary_csv": str((summaries_dir / "tail_threshold_v2_model_summary.csv").resolve()),
646
+ "dataset_summary_csv": str((summaries_dir / "tail_threshold_v2_dataset_summary.csv").resolve()),
647
+ "dataset_manifest_csv": str((run_dir / "dataset_manifest.csv").resolve()),
648
+ },
649
+ }
650
+ write_json(run_dir / "manifest.json", manifest)
651
+ write_json(TAIL_THRESHOLD_ROOT / "final" / "manifest.json", manifest)
652
+ return manifest