File size: 7,519 Bytes
4859287
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
"""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"}


@dataclass(frozen=True)
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 = ""

    @property
    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