ryan-superman's picture
Publish trajectories and metrics (BMB content gated)
a1b575d verified
Raw History Blame Contribute Delete
8.11 kB
"""Internal consistency checks: a dense progress signal computable without ground truth.
The point of this module is a licensing constraint, not a convenience. BioMysteryBench
is released for evaluation only -- its problems, rubrics and task formulation may not be
used to train, fine-tune, reinforce or distill a model. Test-time policy improvement
(JiTRL) needs a *dense progress signal*; the only signal the benchmark offers is one
terminal rubric grade, and manufacturing a denser one by fitting to that grade is exactly
what the licence forbids.
So every check here is computable from the **staged data and the agent's own intermediate
artifacts alone**. None consults a rubric, an answer, or a judge. That makes the resulting
score legal to compute at test time on a benchmark we may not train on.
Four kinds, chosen because each catches a failure mode that is invisible to the model's
own confidence:
* ``conservation`` -- a total that a transformation must preserve (cells before/after a
filter, reads before/after demultiplexing). Catches silent row loss, the classic
pipeline bug.
* ``range`` -- a value must lie in its mathematically admissible interval
(p-values in [0,1], correlations in [-1,1], counts non-negative).
* ``invariance`` -- an estimate must be stable across resampling or seeds. Catches
results driven by a handful of points.
* ``type`` -- an identifier must match the format of the biological entity it
claims to be. Catches transcript ids reported where gene ids were asked for.
**Design decision worth stating**: a node with no checks scores 0, not 1. Unverified is
not the same as verified, and scoring it 1 would reward the agent for making unfalsifiable
claims -- the opposite of the intent.
"""
from __future__ import annotations
import math
import re
from dataclasses import dataclass
from typing import Sequence
KINDS = ("conservation", "range", "invariance", "type")
@dataclass(frozen=True)
class CheckResult:
"""Outcome of one consistency check.
Attributes:
name: Human-readable identifier, e.g. ``"cells preserved across QC"``.
kind: One of `KINDS`. Used to weight and to report per-kind coverage.
passed: Whether the check held.
detail: Short explanation, always populated on failure so a transcript
reader can see *why* without re-running anything.
"""
name: str
kind: str
passed: bool
detail: str = ""
def __post_init__(self) -> None:
if self.kind not in KINDS:
raise ValueError(f"unknown check kind {self.kind!r}; expected one of {KINDS}")
def _finite(x) -> bool:
"""True if `x` is a real, finite number (NaN and inf are not)."""
try:
return math.isfinite(float(x))
except (TypeError, ValueError):
return False
def conservation(name: str, before: float, after: float, *, rel_tol: float = 1e-9) -> CheckResult:
"""Check that a scalar total survives a transformation.
Args:
name: What is being conserved.
before: Total before the transformation.
after: Total after it.
rel_tol: Relative tolerance. An absolute fallback of `rel_tol` is used when
`before` is zero, since a relative test is undefined there.
Returns:
A `CheckResult`. Non-finite inputs fail rather than raise: the agent's artifact
may legitimately contain a NaN, and that is a check failure, not a crash.
"""
if not (_finite(before) and _finite(after)):
return CheckResult(name, "conservation", False, f"non-finite: {before!r} -> {after!r}")
before, after = float(before), float(after)
denom = abs(before)
delta = abs(after - before)
ok = (delta <= rel_tol) if denom == 0 else (delta / denom <= rel_tol)
return CheckResult(
name, "conservation", ok,
"" if ok else f"{before:g} -> {after:g} (delta {delta:g}, rel_tol {rel_tol:g})",
)
def in_range(name: str, values: Sequence[float], lo: float, hi: float) -> CheckResult:
"""Check that every value lies within a closed admissible interval.
An **empty sequence fails**. A check over nothing is vacuously true, and treating
that as a pass would let an agent earn credit for producing no output.
Args:
name: What the values represent.
values: The values to test.
lo: Inclusive lower bound.
hi: Inclusive upper bound.
"""
vals = list(values)
if not vals:
return CheckResult(name, "range", False, "no values to check")
bad = [v for v in vals if not _finite(v) or not (lo <= float(v) <= hi)]
return CheckResult(
name, "range", not bad,
"" if not bad else f"{len(bad)}/{len(vals)} outside [{lo:g}, {hi:g}], e.g. {bad[0]!r}",
)
def invariance(name: str, replicates: Sequence[float], *, rel_tol: float = 0.1) -> CheckResult:
"""Check that an estimate is stable across resampled replicates.
Stability is measured as spread relative to centre, using the median and the median
absolute deviation rather than mean and standard deviation, so a single divergent
replicate does not by itself declare instability.
Args:
name: What was estimated.
replicates: Estimates from independent resamples or seeds. Fewer than two
**fails**: stability cannot be assessed from a single number, and calling
that a pass would reward skipping the resampling.
rel_tol: Maximum ``1.4826 * MAD / |median|`` for the estimate to count as stable.
"""
vals = [float(v) for v in replicates if _finite(v)]
if len(vals) < 2:
return CheckResult(name, "invariance", False,
f"need >=2 finite replicates, got {len(vals)}")
vals.sort()
n = len(vals)
med = vals[n // 2] if n % 2 else 0.5 * (vals[n // 2 - 1] + vals[n // 2])
devs = sorted(abs(v - med) for v in vals)
mad = devs[n // 2] if n % 2 else 0.5 * (devs[n // 2 - 1] + devs[n // 2])
scale = 1.4826 * mad
# A zero-centred estimate has no meaningful relative spread; fall back to absolute.
rel = scale if med == 0 else scale / abs(med)
ok = rel <= rel_tol
return CheckResult(name, "invariance", ok,
"" if ok else f"median {med:g}, robust sd {scale:g}, rel {rel:.3g} > {rel_tol:g}")
# Identifier formats for the entity types these benchmarks actually ask about.
ENTITY_PATTERNS = {
"ensembl_gene": r"^ENS[A-Z]*G\d{6,}(\.\d+)?$",
"ensembl_transcript": r"^ENS[A-Z]*T\d{6,}(\.\d+)?$",
"hgnc_symbol": r"^[A-Z][A-Z0-9\-]{0,14}$",
"uniprot": r"^([OPQ][0-9][A-Z0-9]{3}[0-9]|[A-NR-Z][0-9]([A-Z][A-Z0-9]{2}[0-9]){1,2})$",
"rsid": r"^rs\d+$",
"taxon_binomial": r"^[A-Z][a-z]+ [a-z]+$",
}
def entity_type(name: str, value: str, entity: str) -> CheckResult:
"""Check that an identifier matches the format of its declared biological entity.
Catches the specific, common failure of answering with the right *kind* of thing at
the wrong granularity -- a transcript id where a gene id was requested.
Args:
name: What the identifier is for.
value: The identifier as emitted.
entity: Key into `ENTITY_PATTERNS`.
Raises:
KeyError: If `entity` is not a known type. This is a programming error in the
check definition, not a property of the agent's output, so it raises.
"""
if entity not in ENTITY_PATTERNS:
raise KeyError(f"unknown entity type {entity!r}; known: {sorted(ENTITY_PATTERNS)}")
ok = bool(re.match(ENTITY_PATTERNS[entity], str(value).strip()))
return CheckResult(name, "type", ok, "" if ok else f"{value!r} is not a valid {entity}")
def rho(results: Sequence[CheckResult]) -> float:
"""Fraction of checks that passed -- the node's verification score.
Returns 0.0 for an empty check set. See the module docstring: unverified must not
score as verified, or the agent is rewarded for producing unfalsifiable claims.
"""
results = list(results)
if not results:
return 0.0
return sum(r.passed for r in results) / len(results)