"""A portable registry of the pretrained biological models this harness can call. Written so the code runs unchanged on another machine. Nothing here hardcodes a lab path: each model is named, and resolution walks an ordered search path 1. ``$VERA_MODEL_ROOT/`` -- an explicit, machine-local root 2. any directory in ``$VERA_MODEL_PATH`` -- colon-separated, like ``$PATH`` 3. the Hugging Face cache, via the hub id -- downloaded on first use so a new machine needs at most one environment variable, and none at all if it is willing to download. `ensure_local` reports which rung it used, because "the model was silently re-downloaded" and "the model was silently the wrong one" are both failures that look like success. Layout under a root is fixed and shallow, so a directory can be rsynced between machines and still resolve:: $VERA_MODEL_ROOT/ c2s/celltype/ vandijklab/C2S-Pythia-410m-cell-type-prediction dna/nucleotide-transformer/ InstaDeepAI/nucleotide-transformer-v2-500m-multi-species dna/dnabert2/ zhihan1996/DNABERT-2-117M """ from __future__ import annotations import os from dataclasses import dataclass from pathlib import Path # Where a lab machine may already hold these, tried before any download. Extend rather # than edit: an unreachable entry is skipped, so listing several machines is harmless. FALLBACK_ROOTS = ( Path("/srv/disk00/sshfs/pengchx3/vera_models"), Path("/tmp/galaxy_srv_disk00/pengchx3/vera_models"), ) # Tasks a model can answer. Grouping by task rather than by model is deliberate: rbio1 # reports that *composing* several approximate verifiers beats any one of them, and a # registry keyed by model cannot express "ask everything that speaks to this question". CELL_TYPE = "cell_type" DNA_SEQUENCE = "dna_sequence" @dataclass(frozen=True) class ModelSpec: """One callable pretrained model. Attributes: key: Short name used by callers and on the command line. hub_id: Hugging Face id, used for download and as the cache key. Empty for models that are not distributed through the hub (see `kind`). relpath: Location under a model root, so roots stay rsync-compatible. task: Which question this answers. Several models may share a task. kind: How to load it -- ``"hf"`` for transformers weights, ``"celltypist"`` for a CellTypist model resolved by name. New kinds are added here rather than by special-casing at call sites. description: What it answers, in the vocabulary of the benchmark's questions. tokenizer_hub_id: Where to get the tokenizer when the weights directory has none. Several HF repos ship weights only and expect the base model's tokenizer; loading `AutoTokenizer` from such a directory does not raise -- it yields a tokenizer that encodes to ZERO tokens, and generation then fails with an unrelated reshape error minutes later. note: Anything a caller must know before trusting its output. """ key: str hub_id: str relpath: str task: str description: str kind: str = "hf" tokenizer_hub_id: str = "" note: str = "" REGISTRY: dict[str, ModelSpec] = { "c2s-celltype": ModelSpec( key="c2s-celltype", hub_id="vandijklab/C2S-Pythia-410m-cell-type-prediction", relpath="c2s/celltype", task=CELL_TYPE, description="cell type from a cell's ranked gene expression (Cell2Sentence)", # The published repo ships weights without a tokenizer; C2S-Pythia is a Pythia # derivative, so the base tokenizer is the correct one. tokenizer_hub_id="EleutherAI/pythia-410m", note="Cell2Sentence: input is gene symbols ordered by descending expression.", ), # A second, independent opinion on the same question. CellTypist is a different model # family (regression over marker genes, not a language model), so its agreement with # Cell2Sentence is evidence rather than a restatement -- two models that fail the same # way would agree confidently and teach nothing. "celltypist": ModelSpec( key="celltypist", hub_id="", relpath="celltypist", task=CELL_TYPE, description="cell type from an expression matrix (CellTypist, marker-based)", kind="celltypist", note="Resolved by CellTypist model name, e.g. Immune_All_Low.pkl.", ), "nt-500m": ModelSpec( key="nt-500m", hub_id="InstaDeepAI/nucleotide-transformer-v2-500m-multi-species", relpath="dna/nucleotide-transformer", task=DNA_SEQUENCE, description="embed or score a DNA sequence (Nucleotide Transformer v2)", ), "dnabert2": ModelSpec( key="dnabert2", hub_id="zhihan1996/DNABERT-2-117M", relpath="dna/dnabert2", task=DNA_SEQUENCE, description="embed a DNA sequence (DNABERT-2)", ), } def models_for_task(task: str) -> tuple[ModelSpec, ...]: """Every registered model that answers `task`, in registration order. Callers that want a consensus iterate this rather than naming one model, so adding a model to the registry widens the consensus without touching call sites. """ return tuple(m for m in REGISTRY.values() if m.task == task) def search_roots() -> list[Path]: """Model roots to try, most explicit first.""" roots: list[Path] = [] explicit = os.environ.get("VERA_MODEL_ROOT") if explicit: roots.append(Path(explicit).expanduser()) for entry in (os.environ.get("VERA_MODEL_PATH") or "").split(os.pathsep): if entry.strip(): roots.append(Path(entry.strip()).expanduser()) roots.extend(FALLBACK_ROOTS) return roots def _looks_like_a_model(path: Path) -> bool: """Whether `path` holds loadable weights, not just an empty placeholder. Checked because an interrupted copy leaves a directory that exists and fails at load time, several minutes into a run. Weights only -- the tokenizer is resolved separately by `resolve_tokenizer`, because some repos legitimately ship without one. """ if not path.is_dir(): return False if not (path / "config.json").is_file(): return False return any(path.glob("*.safetensors")) or any(path.glob("*.bin")) TOKENIZER_FILES = ("tokenizer.json", "tokenizer_config.json", "vocab.json", "spiece.model", "merges.txt") def has_tokenizer(path: Path) -> bool: """Whether a directory carries a usable tokenizer. Note the doubled `any`: ``any(path.glob(p) for p in ...)`` tests the truthiness of generator OBJECTS, which are always truthy, so that spelling returns True for an empty directory. This guard silently passed before it was mutation-tested. """ return any(any(path.glob(name)) for name in TOKENIZER_FILES) def resolve_tokenizer(key: str) -> tuple[str, str]: """Resolve where to load this model's tokenizer from. Returns: ``(target, source)`` as `resolve` does. Falls back to `tokenizer_hub_id`, then to the model's own hub id, when the local weights directory has no tokenizer files. """ spec = REGISTRY[key] local = find_local(key) if local is not None and has_tokenizer(local): return str(local), "local" return (spec.tokenizer_hub_id or spec.hub_id), "hub" def find_local(key: str) -> Path | None: """First local directory holding this model, or None. Raises: KeyError: If `key` is not registered, so a typo fails loudly rather than silently falling through to a download of nothing. """ spec = REGISTRY[key] for root in search_roots(): candidate = root / spec.relpath if _looks_like_a_model(candidate): return candidate return None def resolve(key: str) -> tuple[str, str]: """Resolve a model to something loadable. Args: key: Registry key. Returns: ``(target, source)`` where `target` is a local path or a hub id, and `source` is ``"local"`` or ``"hub"``. Callers should log `source`: a silent fall-through to the hub is how a 15 GB re-download happens on a machine that already had the file. Raises: KeyError: If `key` is not registered. """ spec = REGISTRY[key] if spec.kind != "hf": raise ValueError(f"{key!r} is a {spec.kind} model; resolve() is for hub weights") local = find_local(key) if local is not None: return str(local), "local" return spec.hub_id, "hub" def describe() -> str: """One line per registered model, for a prompt or a CLI listing.""" lines = [] for task in sorted({m.task for m in REGISTRY.values()}): lines.append(f"[{task}]") for spec in models_for_task(task): if spec.kind == "hf": target, source = resolve(spec.key) where = f"{source}: {target}" else: where = spec.kind lines.append(f" {spec.key:<14} {spec.description} [{where}]") return "\n".join(lines)