#!/usr/bin/env python3 """Build the transparent provisional leaderboard from benchmark results.""" from __future__ import annotations import argparse import csv import json import math import statistics from collections import Counter from pathlib import Path import pyarrow as pa import pyarrow.parquet as pq MEAN_DOMAIN_WEIGHT = 0.80 LOWER_QUARTILE_WEIGHT = 0.20 TIE_WINDOW_POINTS = 2.0 def args_parse() -> argparse.Namespace: parser = argparse.ArgumentParser() parser.add_argument("--results", type=Path, default=Path("results/tokenizer_benchmark.parquet")) parser.add_argument("--dataset", type=Path, default=Path("data/train-00000-of-00001.parquet")) parser.add_argument( "--author-evidence", type=Path, default=Path("results/author_evidence_scores.csv") ) parser.add_argument("--csv", type=Path, default=Path("results/provisional_leaderboard.csv")) parser.add_argument("--parquet", type=Path, default=Path("results/provisional_leaderboard.parquet")) return parser.parse_args() def weighted_ols_residuals(points: list[tuple[float, float]], weights: list[float]) -> list[float]: """Residuals for weighted y = intercept + slope*x.""" total_weight = sum(weights) x_mean = sum(weight * point[0] for point, weight in zip(points, weights)) / total_weight y_mean = sum(weight * point[1] for point, weight in zip(points, weights)) / total_weight denominator = sum(weight * (x - x_mean) ** 2 for (x, _), weight in zip(points, weights)) slope = sum( weight * (x - x_mean) * (y - y_mean) for (x, y), weight in zip(points, weights) ) / denominator intercept = y_mean - slope * x_mean return [y - (intercept + slope * x) for x, y in points] def author_weighted_percentile_scores(values: list[float], weights: list[float]) -> list[float]: """Author-balanced percentile, rescaled so observed best=100 and worst=0.""" if len(values) == 1: return [100.0] raw = [] total = sum(weights) for value in values: better = sum(weight for candidate, weight in zip(values, weights) if candidate < value) tied = sum(weight for candidate, weight in zip(values, weights) if candidate == value) raw.append(100.0 * (1.0 - (better + tied / 2) / total)) low, high = min(raw), max(raw) return [100.0 * (score - low) / (high - low) for score in raw] def eligibility(row: dict) -> tuple[bool, str]: if row["status"] != "ok": return False, "benchmark_error" if row["adapter_fidelity"] != "exact": return False, "core_only_adapter" if not row["roundtrip_pass"]: return False, "roundtrip_failure" if row["unk_rate"] != 0: return False, "nonzero_unk_rate" return True, "eligible" def traceability_score(source: dict) -> tuple[float, str]: checks = { "source_repo": bool(source.get("source_repo")), "source_path": bool(source.get("source_path")), "source_commit": bool(source.get("source_commit")), "sha256": len(source.get("sha256") or "") == 64, } return 25.0 * sum(checks.values()), json.dumps(checks, sort_keys=True) def main() -> None: args = args_parse() benchmark = pq.read_table(args.results).to_pylist() sources = {row["sha256"]: row for row in pq.read_table(args.dataset).to_pylist()} with args.author_evidence.open(newline="", encoding="utf-8") as handle: author_evidence = {row["author"]: row for row in csv.DictReader(handle)} domains = sorted(json.loads(benchmark[0]["domain_metrics_json"])) eligible_indices = [i for i, row in enumerate(benchmark) if eligibility(row)[0]] eligible_author_counts = Counter(benchmark[i]["author"] for i in eligible_indices) author_weights = [1.0 / eligible_author_counts[benchmark[i]["author"]] for i in eligible_indices] # Fit the expected log(tokens/word) vs log2(vocabulary size) relation in # each domain. Averaging residuals gives every domain equal influence. residuals_by_index = {index: [] for index in eligible_indices} domain_scores_by_index = {index: [] for index in eligible_indices} for domain in domains: points = [] for index in eligible_indices: row = benchmark[index] tpw = json.loads(row["domain_metrics_json"])[domain]["tokens_per_word"] points.append((math.log2(row["size"]), math.log(tpw))) residuals = weighted_ols_residuals(points, author_weights) percentiles = author_weighted_percentile_scores(residuals, author_weights) for index, residual, percentile in zip(eligible_indices, residuals, percentiles): residuals_by_index[index].append(residual) domain_scores_by_index[index].append(percentile) adjusted = { index: math.exp(sum(values) / len(values)) for index, values in residuals_by_index.items() } quality_scores = {} mean_domain_scores = {} lower_quartile_scores = {} for index, scores in domain_scores_by_index.items(): mean_domain_scores[index] = statistics.mean(scores) lower_quartile_scores[index] = statistics.quantiles(scores, n=4, method="inclusive")[0] quality_scores[index] = ( MEAN_DOMAIN_WEIGHT * mean_domain_scores[index] + LOWER_QUARTILE_WEIGHT * lower_quartile_scores[index] ) rows = [] for index, source_result in enumerate(benchmark): is_eligible, reason = eligibility(source_result) source = sources[source_result["sha256"]] traceability, traceability_detail = traceability_score(source) reviewed_evidence = author_evidence.get(source_result["author"]) evidence_package_score = ( float(reviewed_evidence["total"]) * 5 if reviewed_evidence is not None else None ) readiness = 100.0 if source_result["adapter_status"] == "native" else 70.0 quality = quality_scores.get(index) rows.append({ "rank": None, "eligible": is_eligible, "eligibility_reason": reason, "author": source_result["author"], "name": source_result["name"], "source_path": source_result["source_path"], "vocab_size": source_result["size"], "tokens_per_word": source_result["tokens_per_word"], "adjusted_compression_index": adjusted.get(index), "mean_domain_percentile": mean_domain_scores.get(index), "lower_quartile_domain_percentile": lower_quartile_scores.get(index), "provisional_quality_score": round(quality, 1) if quality is not None else None, "artifact_readiness_score": readiness, "evidence_package_score": evidence_package_score, "evidence_package_total_20": ( int(reviewed_evidence["total"]) if reviewed_evidence is not None else None ), "evidence_package_judgment": ( reviewed_evidence["evidence_judgment"] if reviewed_evidence is not None else "" ), "traceability_score": traceability, "reference_baseline": source_result["author"] == "kacperwikiel", "author_eligible_submission_count": eligible_author_counts.get(source_result["author"], 0), "selection_bias_label": "", "adapter_status": source_result["adapter_status"], "adapter_fidelity": source_result["adapter_fidelity"], "runtime": source_result["runtime"], "roundtrip_pass": source_result["roundtrip_pass"], "unk_rate": source_result["unk_rate"], "encode_mb_per_s_info_only": source_result["encode_mb_per_s"], "decode_mb_per_s_info_only": source_result["decode_mb_per_s"], "traceability_checks_json": traceability_detail, "sha256": source_result["sha256"], }) ranked = sorted( (row for row in rows if row["eligible"]), key=lambda row: (-row["provisional_quality_score"], row["source_path"]), ) author_best_path = {} for row in ranked: author_best_path.setdefault(row["author"], row["source_path"]) tier_start = 1 tier_anchor = None for position, row in enumerate(ranked, 1): score = row["provisional_quality_score"] if tier_anchor is None or tier_anchor - score > TIE_WINDOW_POINTS: tier_start, tier_anchor = position, score row["rank"] = tier_start count = row["author_eligible_submission_count"] if count == 1: row["selection_bias_label"] = "single_submission" elif row["source_path"] == author_best_path[row["author"]]: row["selection_bias_label"] = f"author_best_of_{count}_selection_bias" else: row["selection_bias_label"] = f"variant_among_{count}" rows.sort(key=lambda row: ( not row["eligible"], row["rank"] or 10**9, -(row["provisional_quality_score"] or -1), row["source_path"], )) args.csv.parent.mkdir(parents=True, exist_ok=True) with args.csv.open("w", newline="", encoding="utf-8") as handle: writer = csv.DictWriter(handle, fieldnames=list(rows[0])) writer.writeheader() writer.writerows(rows) pq.write_table(pa.Table.from_pylist(rows), args.parquet, compression="zstd") print(f"eligible={len(ranked)} unranked={len(rows)-len(ranked)}") for row in ranked[:10]: print( f"{row['rank']:2}. {row['author']:16} size={row['vocab_size']:6} " f"quality={row['provisional_quality_score']:.1f} adjusted={row['adjusted_compression_index']:.4f} " f"{row['source_path']}" ) if __name__ == "__main__": main()