Datasets:
Download code/scripts_seqroute/audit_report.py from divy123/sequential-router-v2: direct link, hf CLI and curl.
- Browser
- Download file 9.84 kB
-
https://huggingface.co/datasets/divy123/sequential-router-v2/resolve/main/code/scripts_seqroute/audit_report.py
- Command line
-
hf download hf://datasets/divy123/sequential-router-v2/code/scripts_seqroute/audit_report.py
-
curl -L -o audit_report.py https://huggingface.co/datasets/divy123/sequential-router-v2/resolve/main/code/scripts_seqroute/audit_report.py
9.84 kB
| """Audits and the final dataset report. Writes reports/dataset_report.md, reports/audit.json and prints the verdict line. | |
| Usage: python audit_report.py | |
| """ | |
| import json | |
| import re | |
| import sys | |
| from pathlib import Path | |
| import numpy as np | |
| import pandas as pd | |
| ROOT = Path("/mnt/localssd/seqroute1m") | |
| (ROOT / "reports").mkdir(exist_ok=True) | |
| models = json.load(open(ROOT / "manifests/models.json")) | |
| mid = [m["id"] for m in models] | |
| mfam = {m["id"]: m["family"] for m in models} | |
| q = pd.read_parquet(ROOT / "queries/queries_20k.parquet", columns=["query_id", "task_family", "source_dataset", "split", "group_id"]) | |
| R = pd.read_parquet(ROOT / "dataset/responses.parquet") | |
| S = pd.read_parquet(ROOT / "dataset/states.parquet") | |
| C = pd.read_parquet(ROOT / "dataset/candidates.parquet") | |
| RF = pd.read_parquet(ROOT / "dataset/response_features.parquet") | |
| audit, md = {}, [] | |
| def P(s=""): | |
| md.append(s) | |
| def tbl(df, floatfmt=3): | |
| return df.to_markdown(floatfmt=f".{floatfmt}f") if hasattr(df, "to_markdown") else str(df) | |
| # ---------------------------------------------------------------------- audits | |
| n_q, n_m = len(q), len(mid) | |
| R20 = R[R.in_20k.astype(bool)] | |
| expected = n_q * n_m | |
| audit["expected_responses"] = expected | |
| audit["responses_present"] = int(len(R20)) | |
| audit["response_coverage"] = len(R20) / expected | |
| audit["quality_coverage"] = float(R20.Q.notna().sum() / expected) | |
| audit["duplicate_query_model"] = int(R.duplicated(["query_id", "model_id"]).sum()) | |
| audit["cost_incomplete"] = int(R20.gpu_seconds.isna().sum() + R20.completion_tokens.isna().sum() + R20.latency_s.isna().sum()) | |
| sid = set(S.state_id) | |
| audit["candidates_without_state"] = int((~C.state_id.isin(sid)).sum()) | |
| key = set(zip(R20.query_id, R20.model_id)) | |
| audit["candidates_unresolved"] = int(sum((a, b) not in key for a, b in zip(C.query_id.head(2_000_000), C.candidate_model.astype(str).head(2_000_000)))) | |
| called_unres = 0 | |
| for lst, qid in zip(S.called_models.head(500_000), S.query_id.head(500_000)): | |
| for m in lst: | |
| called_unres += (qid, m) not in key | |
| audit["called_models_unresolved"] = int(called_unres) | |
| # split validity: no query or group in two splits | |
| qs = q.groupby("query_id").split.nunique() | |
| gs = q.groupby("group_id").split.nunique() | |
| audit["queries_in_multiple_splits"] = int((qs > 1).sum()) | |
| audit["groups_in_multiple_splits"] = int((gs > 1).sum()) | |
| audit["split_counts"] = q.split.value_counts().to_dict() | |
| # separation of features from outcomes | |
| feat_cols = [c for c in S.columns if c.startswith("feat_")] | |
| label_cols = [c for c in S.columns if c.startswith("label_")] | |
| audit["state_feature_columns"] = feat_cols | |
| audit["feature_label_name_overlap"] = [c for c in feat_cols if re.search(r"(?i)label|delta|gain|Q_best|^feat_Q", c)] | |
| rng = np.random.default_rng(0) | |
| chk = S[S.k == 1].sample(min(2000, int((S.k == 1).sum())), random_state=0) | |
| rfi = RF.set_index(["query_id", "model_id"]) | |
| mism = 0 | |
| for r in chk.itertuples(): | |
| f = rfi.loc[(r.query_id, r.called_models[0])] | |
| if not (np.isclose(r.feat_mean_lp, f.feat_mean_lp, equal_nan=True) and np.isclose(r.feat_mean_log_tokens, f.feat_log_tokens)): | |
| mism += 1 | |
| audit["feature_recompute_mismatches_k1"] = mism | |
| # leakage test: k=0 states must carry no features at all | |
| audit["k0_states_with_features"] = int(S[S.k == 0][[c for c in feat_cols if c != "feat_n_called"]].notna().any(axis=1).sum()) | |
| icc = json.load(open(ROOT / "manifests/judge_reliability_icc.json")) if (ROOT / "manifests/judge_reliability_icc.json").exists() else {} | |
| audit["judge_reliability_documented"] = bool(icc) | |
| audit["unparsed_judge_responses"] = int(((R20.Q_source == "judge") & R20.Q.isna()).sum()) | |
| gates = dict(response_coverage=audit["response_coverage"] >= 0.995, quality_coverage=audit["quality_coverage"] >= 0.995, no_duplicates=audit["duplicate_query_model"] == 0, | |
| candidates_resolve=audit["candidates_without_state"] == 0 and audit["candidates_unresolved"] == 0 and audit["called_models_unresolved"] == 0, cost_complete=audit["cost_incomplete"] == 0, | |
| judge_reliability_documented=audit["judge_reliability_documented"], split_valid=audit["queries_in_multiple_splits"] == 0 and audit["groups_in_multiple_splits"] == 0, | |
| features_separated=not audit["feature_label_name_overlap"] and audit["feature_recompute_mismatches_k1"] == 0 and audit["k0_states_with_features"] == 0) | |
| audit["gates"] = gates | |
| ready = all(gates.values()) | |
| # ---------------------------------------------------------------------- report | |
| P("# SeqRoute-1M dataset report\n") | |
| P(f"Generated {pd.Timestamp.now():%F %T}. Models: {n_m}. Queries in generation set: {n_q}.\n") | |
| P("## Audit gates\n") | |
| for k, v in gates.items(): | |
| P(f"- {'PASS' if v else 'FAIL'}: {k}") | |
| P(f"\nDetails: `reports/audit.json`.\n") | |
| dq = R20.groupby("query_id").model_id.nunique() | |
| comp = int(((dq == n_m) & (R20.dropna(subset=["Q"]).groupby("query_id").model_id.nunique().reindex(dq.index).fillna(0) == n_m)).sum()) | |
| P(f"## Completion\n\n- Completed distinct queries (all {n_m} responses present and scored): **{comp}** / {n_q}") | |
| P(f"- Response coverage: {audit['response_coverage']:.4f}; quality coverage: {audit['quality_coverage']:.4f}\n") | |
| rm = R20.groupby("model_id").agg(responses=("query_id", "size"), quality_scored=("Q", lambda x: x.notna().sum()), mean_Q=("Q", "mean"), truncated_frac=("finish_reason", lambda x: (x == "length").mean())).reindex(mid) | |
| P("### Responses per model\n\n" + tbl(rm)) | |
| P("\n## Task distribution (20k generation set)\n\n" + tbl(q.groupby(["task_family", "source_dataset"]).size().rename("n_queries").to_frame().reset_index(), 0)) | |
| P("\n## Mean quality by model x task family\n\n" + tbl(R20.pivot_table(index="task_family", columns="model_id", values="Q", aggfunc="mean")[mid], 2)) | |
| P(f"\n## States and candidate rows\n\n- States: {len(S):,} (per k: {S.k.value_counts().sort_index().to_dict()})\n- Candidate rows: {len(C):,}\n") | |
| qs_ = C.label_delta_Q.quantile([.01, .05, .25, .5, .75, .95, .99]).rename("delta_Q quantile").to_frame() | |
| P("## delta_Q distribution (all candidate rows)\n\n" + tbl(qs_) + f"\n\nShare delta_Q>0: {(C.label_delta_Q > 0).mean():.4f}; =0: {(C.label_delta_Q == 0).mean():.4f}; <0: {(C.label_delta_Q < 0).mean():.4f}\n") | |
| byk = C.groupby("k").agg(rows=("label_delta_Q", "size"), mean_delta=("label_delta_Q", "mean"), sd_delta=("label_delta_Q", "std"), pos_rate=("label_improves", "mean"), mean_positive_gain=("label_positive_gain", "mean")) | |
| P("### By number of called models\n\n" + tbl(byk)) | |
| Cf = C.merge(S[["state_id", "task_family", "split"]], on="state_id") | |
| P("\n## Positive-improvement rate and mean positive gain by task family and k\n") | |
| pr = Cf.groupby(["task_family", "k"]).label_improves.mean().unstack() | |
| P(tbl(pr)) | |
| P("\n## Oracle best-next-model gain by task (mean over states; lambda=0 means cost-free)\n") | |
| og = S[S.k >= 1].groupby(["task_family", "k"]).label_best_next_gain.mean().unstack() | |
| P(tbl(og)) | |
| P("\n### Cost-aware oracle (k=1 states): mean oracle net utility and STOP rate by lambda\n") | |
| rows = [] | |
| for lam in [0.0, 0.1, 0.25, 0.5, 1.0, 2.0]: | |
| s1 = S[S.k == 1] | |
| rows.append(dict(lam=lam, mean_utility=s1[f"label_oracle_utility_l{lam}"].mean(), mean_gain=s1[f"label_oracle_gain_l{lam}"].mean(), stop_rate=(s1[f"label_oracle_action_l{lam}"] == "STOP").mean())) | |
| P(tbl(pd.DataFrame(rows).set_index("lam"))) | |
| # same-family vs cross-family gains on one-model states | |
| c1 = C[C.k == 1].merge(S[S.k == 1][["state_id", "called_models", "task_family"]], on="state_id") | |
| c1["called"] = c1.called_models.map(lambda l: l[0]) | |
| c1["same_family"] = c1.called.map(mfam) == c1.candidate_model.astype(str).map(mfam) | |
| sf = c1.groupby(["same_family"]).agg(rows=("label_delta_Q", "size"), mean_delta=("label_delta_Q", "mean"), pos_rate=("label_improves", "mean"), mean_positive_gain=("label_positive_gain", "mean")) | |
| P("\n## Same-family vs cross-family candidates (one-model states)\n\n" + tbl(sf)) | |
| P("\n" + tbl(c1.groupby(["task_family", "same_family"]).label_positive_gain.mean().unstack())) | |
| P("\n## Cost distributions\n") | |
| cst = R20.groupby("model_id").agg(gpu_s_median=("gpu_seconds", "median"), gpu_s_p95=("gpu_seconds", lambda x: x.quantile(.95)), gpu_s_total=("gpu_seconds", "sum"), latency_median=("latency_s", "median"), | |
| latency_p95=("latency_s", lambda x: x.quantile(.95)), compl_tok_median=("completion_tokens", "median"), compl_tok_p95=("completion_tokens", lambda x: x.quantile(.95))).reindex(mid) | |
| P(tbl(cst, 4)) | |
| P("\nNormalised cost (cost_norm = gpu_seconds / family median train cost) quantiles: " + json.dumps({str(k): round(float(v), 3) for k, v in R20.cost_norm.quantile([.05, .25, .5, .75, .95]).items()})) | |
| P("\n## Judge reliability\n") | |
| if icc: | |
| P(tbl(pd.DataFrame(icc).T)) | |
| jc = ROOT / "manifests/judge_validation.json" | |
| if jc.exists(): | |
| P("\n```json\n" + jc.read_text() + "\n```") | |
| P(f"\nUnparsed judge responses after retries: {audit['unparsed_judge_responses']}.\n") | |
| gen_stats = [json.load(open(f)) for f in (ROOT / "responses").glob("*.stats.json") if not f.name.endswith(".smoke.stats.json")] | |
| gpu_h = sum(s["gpu_seconds"] for s in gen_stats) / 3600 | |
| wall_h = sum(s["gen_wall_s"] + s["startup_s"] for s in gen_stats) / 3600 | |
| P("## Compute\n") | |
| P(f"- Generation GPU-hours (8 GPUs x measured generation wall time, excluding smoke): {gpu_h:.1f}\n- Generation wall-clock hours incl. server startup: {wall_h:.1f}") | |
| extra = [] | |
| for f in (ROOT / "scores/judge").glob("stats_*.json"): | |
| extra.append(json.load(open(f))) | |
| P(f"- Judge passes: {len(extra)} runs, {sum(e['wall_s'] for e in extra) / 3600:.2f} wall hours (8 GPUs each)") | |
| P(f"\n## Verdict\n\nDATASET READY FOR ROUTER TRAINING: {'YES' if ready else 'NO'}") | |
| (ROOT / "reports/dataset_report.md").write_text("\n".join(md)) | |
| json.dump(audit, open(ROOT / "reports/audit.json", "w"), indent=1, default=str) | |
| print(json.dumps(gates, indent=1)) | |
| print(f"DATASET READY FOR ROUTER TRAINING: {'YES' if ready else 'NO'}") | |