Spaces:
Running
Running
Deploy eval-entity-registry service
Browse filesFiles changed (6)
- packages/eval-entity-resolver/src/eval_entity_resolver/canonical_store.py+110-2
- packages/eval-entity-resolver/src/eval_entity_resolver/models.py+6
- packages/eval-entity-resolver/src/eval_entity_resolver/resolver.py+103-14
- packages/eval-entity-resolver/src/eval_entity_resolver/strategies/fuzzy.py+144-63
- src/eval_entity_registry/services/resolution_service.py+2
- src/eval_entity_registry/store/schemas.py+2-1
20 unmodified lines21222324252619 unmodified lines46474849505163 unmodified lines1151161171181191205 unmodified lines12612712812913013114 unmodified lines1461471481491501513 unmodified lines15515615715815916016188 unmodified lines250251252253254255248 unmodified lines50450550650750850916 unmodified lines52652752852953053153219 unmodified lines55255355455555655755820 unmodified lines"org": "canonical_orgs","family": "canonical_families","composite": "canonical_composites",}# Scalar parent column for non-model types; models carry a typed `parents`19 unmodified linesreturn None if _is_na(value) else valuedef _safe_json_load(s: str, default: Any = None) -> Any:"""`json.loads` that returns `default` on any decode/type error."""try:63 unmodified linesreturn Nonedef _kwarg_for(entity_type: str) -> str:"""Constructor kwarg for an entity_type (English plurals, so no `<type>s_df`rule: `harnesses_df`, `families_df`)."""5 unmodified lines"org": "orgs_df","family": "families_df","composite": "composites_df",}[entity_type]14 unmodified linesorgs_df: Optional[pd.DataFrame] = None,families_df: Optional[pd.DataFrame] = None,composites_df: Optional[pd.DataFrame] = None,) -> None:self._tables: dict[str, pd.DataFrame] = {"model": models_df if models_df is not None else pd.DataFrame(),3 unmodified lines"org": orgs_df if orgs_df is not None else pd.DataFrame(),"family": families_df if families_df is not None else pd.DataFrame(),"composite": composites_df if composites_df is not None else pd.DataFrame(),}self._index: dict[str, dict[str, dict]] = {}# benchmark_id → family_id, built lazily from canonical_families.self._benchmark_to_family: Optional[dict[str, str]] = None88 unmodified linesreturn Nonereturn self._ensure_index(entity_type).get(canonical_id)def eval_name_layout(self, source_config: str) -> Optional[int]:"""The declared dotted-`evaluation_name` layout of `source_config`,read from `metadata.eval_name_layout` of the composite that lists it:248 unmodified linesreturn Nonereturn _na_to_none(entity.get(field))def model_metadata_fields(self, matched_canonical_id: str, matched_entity: Optional[dict]) -> dict:16 unmodified lines"model_family_id": None,"lineage_origin_model_id": None,"lineage_origin_model_org_id": None,"inference_platform": None,"resolution_source": None,"resolution_granularity": None,"parents": None,19 unmodified lines"model_family_id": leaf_family,"lineage_origin_model_id": leaf_lineage_model,"lineage_origin_model_org_id": leaf_lineage_org,"inference_platform": None,"resolution_source": _na_to_none(matched_entity.get("resolution_source")),"resolution_granularity": _na_to_none(matched_entity.get("resolution_granularity")),"parents": parents_decoded,20 unmodified lines2122232425262719 unmodified lines474849505152535455565763 unmodified lines1211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701715 unmodified lines17717817918018118218314 unmodified lines1981992002012022032043 unmodified lines20820921021121221321421521621721888 unmodified lines307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349248 unmodified lines59859960060160260360460560660760860961061161261361461561661761861916 unmodified lines63663763863964064119 unmodified lines66166266366466566620 unmodified lines"org": "canonical_orgs","family": "canonical_families","composite": "canonical_composites","inference_platform": "canonical_inference_platforms",}# Scalar parent column for non-model types; models carry a typed `parents`19 unmodified linesreturn None if _is_na(value) else valuedef _is_list_like(value: Any) -> bool:"""A list or a pyarrow/numpy array of values, not a scalar or a string."""return hasattr(value, "__iter__") and not isinstance(value, (str, bytes, dict))def _safe_json_load(s: str, default: Any = None) -> Any:"""`json.loads` that returns `default` on any decode/type error."""try:63 unmodified linesreturn None# Hub pipeline tags of a model whose output is generated text._TEXT_GENERATING_PIPELINES = frozenset({"text-generation", "text2text-generation", "image-text-to-text","video-text-to-text", "audio-text-to-text", "image-to-text", "any-to-any",})# Hub pipeline tags of a model whose output is an image, a video, audio or a# 3D asset. Every other tag says nothing either way: a chat model can carry# `feature-extraction`, `translation` or `question-answering` on the Hub, and# `audio-to-audio` covers speech-to-speech language models._NON_TEXT_PIPELINES = frozenset({"text-to-image", "image-to-image", "image-text-to-image","unconditional-image-generation","text-to-video", "image-to-video", "image-text-to-video", "video-to-video","text-to-speech", "text-to-audio","text-to-3d", "image-to-3d",})# Curated tags of a model whose output is an image._NON_TEXT_TAGS = frozenset({"image-gen", "diffusion"})def _json_field(entity: dict, key: str) -> Any:"""A JSON-encoded column decoded, or None; a pre-decoded value as is."""value = entity.get(key)return _safe_json_load(value) if isinstance(value, str) else valuedef _row_generates_text(entity: dict) -> Optional[bool]:"""Whether one canonical model row says its model generates text, orNone when the row does not say. Most specific statement first: theoutput modalities, then the Hub pipeline tag, then the curated tags."""modalities = _json_field(entity, "output_modalities")if _is_list_like(modalities) and len(modalities):return "text" in list(modalities)metadata = _json_field(entity, "metadata")pipeline_tag = metadata.get("pipeline_tag") if isinstance(metadata, dict) else Noneif pipeline_tag in _TEXT_GENERATING_PIPELINES:return Trueif pipeline_tag in _NON_TEXT_PIPELINES:return Falsetags = _json_field(entity, "tags")if _is_list_like(tags) and _NON_TEXT_TAGS.intersection(tags):return Falsereturn Nonedef _kwarg_for(entity_type: str) -> str:"""Constructor kwarg for an entity_type (English plurals, so no `<type>s_df`rule: `harnesses_df`, `families_df`)."""5 unmodified lines"org": "orgs_df","family": "families_df","composite": "composites_df","inference_platform": "inference_platforms_df",}[entity_type]14 unmodified linesorgs_df: Optional[pd.DataFrame] = None,families_df: Optional[pd.DataFrame] = None,composites_df: Optional[pd.DataFrame] = None,inference_platforms_df: Optional[pd.DataFrame] = None,) -> None:self._tables: dict[str, pd.DataFrame] = {"model": models_df if models_df is not None else pd.DataFrame(),3 unmodified lines"org": orgs_df if orgs_df is not None else pd.DataFrame(),"family": families_df if families_df is not None else pd.DataFrame(),"composite": composites_df if composites_df is not None else pd.DataFrame(),"inference_platform": (inference_platforms_df if inference_platforms_df is not None else pd.DataFrame()),}self._host_token_platforms: Optional[dict[str, str]] = Noneself._index: dict[str, dict[str, dict]] = {}# benchmark_id → family_id, built lazily from canonical_families.self._benchmark_to_family: Optional[dict[str, str]] = None88 unmodified linesreturn Nonereturn self._ensure_index(entity_type).get(canonical_id)def host_token_platforms(self) -> dict[str, str]:"""Lowercased host-token spelling (`together/`, `-bedrock`) →`canonical_inference_platforms.id`, inverted from the table's`aliases`. Empty when the store carries no platform table."""if self._host_token_platforms is None:mapping: dict[str, str] = {}for platform_id, row in self._ensure_index("inference_platform").items():aliases = row.get("aliases")if isinstance(aliases, str):aliases = _safe_json_load(aliases, default=[])if _is_list_like(aliases):for alias in aliases:if isinstance(alias, str) and alias:mapping[alias.lower()] = platform_idself._host_token_platforms = mappingreturn self._host_token_platformsdef platform_developer_org(self, platform_id: str) -> Optional[str]:"""The developer org that operates `platform_id`, from the platformrow's `canonical_org`, or None for a platform that only serves otherdevelopers' models. A platform and a developer are separate entities;this column is the one declared link between them."""row = self._ensure_index("inference_platform").get(platform_id) or {}org = _na_to_none(row.get("canonical_org"))return org if isinstance(org, str) and org else Nonedef require_host_token_platforms(self, origin: str) -> None:"""Refuse a registry snapshot that cannot attribute any host token.Without this every `inference_platform` resolves to None and nothingdownstream can tell that from a model served by no platform."""if not self.host_token_platforms():raise ValueError(f"registry snapshot at {origin} has no host tokens in ""canonical_inference_platforms (table missing, empty, or ""without aliases); inference_platform cannot be resolved")def eval_name_layout(self, source_config: str) -> Optional[int]:"""The declared dotted-`evaluation_name` layout of `source_config`,read from `metadata.eval_name_layout` of the composite that lists it:248 unmodified linesreturn Nonereturn _na_to_none(entity.get(field))def model_generates_text(self, entity: Optional[dict]) -> Optional[bool]:"""Whether the registry says this model generates text: True, False,or None when it does not say. Read off the model's own row, then offits group root, which is the same model in another version,precision or mode."""if not entity:return Noneown = _row_generates_text(entity)if own is not None:return owngroup_id = _na_to_none(entity.get("model_group_id"))if not group_id or group_id == entity.get("id"):return Noneroot = self.lookup("model", group_id)return _row_generates_text(root) if root else Nonedef model_metadata_fields(self, matched_canonical_id: str, matched_entity: Optional[dict]) -> dict:16 unmodified lines"model_family_id": None,"lineage_origin_model_id": None,"lineage_origin_model_org_id": None,"resolution_source": None,"resolution_granularity": None,"parents": None,19 unmodified lines"model_family_id": leaf_family,"lineage_origin_model_id": leaf_lineage_model,"lineage_origin_model_org_id": leaf_lineage_org,"resolution_source": _na_to_none(matched_entity.get("resolution_source")),"resolution_granularity": _na_to_none(matched_entity.get("resolution_granularity")),"parents": parents_decoded,
63 unmodified lines64656667686921 unmodified lines91929394959663 unmodified lines`lineage_origin_model_org_id`; remove once no consumer reads it.- `lineage_origin_model_org_id`: that ancestor's org_id. Models only.- `inference_platform`: FK to inference_platforms.id. Models only.- `resolution_source`: {hf|models_dev|curated|inferred|none}.- `resolution_granularity`: {variant|group|family}.- `parents`: typed-edge list of the matched leaf. Models only.21 unmodified lineslineage_origin_model_id: Optional[str] = Nonelineage_origin_model_org_id: Optional[str] = Noneinference_platform: Optional[str] = Noneresolution_source: Optional[str] = Noneresolution_granularity: Optional[str] = Noneparents: Optional[list[dict]] = None63 unmodified lines6465666768697071727321 unmodified lines959697989910010110263 unmodified lines`lineage_origin_model_org_id`; remove once no consumer reads it.- `lineage_origin_model_org_id`: that ancestor's org_id. Models only.- `inference_platform`: FK to inference_platforms.id. Models only.- `reasoning_effort`, `reasoning_tokens`: the effort tier (`…-low`)and thinking-token budget (`…-thinking-16k`) of the run. Read offthe matched mode leaf's id, else off the raw id when the id withoutthem names the same model. Models only.- `resolution_source`: {hf|models_dev|curated|inferred|none}.- `resolution_granularity`: {variant|group|family}.- `parents`: typed-edge list of the matched leaf. Models only.21 unmodified lineslineage_origin_model_id: Optional[str] = Nonelineage_origin_model_org_id: Optional[str] = Noneinference_platform: Optional[str] = Nonereasoning_effort: Optional[str] = Nonereasoning_tokens: Optional[int] = Noneresolution_source: Optional[str] = Noneresolution_granularity: Optional[str] = Noneparents: Optional[list[dict]] = None
10 unmodified lines111213141516178 unmodified lines26272829303132104 unmodified lines1371381391401411421431441451461472 unmodified lines15015115215315415515615715815916060 unmodified lines221222223224225226227228229230231232233234235236237238239240486 unmodified lines72772872973073173221 unmodified lines75475575675775875916 unmodified lines77677777877978078178210 unmodified linesfrom typing import Callable, Optionalfrom eval_entity_resolver.alias_store import AliasStorefrom eval_entity_resolver.canonical_store import CanonicalStore, _hf_repo_id_offrom eval_entity_resolver.eee import (clean_eval_name,prepare_eval_name_segments,8 unmodified lines)from eval_entity_resolver.strategies.exact import exact_matchfrom eval_entity_resolver.strategies.normalized import normalized_matchfrom eval_entity_resolver.strategies.fuzzy import fuzzy_match# Strictly between exact (1.0) and fuzzy (`_STEM_CONFIDENCE`, 0.90) so the# tier is recoverable from the confidence alone.104 unmodified linesconfig: Optional[ResolverConfig] = None,) -> "Resolver":"""Fully-enriching resolver over `<path>/*.parquet` (alias + canonicaltables)."""return cls(AliasStore.from_parquet(path),config=config,canonical_store=CanonicalStore.from_parquet(path),)@classmethod2 unmodified linesrepo_id: str,config: Optional[ResolverConfig] = None,) -> "Resolver":"""Fully-enriching resolver over a HF Dataset repo."""return cls(AliasStore.from_hf(repo_id),config=config,canonical_store=CanonicalStore.from_hf(repo_id),)def resolve(60 unmodified linesconfidence=0.0,)canonical_id, confidence, inferred_platform = fuzzy_match(raw_value, entity_type, self.config.threshold, self.store, source_config,org_dev_map=self._org_fold_map(), known_orgs=self._known_orgs(),)if canonical_id is not None:result = self._enrich(raw_value, entity_type, source_config,canonical_id, "fuzzy", confidence,)# An explicit host token in the raw id (`together/`, `-bedrock`) is# the strongest per-run platform fact; absent one, leave the field.if inferred_platform is not None:result.inference_platform = inferred_platformreturn resultreturn self._no_match_or_harness_retry(raw_value, entity_type, source_config, mode486 unmodified linesknows (bypassing the strategy chain); same enrichment as `resolve()`."""return self._enrich(raw_value, entity_type, source_config, canonical_id, strategy, confidence)def _enrich(self,raw_value: str,21 unmodified linesif entity_type == "model":fields = cs.model_metadata_fields(matched_canonical_id, matched_entity)# review_status must describe the canonical the response names.if fields["canonical_id"] != matched_canonical_id:root_entity = cs.lookup("model", fields["canonical_id"])16 unmodified linesmodel_family_id=fields.get("model_family_id"),lineage_origin_model_id=fields.get("lineage_origin_model_id"),lineage_origin_model_org_id=fields.get("lineage_origin_model_org_id"),inference_platform=fields.get("inference_platform"),resolution_source=fields.get("resolution_source"),resolution_granularity=fields.get("resolution_granularity"),parents=fields["parents"],10 unmodified lines11121314151617181920218 unmodified lines3031323334353637383940414243104 unmodified lines1481491501511521531541551561571581591601612 unmodified lines16416516616716816917017117217317417517617760 unmodified lines238239240241242243244245246247248249250251252486 unmodified lines73974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581621 unmodified lines83883984084184284384484584616 unmodified lines86386486586686786886987087110 unmodified linesfrom typing import Callable, Optionalfrom eval_entity_resolver.alias_store import AliasStorefrom eval_entity_resolver.canonical_store import (CanonicalStore,_hf_repo_id_of,decode_parents,)from eval_entity_resolver.eee import (clean_eval_name,prepare_eval_name_segments,8 unmodified lines)from eval_entity_resolver.strategies.exact import exact_matchfrom eval_entity_resolver.strategies.normalized import normalized_matchfrom eval_entity_resolver.fold import _norm_org_keyfrom eval_entity_resolver.strategies.fuzzy import (_canon_org,fuzzy_match,host_platform_of,mode_leaf_run_condition,reasoning_run_condition_of,)# Strictly between exact (1.0) and fuzzy (`_STEM_CONFIDENCE`, 0.90) so the# tier is recoverable from the confidence alone.104 unmodified linesconfig: Optional[ResolverConfig] = None,) -> "Resolver":"""Fully-enriching resolver over `<path>/*.parquet` (alias + canonicaltables). Raises ValueError when the snapshot carries no host-tokenplatform map."""canonical_store = CanonicalStore.from_parquet(path)canonical_store.require_host_token_platforms(str(path))return cls(AliasStore.from_parquet(path),config=config,canonical_store=canonical_store,)@classmethod2 unmodified linesrepo_id: str,config: Optional[ResolverConfig] = None,) -> "Resolver":"""Fully-enriching resolver over a HF Dataset repo. Raises ValueErrorwhen the snapshot carries no host-token platform map."""canonical_store = CanonicalStore.from_hf(repo_id)canonical_store.require_host_token_platforms(repo_id)return cls(AliasStore.from_hf(repo_id),config=config,canonical_store=canonical_store,)def resolve(60 unmodified linesconfidence=0.0,)canonical_id, confidence = fuzzy_match(raw_value, entity_type, self.config.threshold, self.store, source_config,org_dev_map=self._org_fold_map(), known_orgs=self._known_orgs(),)if canonical_id is not None:return self._enrich(raw_value, entity_type, source_config,canonical_id, "fuzzy", confidence,)return self._no_match_or_harness_retry(raw_value, entity_type, source_config, mode486 unmodified linesknows (bypassing the strategy chain); same enrichment as `resolve()`."""return self._enrich(raw_value, entity_type, source_config, canonical_id, strategy, confidence)def _host_platform(self, raw_value: str, canonical_id: str) -> Optional[str]:"""The platform a host token in `raw_value` names, or None.Who served a run and who developed the model are separate facts. Thedeveloper comes from the matched model, never from the token. A prefixtoken is ambiguous only when the platform it names is operated by thatsame developer (the platform row's `canonical_org`): `together/` on aTogether-developed model, `Groq/Llama-3-Groq-8B-Tool-Use`,`fireworks/ember-1`. That prefix may be a namespace, so no platform isclaimed."""cs = self.canonical_storehost = host_platform_of(raw_value, cs.host_token_platforms())if host is None:return Noneoperator = cs.platform_developer_org(host.platform_id)if host.prefix_token is not None and operator is not None:# An alias can point at an id with no canonical row; its namespace# is then the only developer on record.developer = (cs.lookup("model", canonical_id) or {}).get("org_id") or (canonical_id.split("/", 1)[0] if "/" in canonical_id else None)fold = self._org_fold_map()if developer and _norm_org_key(_canon_org(operator, fold)) == _norm_org_key(_canon_org(developer, fold)):return Nonereturn host.platform_iddef _reasoning_run_condition(self,raw_value: str,source_config: Optional[str],canonical_id: str,matched_entity: Optional[dict],) -> tuple[Optional[str], Optional[int]]:"""`(effort tier, thinking-token budget)` of the run `raw_value`names, each None when absent.How a run was configured and which model ran are separate facts, anda trailing `-low` / `-max` can be either. Two rules, in this order:1. The matched entity. A mode leaf (`o3-2025-04-16-high`, a `variant`of `o3-2025-04-16` on `axis: mode`) states the condition in itsown id, so every spelling that reaches the leaf reports it.2. The raw id, for what the entity leaves unstated. The suffix is acondition when the id without it names the same model: thematched one (`claude-sonnet-5-low` and `claude-sonnet-5`) or theone it is a variant of. `mistral-medium` and `mistral` are twomodels. It is not read at all on a model the registry knowsproduces no text: nothing reasons there, so the tier word is partof the product name (Stable Diffusion 3 Medium)."""cs = self.canonical_storeparents = decode_parents((matched_entity or {}).get("parents"))leaf = mode_leaf_run_condition(canonical_id, parents)effort, tokens = (leaf.effort, leaf.reasoning_tokens) if leaf else (None, None)stated = reasoning_run_condition_of(raw_value)if stated is None or cs.model_generates_text(matched_entity) is False:return effort, tokensif (effort or not stated.effort) and (tokens or not stated.reasoning_tokens):return effort, tokenssame_model = {canonical_id, cs.parent_canonical_id("model", matched_entity)}same_model.discard(None)for stem in stated.stems:# The stem is synthesized here, not asked about by the caller, so# it draws no live HF lookup, and an HF repo that happens to carry# its name cannot stand in for what the aliases say it names.named = self.resolve(stem, "model", source_config, check_hf=False)if named.canonical_id in same_model:return effort or stated.effort, tokens or stated.reasoning_tokensreturn effort, tokensdef _enrich(self,raw_value: str,21 unmodified linesif entity_type == "model":fields = cs.model_metadata_fields(matched_canonical_id, matched_entity)effort, reasoning_tokens = self._reasoning_run_condition(raw_value, source_config, fields["canonical_id"], matched_entity)# review_status must describe the canonical the response names.if fields["canonical_id"] != matched_canonical_id:root_entity = cs.lookup("model", fields["canonical_id"])16 unmodified linesmodel_family_id=fields.get("model_family_id"),lineage_origin_model_id=fields.get("lineage_origin_model_id"),lineage_origin_model_org_id=fields.get("lineage_origin_model_org_id"),inference_platform=self._host_platform(raw_value, fields["canonical_id"]),reasoning_effort=effort,reasoning_tokens=reasoning_tokens,resolution_source=fields.get("resolution_source"),resolution_granularity=fields.get("resolution_granularity"),parents=fields["parents"],
12 unmodified lines1314151617181920212223242526272829303132333435363738394072 unmodified lines1131141151161171181191201211221231241251 unmodified line12712812913013113213313434 unmodified lines16917017117217317417517617712 unmodified lines19019119219319419519619719819920020120220320420552 unmodified lines2582592602612622632642652662672682692702712722732 unmodified lines27627727827928028128214 unmodified lines29729829930030130230330430530630730830931031131231331494 unmodified lines4094104114124134144154164174184194204214224234244254264274284294304314324331 unmodified line4354364374384394404414424434444454464474488 unmodified lines45745845946046146246346446546626 unmodified lines49349449549649749849950050150250312 unmodified linesfrom __future__ import annotationsimport refrom typing import Optionalfrom eval_entity_resolver.normalization import normalizefrom eval_entity_resolver.strategies._platform_map import get_host_token_platform# Stripped only from the end of the raw value; longer suffixes first so a# shorter one cannot pre-empt a compound (`-int8` vs `-int8-awq`). Host# suffixes (`-together`, `-bedrock`, `-openrouter`) are deliberately absent:# they live in `_SUFFIX_PLATFORM_MAP` so the platform is captured, not lost._STRIP_SUFFIXES = [# Evaluation-mode suffixes (BFCL)."-fc","-prompt",# Reasoning-effort tiers. `-max` IS an effort tier (arc-agi's low/high/max# ladder); genuine `-max` products (qwen3-max) are safe because# exact/normalized matching wins before fuzzy ever strips."-xhigh-effort","-high-effort","-medium-effort","-low-effort","-minimal-effort","-non-reasoning","-xhigh","-high",72 unmodified linesdef _benchmark_stem_match(raw_value: str, alias_store, source_config: Optional[str]) -> tuple[Optional[str], float, None]:"""One candidate, built by removing run-configuration tokens. Runs afterexact and normalized, so a canonical whose name genuinely carries such atoken still wins on its own spelling."""candidate = _strip_run_config_tokens(raw_value)if candidate is None:return None, 0.0, Nonecanonical_id = (alias_store.lookup(candidate, "benchmark", source_config)or alias_store.get_normalized_lookup("benchmark", source_config).get(1 unmodified line))if canonical_id is None:return None, 0.0, Nonereturn canonical_id, _STEM_CONFIDENCE, Nonefrom eval_entity_resolver.fold import _ORG_ALIASES, _norm_org_key, dev_org_of_prefix # noqa: E402,F40134 unmodified lines# Hosting platforms, gateways and missing-developer placeholders: dropped as a# prefix so the bare model body is tried, since they are not developers.# Deliberately broader than the `inference_platforms` seed: stripping for# matching is independent of platform attribution. Values come from the seed# map; tokens absent there capture `None`._HOST_PREFIX_TOKENS: tuple[str, ...] = ("unknown","bedrock", "amazon-bedrock", "aws-bedrock",12 unmodified lines"kilo", "vercel", "llmgateway", "poe",)_HOST_PREFIXES_TO_STRIP: dict[str, Optional[str]] = {token: (None if token == "unknown" else get_host_token_platform(f"{token}/"))for token in _HOST_PREFIX_TOKENS}# Host suffixes: captured as the platform side-value rather than discarded._SUFFIX_PLATFORM_MAP: dict[str, Optional[str]] = {suffix: get_host_token_platform(suffix)for suffix in ("-together", "-bedrock", "-openrouter")}def _drop_duplicated_org_prefix(value: str) -> str | None:52 unmodified linesdef _drop_host_prefix(value: str) -> tuple[str, Optional[str]] | None:"""``(rest, platform_id)`` when the developer prefix (``host/`` or``host.``) is a known hosting platform, else None. ``platform_id`` is Nonewhen the host token has no attribution in the seed map; ``rest`` keeps theraw casing."""if "/" in value:org, rest = value.split("/", 1)org_lower = org.lower()if org_lower in _HOST_PREFIXES_TO_STRIP and rest:return (rest, _HOST_PREFIXES_TO_STRIP[org_lower])if "." in value:# Bedrock-style `bedrock.anthropic.claude-3-5-sonnet`: only the# segment before the first dot can be the host.2 unmodified linesrest = value[first_dot + 1:]org_lower = org.lower()if org_lower in _HOST_PREFIXES_TO_STRIP and rest:return (rest, _HOST_PREFIXES_TO_STRIP[org_lower])return None# Below exact (1.0) and normalized (0.95) so the tier is recoverable from the14 unmodified linesreturn Nonedef _strip_and_capture_platform_suffix(value: str) -> tuple[str, Optional[str]] | None:"""``(stem, platform_id)`` after stripping a trailing host suffix(`-together` / `-bedrock` / `-openrouter`), or None. The platform is a sidevalue, never embedded in the candidate."""lower = value.lower()for suffix, platform in _SUFFIX_PLATFORM_MAP.items():if lower.endswith(suffix):stem = value[: len(value) - len(suffix)]return (stem, platform)return None# ``qwen-2-72b`` ↔ ``qwen2-72b``. Safe because distinguishing tokens sit on the# other side of a separator (``gpt-4`` vs ``gpt-4-mini`` keeps ``-mini``)._LETTER_DIGIT_DASH = re.compile(r"([a-zA-Z])-(\d)")94 unmodified linessource_config: Optional[str] = None,org_dev_map: Optional[dict] = None,known_orgs: Optional[frozenset] = None,) -> tuple[Optional[str], float, Optional[str]]:"""Returns ``(canonical_id, confidence, inference_platform)``; canonical_idis None on no match.``inference_platform`` is a SIDE VALUE captured from a host token and neverembedded in the matched candidate, so capture cannot alter the canonical_id.A suffix capture (`-bedrock`) takes priority over a prefix capture(`together/`): a host token in the model name is the stronger per-run signal."""if entity_type == "benchmark":return _benchmark_stem_match(raw_value, alias_store, source_config)# The rewrites below are model-specific; on metrics/harnesses they would# merge unrelated entities that merely share a host-like prefix or tail.if entity_type != "model":return None, 0.0, Nonecandidates_to_try: list[str] = []captured_platform: Optional[str] = None# Tried before the generic strip so an aliased thinking-mode canonical# (`model-thinking`) wins over the drop-thinking stem (`model`).1 unmodified lineif preserve_match:candidates_to_try.append(preserve_match.group(1))# Before the generic strip so the host suffix is captured, not discarded;# the stem is re-stripped (`model-fc-together` → capture, then drop `-fc`).suffix_capture = _strip_and_capture_platform_suffix(raw_value)if suffix_capture:stem, platform = suffix_capturecandidates_to_try.append(stem)if platform is not None:captured_platform = platformstem_stripped = _strip_suffix(stem)if stem_stripped:candidates_to_try.append(stem_stripped)8 unmodified linesfor val in [raw_value] + candidates_to_try[:]:host = _drop_host_prefix(val)if host:bare, platform = hostcandidates_to_try.append(bare)if captured_platform is None and platform is not None:captured_platform = platformstripped_bare = _strip_suffix(bare)if stripped_bare:candidates_to_try.append(stripped_bare)26 unmodified lines# (`together/meta-llama/Llama-3-8B`) carries the host as its prefix.exact_id = alias_store.lookup(candidate, entity_type, source_config)if exact_id is not None and _orgs_agree(candidate, exact_id, org_dev_map, known_orgs):return exact_id, _STEM_CONFIDENCE, captured_platformnorm = normalize(candidate)canonical_id = norm_lookup.get(norm)if canonical_id is not None and _orgs_agree(candidate, canonical_id, org_dev_map, known_orgs):return canonical_id, _STEM_CONFIDENCE, captured_platformreturn None, 0.0, None12 unmodified lines1314151617181920212223242526272829303132333435363738394041424344454647484950515272 unmodified lines1251261271281291301311321331341351361371 unmodified line13914014114214314414514634 unmodified lines18118218318418518618718812 unmodified lines20120220320420520620720820921052 unmodified lines2632642652662672682692702712722732742752762772 unmodified lines28028128228328428528614 unmodified lines30130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540694 unmodified lines5015025035045055065075085095105115125135145155165175181 unmodified line5205215225235245255265275285295305318 unmodified lines54054154254354454554654726 unmodified lines57457557657757857958058158258358412 unmodified linesfrom __future__ import annotationsimport refrom typing import Mapping, NamedTuple, Optional, Sequencefrom eval_entity_resolver.normalization import normalize# Stripped only from the end of the raw value; longer suffixes first so a# shorter one cannot pre-empt a compound (`-int8` vs `-int8-awq`). Host# suffixes (`-together`, `-bedrock`, `-openrouter`) are deliberately absent:# they live in `_HOST_SUFFIXES`, which `host_platform_of` reads.# Reasoning-effort tiers a source welds onto the model name, mapped to the# tier they state. `-max` IS an effort tier (arc-agi's low/high/max ladder).# Longer spellings first so `-high-effort` is read before `-high`._EFFORT_SUFFIXES: dict[str, str] = {"-xhigh-effort": "xhigh","-max-effort": "max","-high-effort": "high","-medium-effort": "medium","-low-effort": "low","-minimal-effort": "minimal","-xhigh": "xhigh","-high": "high","-medium": "medium","-low": "low","-minimal": "minimal","-max": "max",}_STRIP_SUFFIXES = [# Evaluation-mode suffixes (BFCL)."-fc","-prompt",# Genuine `-max` products (qwen3-max) are safe because exact/normalized# matching wins before fuzzy ever strips.*_EFFORT_SUFFIXES,"-non-reasoning","-xhigh","-high",72 unmodified linesdef _benchmark_stem_match(raw_value: str, alias_store, source_config: Optional[str]) -> tuple[Optional[str], float]:"""One candidate, built by removing run-configuration tokens. Runs afterexact and normalized, so a canonical whose name genuinely carries such atoken still wins on its own spelling."""candidate = _strip_run_config_tokens(raw_value)if candidate is None:return None, 0.0canonical_id = (alias_store.lookup(candidate, "benchmark", source_config)or alias_store.get_normalized_lookup("benchmark", source_config).get(1 unmodified line))if canonical_id is None:return None, 0.0return canonical_id, _STEM_CONFIDENCEfrom eval_entity_resolver.fold import _ORG_ALIASES, _norm_org_key, dev_org_of_prefix # noqa: E402,F40134 unmodified lines# Hosting platforms, gateways and missing-developer placeholders: dropped as a# prefix so the bare model body is tried, since they are not developers.# Deliberately broader than the registry's platform table: stripping for# matching is independent of platform attribution (`host_platform_of`)._HOST_PREFIX_TOKENS: tuple[str, ...] = ("unknown","bedrock", "amazon-bedrock", "aws-bedrock",12 unmodified lines"kilo", "vercel", "llmgateway", "poe",)_HOST_PREFIXES_TO_STRIP = frozenset(_HOST_PREFIX_TOKENS)# Host suffixes: stripped as a unit so the stem can match._HOST_SUFFIXES: tuple[str, ...] = ("-together", "-bedrock", "-openrouter")def _drop_duplicated_org_prefix(value: str) -> str | None:52 unmodified linesdef _drop_host_prefix(value: str) -> tuple[str, Optional[str]] | None:"""``(rest, host_token)`` when the developer prefix (``host/`` or``host.``) is a known hosting platform, else None. ``host_token`` islowercased; ``rest`` keeps the raw casing."""if "/" in value:org, rest = value.split("/", 1)org_lower = org.lower()if org_lower in _HOST_PREFIXES_TO_STRIP and rest:return (rest, org_lower)if "." in value:# Bedrock-style `bedrock.anthropic.claude-3-5-sonnet`: only the# segment before the first dot can be the host.2 unmodified linesrest = value[first_dot + 1:]org_lower = org.lower()if org_lower in _HOST_PREFIXES_TO_STRIP and rest:return (rest, org_lower)return None# Below exact (1.0) and normalized (0.95) so the tier is recoverable from the14 unmodified linesreturn Nonedef _strip_host_suffix(value: str) -> tuple[str, str] | None:"""``(stem, host_suffix)`` after stripping a trailing host suffix(`-together` / `-bedrock` / `-openrouter`), or None."""lower = value.lower()for suffix in _HOST_SUFFIXES:if lower.endswith(suffix):return (value[: len(value) - len(suffix)], suffix)return Noneclass HostPlatform(NamedTuple):platform_id: str# The leading host token (`fireworks`) when the platform was read off a# prefix; None for a suffix capture, which can never be a developer.prefix_token: Optional[str]def host_platform_of(raw_value: str, host_token_platforms: Mapping[str, str]) -> Optional[HostPlatform]:"""The serving platform a raw model id names through a host token(`together/…`, `bedrock.…`, `…-bedrock`), or None. A function of the rawid alone, so it holds whichever strategy matched the id.``host_token_platforms`` maps a host-token spelling to a platform id(``CanonicalStore.host_token_platforms``). A suffix beats a prefix: a hosttoken in the model name is the stronger per-run signal."""suffix = _strip_host_suffix(raw_value)if suffix:platform_id = host_token_platforms.get(suffix[1])if platform_id is not None:return HostPlatform(platform_id, None)prefix = _drop_host_prefix(raw_value)if prefix:platform_id = host_token_platforms.get(f"{prefix[1]}/")if platform_id is not None:return HostPlatform(platform_id, prefix[1])return Noneclass RunCondition(NamedTuple):# Reasoning-effort tier (`low`, `xhigh`) the id states, or None.effort: Optional[str]# Thinking-token budget (`-thinking-16k` -> 16000) the id states, or None.reasoning_tokens: Optional[int]# The raw id without the condition (any host suffix put back): the names# of the model the condition was run on, most specific first.stems: tuple[str, ...]_THINKING_BUDGET_RE = re.compile(r"^(.*)(-thinking)-(\d+)k$", re.IGNORECASE)def reasoning_run_condition_of(raw_value: str) -> Optional[RunCondition]:"""The reasoning-effort tier and thinking-token budget a raw model idends in (`…-low`, `…-high-effort`, `…-thinking-16k`,`…-thinking-120k-high`, `…-medium-bedrock`), or None. A function of theraw id alone. A tier word can also be part of a product name(`mistral-medium`), so the caller confirms the condition against themodel a stem resolves to (`Resolver._reasoning_run_condition`)."""host = _strip_host_suffix(raw_value)body, host_suffix = (host[0], raw_value[len(host[0]):]) if host else (raw_value, "")effort = Nonelower = body.lower()for suffix, tier in _EFFORT_SUFFIXES.items():if lower.endswith(suffix) and len(body) > len(suffix):effort, body = tier, body[: len(body) - len(suffix)]breakbudget = _THINKING_BUDGET_RE.match(body)if budget is None:if effort is None:return Nonereturn RunCondition(effort, None, (body + host_suffix,))base, thinking, thousands = budget.groups()# A thinking-mode model (`…-thinking`) is the closer match when the# registry holds one; the plain model is the fallback.return RunCondition(effort, int(thousands) * 1000,(base + thinking + host_suffix, base + host_suffix),)def mode_leaf_run_condition(canonical_id: str, parents: Sequence[Mapping]) -> Optional[RunCondition]:"""The run condition a canonical model states in its own id(`openai/o3-mini-high`), when the registry holds it as a mode leaf: a`variant` of a base model on `axis: mode`. ``parents`` is the canonical'sdecoded edge list. A tier-named canonical with no such edge is its ownproduct (`qwen/qwen3-max`), so it states no condition."""is_mode_leaf = any(isinstance(edge, Mapping)and edge.get("relationship") == "variant"and edge.get("axis") == "mode"for edge in parents)return reasoning_run_condition_of(canonical_id) if is_mode_leaf else None# ``qwen-2-72b`` ↔ ``qwen2-72b``. Safe because distinguishing tokens sit on the# other side of a separator (``gpt-4`` vs ``gpt-4-mini`` keeps ``-mini``)._LETTER_DIGIT_DASH = re.compile(r"([a-zA-Z])-(\d)")94 unmodified linessource_config: Optional[str] = None,org_dev_map: Optional[dict] = None,known_orgs: Optional[frozenset] = None,) -> tuple[Optional[str], float]:"""Returns ``(canonical_id, confidence)``; canonical_id is None on nomatch."""if entity_type == "benchmark":return _benchmark_stem_match(raw_value, alias_store, source_config)# The rewrites below are model-specific; on metrics/harnesses they would# merge unrelated entities that merely share a host-like prefix or tail.if entity_type != "model":return None, 0.0candidates_to_try: list[str] = []# Tried before the generic strip so an aliased thinking-mode canonical# (`model-thinking`) wins over the drop-thinking stem (`model`).1 unmodified lineif preserve_match:candidates_to_try.append(preserve_match.group(1))# Before the generic strip; the stem is re-stripped (`model-fc-together`# → drop `-together`, then `-fc`).suffix_capture = _strip_host_suffix(raw_value)if suffix_capture:stem, _ = suffix_capturecandidates_to_try.append(stem)stem_stripped = _strip_suffix(stem)if stem_stripped:candidates_to_try.append(stem_stripped)8 unmodified linesfor val in [raw_value] + candidates_to_try[:]:host = _drop_host_prefix(val)if host:bare, _ = hostcandidates_to_try.append(bare)stripped_bare = _strip_suffix(bare)if stripped_bare:candidates_to_try.append(stripped_bare)26 unmodified lines# (`together/meta-llama/Llama-3-8B`) carries the host as its prefix.exact_id = alias_store.lookup(candidate, entity_type, source_config)if exact_id is not None and _orgs_agree(candidate, exact_id, org_dev_map, known_orgs):return exact_id, _STEM_CONFIDENCEnorm = normalize(candidate)canonical_id = norm_lookup.get(norm)if canonical_id is not None and _orgs_agree(candidate, canonical_id, org_dev_map, known_orgs):return canonical_id, _STEM_CONFIDENCEreturn None, 0.0
89 unmodified lines9091929394955 unmodified lines10110210310410510689 unmodified linesorgs_df=_table_with_pending(registry_store, "canonical_orgs") if registry_store.has_table("canonical_orgs") else None,families_df=registry_store.table("canonical_families") if registry_store.has_table("canonical_families") else None,composites_df=registry_store.table("canonical_composites") if registry_store.has_table("canonical_composites") else None,)5 unmodified lines# `model_group_id` / `lineage_origin_model_org_id`, kept for older consumers."model_group_id", "model_family_id", "lineage_origin_model_id","lineage_origin_model_org_id", "inference_platform","resolution_source", "resolution_granularity","parents", "open_weights","release_date", "params_billions",89 unmodified lines909192939495965 unmodified lines10210310410510610710889 unmodified linesorgs_df=_table_with_pending(registry_store, "canonical_orgs") if registry_store.has_table("canonical_orgs") else None,families_df=registry_store.table("canonical_families") if registry_store.has_table("canonical_families") else None,composites_df=registry_store.table("canonical_composites") if registry_store.has_table("canonical_composites") else None,inference_platforms_df=registry_store.table("canonical_inference_platforms") if registry_store.has_table("canonical_inference_platforms") else None,)5 unmodified lines# `model_group_id` / `lineage_origin_model_org_id`, kept for older consumers."model_group_id", "model_family_id", "lineage_origin_model_id","lineage_origin_model_org_id", "inference_platform","reasoning_effort", "reasoning_tokens","resolution_source", "resolution_granularity","parents", "open_weights","release_date", "params_billions",
163 unmodified lines164165166167168169170163 unmodified lines"updated_at": pd.StringDtype(),},# Host-token spellings (`fireworks/`, `-bedrock`, …) live in `aliases`# and are inverted into the platform map by lib/inference_platforms_map.py."canonical_inference_platforms": {"id": pd.StringDtype(), # PK; = models.dev provider slug where one exists"display_name": pd.StringDtype(),163 unmodified lines164165166167168169170171163 unmodified lines"updated_at": pd.StringDtype(),},# Host-token spellings (`fireworks/`, `-bedrock`, …) live in `aliases`# and are inverted into the platform map by the resolver's# CanonicalStore.host_token_platforms()."canonical_inference_platforms": {"id": pd.StringDtype(), # PK; = models.dev provider slug where one exists"display_name": pd.StringDtype(),
packages/eval-entity-resolver/src/eval_entity_resolver/canonical_store.py+110-2
packages/eval-entity-resolver/src/eval_entity_resolver/models.py+6
packages/eval-entity-resolver/src/eval_entity_resolver/resolver.py+103-14
packages/eval-entity-resolver/src/eval_entity_resolver/strategies/fuzzy.py+144-63
src/eval_entity_registry/services/resolution_service.py+2
src/eval_entity_registry/store/schemas.py+2-1