Spaces:
Running
Running
Deploy eval-card-registry service
Browse filesFiles changed (6)
142 unmodified lines143144145146147148142 unmodified lines# Class-averaged F1 (before generic F1, which would swallow both)(r"macro[\s_-]*f1", "Macro F1"),(r"micro[\s_-]*f1", "Micro F1"),# Single-word patterns (generic, checked last by position)(r"\baccuracy\b", "Accuracy"),(r"\bacc\b", "Accuracy"),142 unmodified lines143144145146147148149150151152153154155156157158159160161162163164165166167168142 unmodified lines# Class-averaged F1 (before generic F1, which would swallow both)(r"macro[\s_-]*f1", "Macro F1"),(r"micro[\s_-]*f1", "Micro F1"),# Benchmark-scoped safety rubrics. Each is its own canonical with its own# rubric and direction, so the generic tail ("Score", "Harmlessness") must# not swallow them onto `score` / `harmlessness`.(r"harmbench[\s_-]*refusal[\s_-]*score","HarmBench Refusal Score"),(r"xstest[\s_-]*appropriateness[\s_-]*score","XSTest Appropriateness Score"),(r"simple[\s_-]*safety[\s_-]*tests?[\s_-]*safety[\s_-]*score","SimpleSafetyTests Safety Score"),(r"anthropic[\s_-]*red[\s_-]*team(?:ing)?[\s_-]*harmlessness[\s_-]*score","Anthropic Red Team Harmlessness Score"),# Model-scored generation metrics whose variant tail ("F1", "Accuracy")# the single-word patterns below would otherwise swallow onto the plain# f1 / accuracy canonicals.(r"bertscore[\s_-]*f1?\b", "BERTScore-F"),(r"bertscore[\s_-]*p(?:recision)?\b", "BERTScore-P"),(r"bertscore[\s_-]*r(?:ecall)?\b", "BERTScore-R"),(r"bleurt[\s_-]*acc(?:uracy)?\b", "BLEURT_acc"),(r"bleurt[\s_-]*diff\b", "BLEURT_diff"),(r"bleurt[\s_-]*max\b", "BLEURT_max"),# Single-word patterns (generic, checked last by position)(r"\baccuracy\b", "Accuracy"),(r"\bacc\b", "Accuracy"),
36 unmodified lines37383940414231 unmodified lines7475767778798081828384244 unmodified lines32933033133233333411 unmodified lines34634734834935035135235335435535635735835936036136236344 unmodified lines40840941041141241341441541679 unmodified lines49649749849950050150250350450550650750850951016 unmodified lines52752852953053153253353453536 unmodified lines# benchmark, and the registry does hold a handful of two-letter canonicals# (`if`, `mc`, `nq`) a bare segment would otherwise collide with._MIN_BENCHMARK_SEGMENT_LEN = 3# A trailing version token on a harness string (`lm_eval 0.4.12`,# `inspect_ai inspect_ai:0.3.80.dev25+g91a50728.d20250331`). Whitespace-31 unmodified lines"""One dotted `evaluation_name` resolved against the benchmarkvocabulary. `benchmark_raw` is the surface form to record downstream:the winning segment plus any subset segments, which is what theproducer's slice machinery reads."""canonical_id: strbenchmark_raw: strsubset: Optional[str]class Resolver:244 unmodified lines(no hits, only catch-all hits, or conflicting hits) — callers fallback to their existing description/name path unchanged."""if not raw_id or not isinstance(raw_id, str):return Noneraw_id = raw_id.strip()11 unmodified lines# normalized whole-id lookup could equate distinct ids.whole = exact_match(raw_id, "metric", source_config, self.store)if whole is not None and whole not in catch_all_ids:return wholehits: list[str] = []for segment in segments[1:]: # segments[0] is the adapter namespacecanonical = exact_match(segment, "metric", source_config, self.store) or normalized_match(segment, "metric", self.store, source_config)if canonical is not None:hits.append(canonical)specific = {h for h in hits if h not in catch_all_ids}if len(specific) == 1:return next(iter(specific))return Nonedef resolve_structured_benchmark(self,44 unmodified lines`paperswithcode` (64) sit in that position and stay unresolved onlybecause neither is a benchmark alias.`subset` is only meaningful when the winning canonical is the segmenthit itself; when the joined form won, the trailing segments belong tothe identity and `subset` is informational.Returns None when no segment resolves, so callers fall back to`clean_eval_name` unchanged.79 unmodified linesbenchmark_raw, "benchmark", source_config, check_hf=False)if joined.canonical_id is not None:return StructuredBenchmark(joined.canonical_id, benchmark_raw, _spell(segments[index + 1:]))index, canonical = hits[-1]return StructuredBenchmark(canonical, _spell(segments[index:]), _spell(segments[index + 1:]) or None)def _is_namespace_segment(self, segment: str, next_segment: Optional[str], source_config: Optional[str]) -> bool:16 unmodified linesresolves as a metric or reads as one to the metric extractor, so ametric tail is never mistaken for a subset."""spelled = segment.replace("_", " ")if exact_match(segment, "metric", source_config, self.store) or normalized_match(segment, "metric", self.store, source_config):return Truereturn _keyword_extract(spelled.lower()) is not None36 unmodified lines3738394041424331 unmodified lines75767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138244 unmodified lines38338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042111 unmodified lines43343443543643743843944044144244344444544644744844945045145245345445545645745845946044 unmodified lines50550650750850951051151251351451551679 unmodified lines59659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868916 unmodified lines70670770870971071171271371471571671771871972072136 unmodified lines# benchmark, and the registry does hold a handful of two-letter canonicals# (`if`, `mc`, `nq`) a bare segment would otherwise collide with._MIN_BENCHMARK_SEGMENT_LEN = 3_MIN_METRIC_SEGMENT_LEN = 3# A trailing version token on a harness string (`lm_eval 0.4.12`,# `inspect_ai inspect_ai:0.3.80.dev25+g91a50728.d20250331`). Whitespace-31 unmodified lines"""One dotted `evaluation_name` resolved against the benchmarkvocabulary. `benchmark_raw` is the surface form to record downstream:the winning segment plus any subset segments, which is what theproducer's slice machinery reads.`subset_is_identity` says whether `subset` names a PART of the benchmarkor merely spells the benchmark itself at greater length. The two lookidentical in `subset` and mean opposite things to a consumer decidingwhat a row measured:* `mmlu.mmlu.anatomy` — the registry knows `mmlu`, not`mmlu anatomy`, so `anatomy` is a real subset. The row measured onesubject, a PART of MMLU. `subset_is_identity` False.* `polyglotoxicityprompts.polyglotoxicityprompts.small_overall` — theregistry aliases the whole joined spelling to the benchmark, so thetrailing segments belong to the identity, not to a subset of it. Therow measured the benchmark. `subset_is_identity` True.`subset` is kept in both cases because the producer's slice machineryspells its display axis from it either way."""canonical_id: strbenchmark_raw: strsubset: Optional[str]subset_is_identity: bool = False@propertydef observation_role(self) -> str:"""What this match VERIFIED the row observed, relative to thebenchmark it resolved to: `"whole"` or `"part"`.There is a third answer this class cannot express — `"unknown"`,the row whose name the structured path could not read at all(flat/spaced names such as HELM's `MMLU All Subjects`, which`prepare_eval_name_segments` declines). That answer is the ABSENCEof a `StructuredBenchmark`, and callers must map `None` to itrather than assuming a whole: a name nobody parsed is not averified observation of anything, and labelling it `whole` is theclaim that made a page pool 34 subjects into their own total."""return "part" if (self.subset and not self.subset_is_identity) else "whole"@dataclassclass StructuredMetric:"""One namespaced `metric_config.metric_id` resolved against the metricvocabulary. `matched_segment` is the surface form that carried theidentity (the whole id when a whole-id alias won); `qualifier` is thetail spelled after it, which narrows the same metric to a scoringvariant (`gpqa.accuracy.strict`, `squadv2.f1.has_ans`) and is None whenthe tail carries no information."""canonical_id: strmatched_segment: strqualifier: Optional[str]def _is_aggregate_marker(segment: str) -> bool:"""`overall` and `<group>_overall` mark an aggregation level, not avariant of the metric, so they never become a qualifier."""lowered = segment.lower()return lowered == "overall" or lowered.endswith("_overall")class Resolver:244 unmodified lines(no hits, only catch-all hits, or conflicting hits) — callers fallback to their existing description/name path unchanged."""match = self.resolve_structured_metric(raw_id, source_config, catch_all_ids)return match.canonical_id if match is not None else Nonedef resolve_structured_metric(self,raw_id: Optional[str],source_config: Optional[str] = None,catch_all_ids: frozenset = frozenset(),) -> Optional["StructuredMetric"]:"""`resolve_structured_metric_id` with the match span reported.Same identity decision, plus the two pieces a consumer needs to keepdistinct observations apart: `matched_segment`, the surface form thatdisclosed the metric, and `qualifier`, the tail spelled after it.The tail is what narrows one metric to a scoring variant the sourcereports separately — `gpqa.accuracy.strict` next to`gpqa.accuracy.diamond`, `squadv2.f1.has_ans` next to`squadv2.f1.no_ans` — so a consumer that pools on the canonical idalone would median unrelated numbers together. Excluded from thetail: aggregate markers (`overall`, `<group>_overall`) and nothingelse, because those state a level rather than a variant. A numericsegment IS a variant and is kept — `bench.accuracy.1` and`bench.accuracy.5` are k-shot readings of one metric that a sourcereports separately, exactly the case the tail exists for. SegmentsBEFORE the match are never part of it: those are the adapternamespace, the source config and the benchmark. A whole-id aliasmatch reports the whole id as the matched segment and no qualifier,because the registry has claimed that exact string and there is noresidue to interpret.Returns None exactly when `resolve_structured_metric_id` returns None."""if not raw_id or not isinstance(raw_id, str):return Noneraw_id = raw_id.strip()11 unmodified lines# normalized whole-id lookup could equate distinct ids.whole = exact_match(raw_id, "metric", source_config, self.store)if whole is not None and whole not in catch_all_ids:return StructuredMetric(whole, raw_id, None)hits: list[tuple[int, str]] = []for index, segment in enumerate(segments[1:], start=1):# segments[0] is the adapter namespacecanonical = exact_match(segment, "metric", source_config, self.store) or normalized_match(segment, "metric", self.store, source_config)if canonical is not None:hits.append((index, canonical))specific = {c for _, c in hits if c not in catch_all_ids}if len(specific) != 1:return Nonecanonical_id = next(iter(specific))# The LAST segment naming the winning metric ends the identity: a# later restatement of the same metric is not a qualifier of itself.matched_index = max(i for i, c in hits if c == canonical_id)tail = [s for s in segments[matched_index + 1:] if not _is_aggregate_marker(s)]return StructuredMetric(canonical_id, segments[matched_index], ".".join(tail) or None)def resolve_structured_benchmark(self,44 unmodified lines`paperswithcode` (64) sit in that position and stay unresolved onlybecause neither is a benchmark alias.`subset` is only a real subset when the winning canonical is thesegment hit itself; when the JOINED form won, the trailing segmentsbelong to the identity and `subset` is informational. The two casesare told apart by `subset_is_identity`, because a consumer asking"did this row measure the whole benchmark or a part of it?" getsopposite answers from the same `subset` string.Returns None when no segment resolves, so callers fall back to`clean_eval_name` unchanged.79 unmodified linesbenchmark_raw, "benchmark", source_config, check_hf=False)if joined.canonical_id is not None:# Resolution is unchanged: the joined spelling wins whenever# it resolves at all, fuzzy tier included.## The identity flag is stricter, and deliberately so: EXACT# alias only. An exact alias is the registry spelling this# surface form, as written, as the benchmark — a statement# that the trailing segments are part of its name.## The looser tiers are not that statement. `mmlu anatomy`# reaches `mmlu` through the normalized tier, which is# spelling-insensitive and absorbs every subject name; the# fuzzy tier reduces further still by stripping# run-configuration tokens. Accepting either would turn all# 183 MMLU subject rows into whole-benchmark observations and# hand the page a median over its own parts — the number this# whole workstream exists to stop publishing.claimed = exact_match(benchmark_raw, "benchmark", source_config, self.store)joined_subset = _spell(segments[index + 1:]) or Nonereturn StructuredBenchmark(joined.canonical_id, benchmark_raw, joined_subset,subset_is_identity=(claimed is not Noneor self._subset_names_the_benchmark(joined_subset, joined.canonical_id)),)index, canonical = hits[-1]subset = _spell(segments[index + 1:]) or Nonereturn StructuredBenchmark(canonical, _spell(segments[index:]), subset,subset_is_identity=self._subset_names_the_benchmark(subset, canonical),)@staticmethoddef _subset_names_the_benchmark(subset: Optional[str],canonical: str,) -> bool:"""True when the reported subset is just the benchmark again.A subset only narrows the observation when it names something INSIDEthe benchmark. When it names the benchmark itself it narrows nothing,and treating it as a part excludes the source's own total from its ownpage.`vals_ai.swebench.overall` is the live case. The leading segment namesthe source folder, so the identity path lands on it and reports`swebench` as the subset — which is SWE-Bench. Meanwhile the siblingtime buckets (`vals_ai.swebench.<15 min fix>`) hit exact aliases andreport no subset at all, so the roles came out exactly backwards: thesubmitted total was excluded from its own cell and the page moved0.70731 -> 0.58718.The test is SELF-SPELLING, not resolution. A subset names thebenchmark when it is the benchmark's own name written differently —nothing more. Asking the general resolver "does this subset resolveto the same canonical?" answers a different question and answers itwrongly: every alias of a benchmark resolves to that benchmark,including the aliases that name its PARTS. Vals LegalBench is thelive case — `conclusion_tasks`, `interpretation_tasks`,`issue_tasks`, `rhetoric_tasks` and `rule_tasks` are all registryaliases of `legalbench`, so resolution called each of the fivecategory aggregates a whole-benchmark reading and left the source'sown `vals_ai.legal_bench.overall` unable to win its own cell.This is the same line the joined-spelling branch draws (see`_probe_benchmark_segments`): an EXACT alias is the registryspelling a surface form, as written, as the benchmark; thenormalized and fuzzy tiers are spelling-insensitive and absorbmember names. Exact identity of the joined spelling is checkedthere; this predicate adds only self-spelling."""if not subset:return Falsedef _squash(value: str) -> str:# `normalize` maps separators to spaces, so `swe-bench` becomes# `swe bench` while the source spells it `swebench`. Squashing to# alphanumerics makes the two comparable without loosening# `normalize` itself, which other callers depend on.return "".join(ch for ch in normalize(value) if ch.isalnum())return _squash(subset) == _squash(canonical)def _is_namespace_segment(self, segment: str, next_segment: Optional[str], source_config: Optional[str]) -> bool:16 unmodified linesresolves as a metric or reads as one to the metric extractor, so ametric tail is never mistaken for a subset."""spelled = segment.replace("_", " ")if exact_match(segment, "metric", source_config, self.store):return Trueif len(segment) < _MIN_METRIC_SEGMENT_LEN:# A one- or two-character tail is ambiguous: `mr` is a Marathi# language slice (`arc.arc_multilingual.mr`) as much as the# case-folded mean-recall alias `mR`. Only a byte-exact alias hit# (above) may claim it; the case-insensitive and keyword tiers# need a longer token, mirroring `_MIN_BENCHMARK_SEGMENT_LEN`.return Falseif normalized_match(segment, "metric", self.store, source_config):return Truereturn _keyword_extract(spelled.lower()) is not None
162 unmodified lines1631641651661671681691701711721731744 unmodified lines179180181182183184162 unmodified linesreview_status: Optional[str] = Noneclass BenchmarkCreate(BaseModel):id: strdisplay_name: strdescription: Optional[str] = Nonedataset_repo: Optional[str] = Noneparent_benchmark_id: Optional[str] = Nonetags: list[str] = []metadata: dict[str, Any] = {}review_status: str = "draft"4 unmodified linesdescription: Optional[str] = Nonedataset_repo: Optional[str] = Noneparent_benchmark_id: Optional[str] = Nonetags: Optional[list[str]] = Nonemetadata: Optional[dict[str, Any]] = Nonereview_status: Optional[str] = None162 unmodified lines1631641651661671681691701711721731741751761771781791801811821831841851861871881891901914 unmodified lines196197198199200201202203204205206207162 unmodified linesreview_status: Optional[str] = None_PREFERRED_METRIC_DESCRIPTION = ("Registry-declared default metric for the merged benchmark view ""(canonical_metrics.id). Null = no default declared.")_PREFERRED_METRIC_JUDGED_DESCRIPTION = ("Is preferred_metric_id produced by an LLM judge? true = yes, ""false = no, null = unstated. Says nothing about the benchmark's ""other metrics.")class BenchmarkCreate(BaseModel):id: strdisplay_name: strdescription: Optional[str] = Nonedataset_repo: Optional[str] = Noneparent_benchmark_id: Optional[str] = Nonepreferred_metric_id: Optional[str] = Field(default=None, description=_PREFERRED_METRIC_DESCRIPTION)preferred_metric_llm_judged: Optional[bool] = Field(default=None, description=_PREFERRED_METRIC_JUDGED_DESCRIPTION)tags: list[str] = []metadata: dict[str, Any] = {}review_status: str = "draft"4 unmodified linesdescription: Optional[str] = Nonedataset_repo: Optional[str] = Noneparent_benchmark_id: Optional[str] = Nonepreferred_metric_id: Optional[str] = Field(default=None, description=_PREFERRED_METRIC_DESCRIPTION)preferred_metric_llm_judged: Optional[bool] = Field(default=None, description=_PREFERRED_METRIC_JUDGED_DESCRIPTION)tags: Optional[list[str]] = Nonemetadata: Optional[dict[str, Any]] = Nonereview_status: Optional[str] = None
6 unmodified lines78910111213141 unmodified line161718192021477 unmodified lines49950050150250350450550650750850951051151251351451551651751851952035 unmodified lines556557558559560561253 unmodified lines815816817818819820242 unmodified lines106310641065106610671068211 unmodified lines128012811282128312841285128612871288128912901291129212931 unmodified line1295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131790 unmodified lines1408140914101411141214136 unmodified linessync Batch sync one or all EEE configs → eval_results table"""import jsonimport reimport unicodedatafrom pathlib import Pathfrom typing import Optional1 unmodified lineimport yamldef seed_collision_key(s: str) -> str:"""The key under which two seed surface forms count as one entity:NFKD + combining-mark strip (so "racé" and "race" collide before the477 unmodified linescurated_path = seed_path / "benchmarks.yaml"generated_dir = seed_path / "benchmarks_generated"generated_entries: list[dict] = []if generated_dir.is_dir():for src_path in sorted(generated_dir.glob("*.yaml")):with open(src_path) as f:loaded = yaml.safe_load(f) or []if not isinstance(loaded, list):raise typer.BadParameter(f"{src_path} must be a flat list")generated_entries.extend(loaded)curated_entries: list[dict] = []if curated_path.exists():with open(curated_path) as f:loaded = yaml.safe_load(f) or []if not isinstance(loaded, list):raise typer.BadParameter(f"{curated_path} must be a flat list")curated_entries = loadeddef _merge_benchmark(generated: dict, curated: dict) -> dict:"""Curated wins on every field it specifies; aliases are35 unmodified linesmetric_ids = {m["id"] for m in (yaml.safe_load(f) or [])}for entry in by_id.values():pm = entry.pop("preferred_metric", None)if pm is not None:if pm not in metric_ids:raise typer.BadParameter(253 unmodified lines]alias_count = 0# Track all seed entity IDs and alias keys so we can remove stale ones.# Alias key: (raw_value, entity_type, canonical_id, source_config)seed_snapshot: list[tuple[str, str, set[str], set[tuple[str, str, str, Optional[str]]]]] = []242 unmodified lines(raw, None) for raw in global_aliases if raw]for source_cfg, raw_values in scoped_aliases.items():for raw in raw_values or []:if raw:alias_specs.append((raw, source_cfg))211 unmodified linesraise typer.BadParameter(f"{folds_path} must be a flat list")bench_ids = {e["id"] for e in _load_benchmarks_merged()}fold_metrics_path = seed_path / "metrics.yaml"metric_ids = set()if fold_metrics_path.exists():with open(fold_metrics_path) as f:metric_ids = {m["id"] for m in (yaml.safe_load(f) or [])}seen_pairs: set[tuple[str, str]] = set()fold_rows = []for e in fold_entries:b, fm, tm = e.get("benchmark"), e.get("from_metric"), e.get("to_metric")if not (b and fm and tm):raise typer.BadParameter(f"metric_folds entry needs benchmark/from_metric/to_metric: {e!r}")if b not in bench_ids:1 unmodified linemissing = [m for m in (fm, tm) if m not in metric_ids]if missing:raise typer.BadParameter(f"metric_folds ({b}): unknown metric id(s) {missing}")if fm == tm:raise typer.BadParameter(f"metric_folds ({b}): self-fold {fm!r}")if (b, fm) in seen_pairs:raise typer.BadParameter(f"metric_folds: duplicate fold for ({b}, {fm})")seen_pairs.add((b, fm))factor = e.get("scale_factor")if factor is not None and (not isinstance(factor, (int, float)) or factor <= 0):raise typer.BadParameter(f"metric_folds ({b}): scale_factor must be a positive number, got {factor!r}")fold_rows.append({"benchmark_id": b, "from_metric_id": fm,"to_metric_id": tm, "scale_factor": factor, "note": e.get("note"),})# No chains: a fold target must not itself be folded on the same benchmark.targets = {(r["benchmark_id"], r["to_metric_id"]) for r in fold_rows}chained = sorted(targets & seen_pairs)if chained:raise typer.BadParameter(f"metric_folds: chained folds {chained}")folds_df = pd.DataFrame(90 unmodified linesstore.set_table("aliases", current_aliases.reset_index(drop=True))typer.echo(f" aliases: {alias_count} added, {removed_aliases} removed")if removed_entities:typer.echo(f" stale entities removed: {removed_entities}")6 unmodified lines789101112131415161 unmodified line18192021222324252627282930313233477 unmodified lines51151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154235 unmodified lines578579580581582583584585586587588589590591592593594253 unmodified lines848849850851852853854855856857242 unmodified lines110011011102110311041105110611071108110911101111211 unmodified lines132313241325132613271328132913301331133213331334133513361337133813391 unmodified line1341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144190 unmodified lines15321533153415351536153715381539154015416 unmodified linessync Batch sync one or all EEE configs → eval_results table"""import jsonimport mathimport reimport unicodedatafrom numbers import Realfrom pathlib import Pathfrom typing import Optional1 unmodified lineimport yaml# Source scope keys — the `source_config` on a scoped alias or a scoped# metric fold. A key is an UPSTREAM DATASET CONFIG NAME exactly as published# in the EEE datastore (`data/<config>/`): `openeval`, `llm-stats`,# `helm_capabilities`, … Registry ids are never scope keys, and the spelling# is not normalised — `llm-stats` and `llm_stats` are different configs. This# pattern is the shape the datastore uses, so a typo'd or path-like key fails# the seed instead of silently scoping an alias to a config that never calls._SOURCE_SCOPE_KEY_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_.-]*$")def seed_collision_key(s: str) -> str:"""The key under which two seed surface forms count as one entity:NFKD + combining-mark strip (so "racé" and "race" collide before the477 unmodified linescurated_path = seed_path / "benchmarks.yaml"generated_dir = seed_path / "benchmarks_generated"def _load_benchmarks_yaml(path: Path) -> list[dict]:raw_yaml = path.read_text()invalid_judge_flag = re.search(r"^\s*preferred_metric_llm_judged:\s*(?!true\b|false\b|null\b|~)(?P<value>\S+)",raw_yaml,re.MULTILINE,)if invalid_judge_flag:raise typer.BadParameter(f"{path}: invalid preferred_metric_llm_judged value "f"{invalid_judge_flag.group('value')!r}; ""use true, false, null, or ~")loaded = yaml.safe_load(raw_yaml) or []if not isinstance(loaded, list):raise typer.BadParameter(f"{path} must be a flat list")return loadedgenerated_entries: list[dict] = []if generated_dir.is_dir():for src_path in sorted(generated_dir.glob("*.yaml")):generated_entries.extend(_load_benchmarks_yaml(src_path))curated_entries: list[dict] = []if curated_path.exists():curated_entries = _load_benchmarks_yaml(curated_path)def _merge_benchmark(generated: dict, curated: dict) -> dict:"""Curated wins on every field it specifies; aliases are35 unmodified linesmetric_ids = {m["id"] for m in (yaml.safe_load(f) or [])}for entry in by_id.values():pm = entry.pop("preferred_metric", None)judged = entry.get("preferred_metric_llm_judged")if judged is not None and type(judged) is not bool:raise typer.BadParameter(f"benchmark {entry['id']!r}: preferred_metric_llm_judged ""must be a boolean or null")if judged is not None and pm is None:raise typer.BadParameter(f"benchmark {entry['id']!r}: preferred_metric_llm_judged ""requires preferred_metric")if pm is not None:if pm not in metric_ids:raise typer.BadParameter(253 unmodified lines]alias_count = 0# Distinct source scope keys (EEE dataset config names) seen across# scoped aliases and scoped metric folds — reported in the seed summary# so a typo'd config shows up as a new key rather than a silent no-op.source_scope_keys: set[str] = set()# Track all seed entity IDs and alias keys so we can remove stale ones.# Alias key: (raw_value, entity_type, canonical_id, source_config)seed_snapshot: list[tuple[str, str, set[str], set[tuple[str, str, str, Optional[str]]]]] = []242 unmodified lines(raw, None) for raw in global_aliases if raw]for source_cfg, raw_values in scoped_aliases.items():if not isinstance(source_cfg, str) or not _SOURCE_SCOPE_KEY_RE.match(source_cfg):raise typer.BadParameter(f"{label} entry {canonical_id!r}: scoped_aliases key "f"{source_cfg!r} is not a valid EEE dataset config name")source_scope_keys.add(source_cfg)for raw in raw_values or []:if raw:alias_specs.append((raw, source_cfg))211 unmodified linesraise typer.BadParameter(f"{folds_path} must be a flat list")bench_ids = {e["id"] for e in _load_benchmarks_merged()}fold_metrics_path = seed_path / "metrics.yaml"metrics_by_id = {}if fold_metrics_path.exists():with open(fold_metrics_path) as f:metrics_by_id = {m["id"]: m for m in (yaml.safe_load(f) or [])}metric_ids = set(metrics_by_id)seen_rows: set[tuple[str, str, Optional[str]]] = set()unscoped_pairs: dict[tuple[str, str], str] = {}fold_rows = []for e in fold_entries:b, fm, tm = e.get("benchmark"), e.get("from_metric"), e.get("to_metric")source_config = e.get("source_config")if not (b and fm and tm):raise typer.BadParameter(f"metric_folds entry needs benchmark/from_metric/to_metric: {e!r}")if b not in bench_ids:1 unmodified linemissing = [m for m in (fm, tm) if m not in metric_ids]if missing:raise typer.BadParameter(f"metric_folds ({b}): unknown metric id(s) {missing}")if source_config is not None and not isinstance(source_config, str):raise typer.BadParameter(f"metric_folds ({b}): source_config must be a string or null")if source_config is not None and not _SOURCE_SCOPE_KEY_RE.match(source_config):raise typer.BadParameter(f"metric_folds ({b}): source_config {source_config!r} is not a ""valid EEE dataset config name")if source_config is not None:source_scope_keys.add(source_config)# A scoped row may fold a metric onto ITSELF: that is a pure# published-scale conversion for one source, not a rename. An# unscoped row saying `x is x` carries no information.if fm == tm and source_config is None:raise typer.BadParameter(f"metric_folds ({b}): self-fold {fm!r}")row_key = (b, fm, source_config)if row_key in seen_rows:raise typer.BadParameter(f"metric_folds: duplicate fold for ({b}, {fm}, {source_config!r})")seen_rows.add(row_key)if source_config is None:unscoped_pairs[(b, fm)] = tmfactor = e.get("scale_factor")offset = e.get("scale_offset")if source_config is None and (factor is not None or offset is not None):raise typer.BadParameter(f"metric_folds ({b}): scale_factor/scale_offset conversions require source_config")for name, value in (("scale_factor", factor), ("scale_offset", offset)):if value is not None and (not isinstance(value, Real)or isinstance(value, bool)or not math.isfinite(value)):raise typer.BadParameter(f"metric_folds ({b}): {name} must be a finite real number, got {value!r}")if factor is not None and factor <= 0:raise typer.BadParameter(f"metric_folds ({b}): scale_factor must be a positive number, got {factor!r}")if factor is not None or offset is not None:target = metrics_by_id[tm]min_score, max_score = target.get("min_score"), target.get("max_score")if (not isinstance(min_score, Real)or isinstance(min_score, bool)or not math.isfinite(min_score)or not isinstance(max_score, Real)or isinstance(max_score, bool)or not math.isfinite(max_score)or max_score <= min_score):raise typer.BadParameter(f"metric_folds ({b}): {tm!r} must have finite ordered numeric bounds ""when scale_factor or scale_offset is set")fold_rows.append({"benchmark_id": b, "from_metric_id": fm,"to_metric_id": tm, "source_config": source_config,"scale_factor": factor, "scale_offset": offset,"note": e.get("note"),})# A scoped row is either (a) the per-source conversion attached to a# benchmark-wide naming fold — then it must name that fold's target —# or (b) a standalone published-scale conversion, which renames# nothing (from_metric == to_metric) and must actually carry a# conversion. Naming a DIFFERENT target than the benchmark-wide row# would make one source's metric mean something else, so it is# rejected either way.for row in fold_rows:source_config = row["source_config"]if source_config is None:continuepair = (row["benchmark_id"], row["from_metric_id"])unscoped_target = unscoped_pairs.get(pair)if unscoped_target is not None:if row["to_metric_id"] != unscoped_target:raise typer.BadParameter(f"metric_folds ({pair[0]}): scoped to_metric must match unscoped row")elif not (row["to_metric_id"] == row["from_metric_id"]and (row["scale_factor"] is not None or row["scale_offset"] is not None)):raise typer.BadParameter(f"metric_folds ({pair[0]}): scoped row requires unscoped row for "f"{pair[1]!r}, unless it is a pure published-scale conversion ""(from_metric == to_metric with scale_factor/scale_offset)")# No chains: a fold target must not itself be folded on the same benchmark.targets = {(r["benchmark_id"], r["to_metric_id"]) for r in fold_rows}chained = sorted(targets & set(unscoped_pairs))if chained:raise typer.BadParameter(f"metric_folds: chained folds {chained}")folds_df = pd.DataFrame(90 unmodified linesstore.set_table("aliases", current_aliases.reset_index(drop=True))typer.echo(f" aliases: {alias_count} added, {removed_aliases} removed")typer.echo(" source scope keys: "+ (", ".join(sorted(source_scope_keys)) if source_scope_keys else "(none)"))if removed_entities:typer.echo(f" stale entities removed: {removed_entities}")
99 unmodified lines10010110210310410599 unmodified lines"canonical_families","canonical_composites","canonical_metrics","eval_harnesses","canonical_inference_platforms","aliases",99 unmodified lines10010110210310410510610710810999 unmodified lines"canonical_families","canonical_composites","canonical_metrics",# Read-only curated dim table: no CRUD route, but the query-only Space# loads it so a consumer can read the folds alongside the benchmarks# they apply to."benchmark_metric_folds","eval_harnesses","canonical_inference_platforms","aliases",
105 unmodified lines10610710810911011171 unmodified lines183184185186187188189190191192193194195196197198199200201105 unmodified lines# Registry-declared default metric for the merged benchmark view# (seed key `preferred_metric`). Null → consumer fallback rules."preferred_metric_id": pd.StringDtype(),"tags": pd.StringDtype(),"metadata": pd.StringDtype(),"review_status": pd.StringDtype(),71 unmodified lines"created_at": pd.StringDtype(),"updated_at": pd.StringDtype(),},# Curated per-benchmark metric naming folds (seed/metric_folds.yaml):# `from_metric_id` on `benchmark_id` is the same measurement as# `to_metric_id` under a generic name. Naming folds ONLY — protocol# variants (cot-correct vs accuracy) never fold. Consumed by the# producer to compute `metric_id_effective` for the merged view."benchmark_metric_folds": {"benchmark_id": pd.StringDtype(),"from_metric_id": pd.StringDtype(),"to_metric_id": pd.StringDtype(),# Optional curated published-scale -> registry-scale multiplier# (e.g. 0.1 for a raw 1-10 score folding onto a [0,1] metric).# Null = scales already agree; detection-based conversion applies."scale_factor": "float64","note": pd.StringDtype(),},"eval_harnesses": {105 unmodified lines10610710810911011111211311411511671 unmodified lines188189190191192193194195196197198199200201202203204205206207208209210211212213214105 unmodified lines# Registry-declared default metric for the merged benchmark view# (seed key `preferred_metric`). Null → consumer fallback rules."preferred_metric_id": pd.StringDtype(),# Is `preferred_metric_id` produced by an LLM judge? True = yes,# false = no, null = unstated. Non-null only when# `preferred_metric_id` is set. Says nothing about the benchmark's# other metrics."preferred_metric_llm_judged": pd.BooleanDtype(),"tags": pd.StringDtype(),"metadata": pd.StringDtype(),"review_status": pd.StringDtype(),71 unmodified lines"created_at": pd.StringDtype(),"updated_at": pd.StringDtype(),},# Curated per-benchmark metric folds (seed/metric_folds.yaml):# `from_metric_id` on `benchmark_id` is the same measurement as# `to_metric_id` under a generic name. Naming folds ONLY — protocol# variants (cot-correct vs accuracy) never fold. Consumed by the# producer to compute `metric_id_effective` for the merged view.# A naming fold is benchmark-wide (`source_config` null). A scoped row# (`source_config` set to an EEE dataset config name) carries the# published-scale conversion for that one source, and may leave the# metric unchanged (`from_metric_id == to_metric_id`) when the source# differs only in scale."benchmark_metric_folds": {"benchmark_id": pd.StringDtype(),"from_metric_id": pd.StringDtype(),"to_metric_id": pd.StringDtype(),"source_config": pd.StringDtype(),# Optional curated published-scale -> registry-scale affine conversion:# canonical = published * scale_factor + scale_offset (e.g. 1/9 and# -1/9 for a raw 1-10 score folding onto a [0,1] metric). Scoped rows# only. Null = no curated conversion declared."scale_factor": "float64","scale_offset": "float64","note": pd.StringDtype(),},"eval_harnesses": {
packages/eval-entity-resolver/src/eval_entity_resolver/eee.py+20
packages/eval-entity-resolver/src/eval_entity_resolver/resolver.py+203-17
src/eval_card_registry/api/schemas.py+23
src/eval_card_registry/cli.py+148-20
src/eval_card_registry/store/hf_store.py+4
src/eval_card_registry/store/schemas.py+17-4