divy123's picture
Add files using upload-large-folder tool
8ad880b verified
Raw History Blame Contribute Delete
9.53 kB
"""Assemble the unified response table: raw generations + quality (objective / judge / COMET / SARI+BERTScore) + measured cost.
Output: /mnt/localssd/seqroute1m/dataset/responses.parquet (one row per (query_id, model_id); never contains router-visible *features* of other responses)
Quality provenance per row: Q_source in {objective, judge, comet, sari_bertscore, missing}. `label_confidence` = 1 for deterministic scorers, the family ICC for judge scores.
Cost: gpu_seconds = rate_m * (completion_tokens + 0.1 * prompt_tokens) where rate_m = measured wave GPU-seconds / weighted tokens of the large waves (w1..w3) for model m
(smoke-wave GPU-seconds are not used for rates: 100-query batches leave the GPUs mostly idle). Latency is the per-request wall time measured under saturated batching.
"""
import json
import sys
from pathlib import Path
import numpy as np
import pandas as pd
ROOT = Path("/mnt/localssd/seqroute1m")
LP_COLS = ["mean_lp", "median_lp", "p05_lp", "p25_lp", "min_lp", "mean_lp_tail64", "frac_lp_lt_2", "n_lp", "mean_entropy_top5", "median_entropy_top5", "p90_entropy_top5", "max_entropy_top5"]
def judge_q(d):
"""Substantive dimensions (factuality, coverage) carry 80% of the judge score; relevance / coherence / adherence saturate near 10 and share the rest."""
return 0.4 * d.factuality + 0.4 * d.coverage + 0.2 * (d.relevance + d.coherence + d.instruction_adherence) / 3
def load_jsonl(path):
return pd.read_json(path, lines=True, dtype=False) if Path(path).exists() and Path(path).stat().st_size else pd.DataFrame()
def main():
models = json.load(open(ROOT / "manifests/models.json"))
mid = [m["id"] for m in models]
q = pd.read_parquet(ROOT / "queries/master_queries.parquet", columns=["query_id", "task_family", "source_dataset", "evaluator_type", "split", "in_20k"])
qfam = q.set_index("query_id").evaluator_type
parts = []
for m in mid:
f = ROOT / "responses" / f"{m}.jsonl"
if not f.exists():
continue
r = load_jsonl(f).rename(columns={"id": "query_id"})
r["model_id"] = m
parts.append(r)
R = pd.concat(parts, ignore_index=True)
R = R.drop_duplicates(["query_id", "model_id"], keep="first")
# ---- quality ------------------------------------------------------------------------------------------------------------------------
O = pd.concat([load_jsonl(ROOT / "scores/obj" / f"{m}.jsonl").assign(model_id=m) for m in mid if (ROOT / "scores/obj" / f"{m}.jsonl").exists()], ignore_index=True)
O = O.rename(columns={"Q": "Q", "raw": "raw_metric", "answer": "answer_extracted"})[["query_id", "model_id", "Q", "raw_metric", "raw_name", "parse_ok", "truncated", "empty_final", "answer_extracted", "sub"]]
O["Q_source"] = "objective"
aux = []
for name, src in (("comet.jsonl", "comet"), ("simplification.jsonl", "sari_bertscore")):
a = load_jsonl(ROOT / "scores/aux" / name)
if len(a):
a[["model_id", "query_id"]] = a["id"].str.split("|", n=1, expand=True)
a["Q_source"] = src
a = a.rename(columns={"raw": "raw_metric"})
for c in ("parse_ok", "truncated"):
a[c] = True if c == "parse_ok" else False
aux.append(a[["query_id", "model_id", "Q", "raw_metric", "raw_name", "empty_final", "Q_source", "parse_ok", "truncated"]])
J = load_jsonl(ROOT / "scores/judge/parsed_primary.jsonl")
jud = pd.DataFrame()
icc = {}
if len(J):
J = J[~J.id.str.startswith("ctrl_")]
J[["model_id", "query_id"]] = J["id"].str.split("|", n=1, expand=True)
J = J[J.rep == 0].copy()
J["Q_mean5"] = J.Q
J["Q"] = np.where(J.get("empty_final", False).fillna(False).astype(bool), 0.0, judge_q(J))
dims = [c for c in ["factuality", "coverage", "relevance", "coherence", "instruction_adherence"] if c in J.columns]
J["judge_dims"] = J[dims].apply(lambda r: json.dumps({k: (None if pd.isna(v) else float(v)) for k, v in r.items()}), axis=1) if dims else "{}"
jud = J.assign(raw_metric=J.get("Q"), raw_name="judge_mean5", Q_source="judge", parse_ok=J.parsed.astype(bool), truncated=False,
empty_final=J.get("empty_final", False).fillna(False).astype(bool))[["query_id", "model_id", "Q", "raw_metric", "raw_name", "Q_source", "parse_ok", "truncated", "empty_final", "judge_dims"]]
rep = load_jsonl(ROOT / "scores/judge/parsed_repeat.jsonl")
if len(rep):
rep = rep[rep.parsed & ~rep.id.str.startswith("ctrl_")]
rep[["model_id", "query_id"]] = rep["id"].str.split("|", n=1, expand=True)
rep["Q"] = judge_q(rep)
rep = rep.merge(q[["query_id", "task_family"]], on="query_id")
per_resp_sd = rep.groupby(["model_id", "query_id"]).Q.std(ddof=1).rename("judge_noise_sd").reset_index()
for fam, g in rep.groupby("task_family"):
within = g.groupby(["model_id", "query_id"]).Q.var(ddof=1).mean()
total = g.Q.var(ddof=1)
icc[fam] = dict(within_var=float(within), total_var=float(total), reliability=float(max(0.0, 1 - within / total)), pooled_noise_sd=float(np.sqrt(within)))
json.dump(icc, open(ROOT / "manifests/judge_reliability_icc.json", "w"), indent=1)
Qs = pd.concat([O] + aux + ([jud] if len(jud) else []), ignore_index=True)
Qs = Qs.drop_duplicates(["query_id", "model_id"], keep="first")
D = R.merge(Qs, on=["query_id", "model_id"], how="left").merge(q[["query_id", "task_family", "source_dataset", "split", "in_20k"]], on="query_id", how="left")
D["Q_source"] = D.Q_source.fillna("missing")
D["empty_final"] = D.empty_final.fillna(False).astype(bool)
# label confidence / judge noise
fam_noise = {f: v["pooled_noise_sd"] for f, v in icc.items()}
fam_rel = {f: v["reliability"] for f, v in icc.items()}
D["judge_noise_sd"] = np.where(D.Q_source == "judge", D.task_family.map(fam_noise), 0.0)
D["label_confidence"] = np.where(D.Q_source == "judge", D.task_family.map(fam_rel).fillna(0.0), np.where(D.Q_source == "missing", 0.0, 1.0))
D.loc[(D.Q_source == "judge") & D.empty_final, ["judge_noise_sd", "label_confidence"]] = [0.0, 1.0]
# ---- cost -----------------------------------------------------------------------------------------------------------------------------
D["wtok"] = D.completion_tokens + 0.1 * D.prompt_tokens
waves = {w: set(json.load(open(ROOT / "manifests" / f"wave_{w}.json"))) for w in ("w1", "w2", "w3") if (ROOT / "manifests" / f"wave_{w}.json").exists()}
rates = {}
for m in mid:
gs, wt = 0.0, 0.0
for w, ids in waves.items():
sf = ROOT / "responses" / f"{m}.{w}.stats.json"
if not sf.exists():
continue
st = json.load(open(sf))
if st["n_generated"] < 500:
continue
gs += st["gpu_seconds"]
wt += st["completion_tokens"] + 0.1 * st["prompt_tokens"]
rates[m] = gs / wt if wt else np.nan
def ts_rate(m):
"""Fallback when wave stats were overwritten by retry rounds: 8 GPUs x (0.1%-trimmed) wave window from response timestamps; capped attempts archived by the extended pass are included, regenerated ones are not."""
arch = ROOT / "responses_truncated" / f"{m}.jsonl"
ar = [json.loads(l) for l in open(arch)] if arch.exists() else []
aid = {r["id"] for r in ar}
main_rows = [json.loads(l) for l in open(ROOT / "responses" / f"{m}.jsonl")]
smoke = set(json.load(open(ROOT / "manifests/wave_smoke.json")))
gs_, wt_ = 0.0, 0.0
for w, ids in waves.items():
rows = [r for r in main_rows if r["id"] in ids and r["id"] not in aid and r["id"] not in smoke] + [r for r in ar if r["id"] in ids and r["id"] not in smoke]
gs_ += 8 * (np.quantile([r["t_end"] for r in rows], 0.999) - min(r["t_end"] - r["latency_s"] for r in rows))
wt_ += sum(r["completion_tokens"] + 0.1 * r["prompt_tokens"] for r in rows)
return gs_ / wt_
ts_fallback = [m for m in mid if np.isnan(rates[m])]
for m in ts_fallback:
rates[m] = ts_rate(m)
if all(np.isnan(v) for v in rates.values()): # smoke-only run: fall back to smoke stats (flagged)
for m in mid:
sf = ROOT / "responses" / f"{m}.smoke.stats.json"
if sf.exists():
st = json.load(open(sf))
rates[m] = st["gpu_seconds"] / (st["completion_tokens"] + 0.1 * st["prompt_tokens"])
D["cost_source"] = "smoke_wave_rate(NOT FINAL)"
else:
D["cost_source"] = "wave_calibrated_token_rate"
D["gpu_seconds"] = D.wtok * D.model_id.map(rates)
ref = D[D.split == "train"].groupby("task_family").gpu_seconds.median()
D["cost_norm"] = D.gpu_seconds / D.task_family.map(ref)
D = D.drop(columns=["wtok"])
for c in LP_COLS:
if c not in D.columns:
D[c] = np.nan
out = ROOT / "dataset"
out.mkdir(exist_ok=True)
D.to_parquet(out / "responses.parquet", compression="zstd", index=False)
json.dump(dict(rate_from_timestamps_for=ts_fallback, gpu_seconds_per_weighted_token=rates, reference_cost_median_gpu_s_by_family=ref.to_dict()), open(ROOT / "manifests/cost_calibration.json", "w"), indent=1)
print("responses", len(D), "missing quality", int((D.Q_source == "missing").sum()), "models", D.model_id.nunique(), "queries", D.query_id.nunique())
if __name__ == "__main__":
main()