Download code/vera/verify.py from ryan-superman/bio-agent-trajectories: direct link, hf CLI and curl.
- Browser
- Download file 7.52 kB
-
https://huggingface.co/datasets/ryan-superman/bio-agent-trajectories/resolve/main/code/vera/verify.py
- Command line
-
hf download hf://datasets/ryan-superman/bio-agent-trajectories/code/vera/verify.py
-
curl -L -o verify.py https://huggingface.co/datasets/ryan-superman/bio-agent-trajectories/resolve/main/code/vera/verify.py
7.52 kB
| """Harness-supplied answer verification: external checks the agent cannot author. | |
| Why this module replaces `vera.checks` as the source of the verification signal. Asking | |
| the model to write checks over its own artifacts was measured and failed: **0 of 17 | |
| emitted checks constrained anything**, and that did not change when the model was told | |
| in the prompt that vacuous checks score zero. A model that could author a falsifier for | |
| its own claim would already know the claim was wrong. | |
| So verification here is chosen by the *harness* from the answer's type and run against | |
| the staged data. That follows rbio1's finding that biological world models can act as | |
| soft verifiers where formal verification is unavailable, but applies it at inference time | |
| rather than as a training reward -- BioMysteryBench's licence forbids training on it. | |
| **Abstention is a first-class result.** A verifier that fires on everything is the vacuous | |
| check problem again, one level up. Each verifier states the conditions under which it is | |
| valid and returns `None` otherwise, and `None` must never be coerced to a score: an answer | |
| nobody can check is not an answer that failed. | |
| """ | |
| from __future__ import annotations | |
| import gzip | |
| import re | |
| from dataclasses import dataclass | |
| from pathlib import Path | |
| # Chromosome-1 length by assembly, in base pairs. A genome build claim is decidable from | |
| # the data alone, so it needs no model at all. | |
| BUILD_CHR1 = { | |
| "hg38": 248_956_422, "grch38": 248_956_422, | |
| "hg19": 249_250_621, "grch37": 249_250_621, | |
| "mm10": 195_471_971, "grcm38": 195_471_971, | |
| "mm39": 195_154_279, "grcm39": 195_154_279, | |
| } | |
| _TOKEN = re.compile(r"[A-Za-z0-9_.:+-]{2,}") | |
| _STOP = {"the", "and", "for", "with", "from", "sample", "samples", "gene", "genes", | |
| "cell", "cells", "type", "answer", "is", "are", "of", "in"} | |
| class Verdict: | |
| """Outcome of verifying one answer. | |
| Attributes: | |
| verifier: Which verifier ran, or "" when none applied. | |
| score: Confidence in [0, 1], or None when no verifier applied. None means | |
| *unknown*, never *wrong*. | |
| detail: Why, in one line. | |
| """ | |
| verifier: str | |
| score: float | None | |
| detail: str = "" | |
| def abstained(self) -> bool: | |
| """True when no verifier was valid for this answer.""" | |
| return self.score is None | |
| def _read_text(path: Path, limit: int = 4_000_000) -> str: | |
| """Read a possibly-gzipped text file, capped, returning "" on any failure.""" | |
| try: | |
| opener = gzip.open if path.suffix == ".gz" else open | |
| with opener(path, "rt", errors="replace") as fh: # type: ignore[operator] | |
| return fh.read(limit) | |
| except (OSError, EOFError, UnicodeDecodeError): | |
| return "" | |
| def answer_tokens(answer: str) -> list[str]: | |
| """Identifier-like tokens from an answer, minus common English words.""" | |
| return [t for t in _TOKEN.findall(answer or "") | |
| if t.lower() not in _STOP and not t.isdigit()] | |
| def verify_grounded(answer: str, workspace: Path, *, max_files: int = 40) -> Verdict: | |
| """Check that identifiers named in the answer occur in the staged data. | |
| Valid only when the answer names identifier-like tokens *and* the workspace holds | |
| readable text. An answer naming a sample or gene absent from the data it was derived | |
| from is very likely wrong; an answer naming an organism is not checkable this way, | |
| which is why this abstains rather than scoring such answers low. | |
| Args: | |
| answer: The candidate answer. | |
| workspace: Directory holding the staged data files. | |
| max_files: Cap on files scanned, to bound cost. | |
| Returns: | |
| Fraction of the answer's tokens found in the data, or an abstention. | |
| """ | |
| tokens = answer_tokens(answer) | |
| if not tokens: | |
| return Verdict("grounded", None, "answer names no identifiers") | |
| # Only identifier-shaped answers are groundable: prose and species names are not. | |
| idish = [t for t in tokens if any(c.isdigit() for c in t) or t.isupper() or "_" in t] | |
| if not idish: | |
| return Verdict("grounded", None, "answer has no identifier-shaped token") | |
| haystack = [] | |
| for path in sorted(p for p in workspace.rglob("*") if p.is_file())[:max_files]: | |
| haystack.append(_read_text(path)) | |
| blob = "\n".join(haystack) | |
| if not blob.strip(): | |
| return Verdict("grounded", None, "no readable staged text to check against") | |
| hits = [t for t in idish if t in blob] | |
| score = len(hits) / len(idish) | |
| return Verdict("grounded", score, | |
| f"{len(hits)}/{len(idish)} identifiers present in the data") | |
| def verify_genome_build(answer: str, workspace: Path) -> Verdict: | |
| """Decide a genome-build claim by comparing chromosome 1 length to known assemblies. | |
| Valid only when the answer names a build this module knows and the workspace exposes | |
| a chromosome-1 length. Fully deterministic: no model is involved. | |
| """ | |
| claimed = next((b for b in BUILD_CHR1 if b in (answer or "").lower()), None) | |
| if claimed is None: | |
| return Verdict("genome_build", None, "answer names no known assembly") | |
| observed = None | |
| for path in sorted(p for p in workspace.rglob("*") if p.is_file())[:40]: | |
| text = _read_text(path, limit=400_000) | |
| for m in re.finditer(r"^(?:chr)?1\b[^\n]*?(\d{8,10})", text, re.M | re.I): | |
| observed = int(m.group(1)) | |
| break | |
| if observed: | |
| break | |
| if observed is None: | |
| return Verdict("genome_build", None, "no chromosome-1 length found in the data") | |
| want = BUILD_CHR1[claimed] | |
| ok = abs(observed - want) <= max(1000, int(0.0001 * want)) | |
| return Verdict("genome_build", 1.0 if ok else 0.0, | |
| f"chr1 observed {observed:,} vs {claimed} {want:,}") | |
| VERIFIERS = (verify_genome_build, verify_grounded) | |
| def verify(answer: str, workspace: Path) -> Verdict: | |
| """Run the first applicable verifier, most specific first. | |
| Args: | |
| answer: Candidate answer. | |
| workspace: Staged data directory. | |
| Returns: | |
| The first non-abstaining `Verdict`, else an abstention naming no verifier. The | |
| order matters: a decidable check (genome build) must win over a probabilistic one | |
| (grounding), or a confident wrong answer could be scored on the weaker signal. | |
| """ | |
| for fn in VERIFIERS: | |
| verdict = fn(answer, workspace) | |
| if not verdict.abstained: | |
| return verdict | |
| return Verdict("", None, "no verifier applies to this answer") | |
| def select(candidates: list[str], workspace: Path) -> tuple[str, Verdict]: | |
| """Choose among candidate answers by verification score. | |
| Ties, and the all-abstain case, fall back to the first candidate: with no signal the | |
| method must not pretend to have one. Callers should treat an abstaining verdict as | |
| "unselected" rather than "verified". | |
| Args: | |
| candidates: Answers from independent trajectories, best-effort order preserved. | |
| workspace: Staged data directory. | |
| Returns: | |
| ``(answer, verdict)`` for the chosen candidate. | |
| """ | |
| usable = [c for c in candidates if (c or "").strip()] | |
| if not usable: | |
| return "", Verdict("", None, "no candidate answers") | |
| scored = [(c, verify(c, workspace)) for c in usable] | |
| best = max(scored, key=lambda cv: (cv[1].score is not None, cv[1].score or 0.0)) | |
| if best[1].abstained: | |
| return usable[0], Verdict("", None, "no verifier applied to any candidate") | |
| return best | |