Datasets:
Potential confounding: Benign variants are missing gene names while pathogenetic variants have gene names.
#1
by jstjohnnv - opened
See page https://huggingface.co/datasets/wanglab/variant_effect_coding/viewer/default/train?p=320 for example where you can see examples of both pathogenetic and benign variants. Pathogenetic variants have gene names in the question while Benign variants do not.
Here's an analysis from claude:
ββββββββββββββββββ¬βββββββββ¬ββββββββββββββββββββββββ¬βββββββββ
β Split β Random β Gene-mention strategy β Boost β
ββββββββββββββββββΌβββββββββΌββββββββββββββββββββββββΌβββββββββ€
β train (48,850) β 50.3% β 99.2% β +48.9% β
ββββββββββββββββββΌβββββββββΌββββββββββββββββββββββββΌβββββββββ€
β test (1,233) β 51.6% β 99.2% β +47.6% β
ββββββββββββββββββ΄βββββββββ΄ββββββββββββββββββββββββ΄βββββββββ
0/17,398 Benign questions mention a gene; 32,299/32,685 (98.8%) Pathogenic ones do. The Benign vs Pathogenetic label is essentially encoded in the prompt, although the model would have to learn mappings between gene names and diseases to determine the rest of the pathogenetic label.
Root cause: BioReason/data/VEP.ipynb Cell 10 dispatches each row to one of two template sets based on whether the gene/gene_name fields are populated. ClinVar pathogenics always carry a gene annotation; gnomAD common-MAF benigns frequently don't β so template choice perfectly tracks
the label. (Cell 12 also has a not gene or gene_name precedence bug that inverts dispatch on the test split.) The sibling Clinvar_SNV_Non_SNV.ipynb (Task 4) interpolates <GENE_SYMBOL> unconditionally and does NOT reproduce the leak.
And code to generate the above table:
# /// script
# requires-python = ">=3.11"
# dependencies = ["datasets>=2.14", "rich>=13"]
# ///
"""
Demonstrates a data-leakage confound in the BioReason
``wanglab/variant_effect_coding`` dataset (their "Task 1" / coding-SNV
pathogenicity benchmark).
What the leak looks like
------------------------
- Pathogenic variants come from ClinVar; their rows almost always carry a
gene symbol + full description, which is interpolated into the question
text:
"This variant affects gene SRY (sex determining region Y) ..."
- Benign variants come from gnomAD common (MAF > 5%) and frequently lack
a gene annotation; the prompt template degenerates to:
"Located on Chromosome 1, this mutation has been observed ..."
A model can therefore predict pathogenicity well above chance by only
checking whether the question text mentions a gene, without ever looking
at the DNA sequence.
Where the bug originates
------------------------
``data/VEP.ipynb`` in https://github.com/bowang-lab/BioReason
- Cell 7 defines ``question_variants_50`` (templates that mention gene)
- Cell 8 defines ``question_variants_50_no_gene`` (chromosome-only)
- Cell 10 dispatches per-row on gene presence (train split):
if not (task_1.loc[id]['gene'] or task_1.loc[id]['gene_name']):
task_1_train[count]['question'] = (
question_variants_50_no_gene[random.randrange(50)]
.format(task_1.loc[id]['chromosome']))
else:
task_1_train[count]['question'] = (
question_variants_50[random.randrange(50)]
.format(task_1.loc[id]['chromosome'],
task_1.loc[id]['gene'],
task_1.loc[id]['gene_name']))
Because ClinVar pathogenic rows always carry gene annotation and gnomAD
common/benign rows often do not, the dispatch encodes pathogenicity
directly into the prompt text.
- Cell 12 (test) has a likely operator-precedence bug
(``not gene or gene_name`` without outer parens) that inverts the
dispatch on the held-out split.
By contrast the related notebook ``Clinvar_SNV_Non_SNV.ipynb`` (Task 4)
unconditionally interpolates ``<GENE_SYMBOL>`` for every row so it does
NOT reproduce this confound.
Inspired by:
https://huggingface.co/datasets/TIGER-Lab/MMLU-Pro/discussions/41
Usage
-----
uv run tmp_debug_bioreason.py # full dataset
uv run tmp_debug_bioreason.py --max-rows 2000 # quick smoke test
uv run tmp_debug_bioreason.py --splits test # one split only
"""
from __future__ import annotations
import argparse
import random
import re
from collections import defaultdict
from datasets import load_dataset
from rich.console import Console
from rich.table import Table
DATASET = "wanglab/variant_effect_coding"
# Heuristic gene-mention detector.
# Pathogenic prompts contain "gene SYMBOL", "SYMBOL (description)", or
# "in/affects/within SYMBOL". Benign prompts in this dataset typically only
# name a chromosome ("Located on Chromosome 1...").
GENE_RE = re.compile(
r"\bgene\s+[A-Z][A-Z0-9]{1,}\b" # "gene SRY"
r"|\b[A-Z][A-Z0-9]{2,}\s*\(" # "SRY (" / "TBL1Y ("
r"|\b(?:in|affects|affecting|impacts|impacting|within)\s+[A-Z][A-Z0-9]{2,}\b"
)
def has_gene_mention(text: str) -> bool:
return bool(GENE_RE.search(text or ""))
def normalise_label(answer: str) -> str:
"""Map free-text ground truth to 'Pathogenic' / 'Benign' / 'Other'."""
a = (answer or "").strip().lower()
if a.startswith("likely pathogenic") or a.startswith("pathogenic"):
return "Pathogenic"
if a.startswith("likely benign") or a.startswith("benign"):
return "Benign"
return "Other"
def analyse_split(split: str, max_rows: int | None, seed: int) -> dict:
rng = random.Random(seed)
ds = load_dataset(DATASET, split=split)
if max_rows is not None and len(ds) > max_rows:
ds = ds.select(range(max_rows))
sample = ds[0]
q_field = next((k for k in ("question", "Question", "prompt") if k in sample), None)
a_field = next((k for k in ("answer", "Answer", "label") if k in sample), None)
if q_field is None or a_field is None:
raise RuntimeError(f"Unrecognised schema; got fields {list(sample.keys())}")
s: dict = {
"total": 0,
"random_correct": 0,
"strategy_correct": 0,
"by_label": defaultdict(lambda: {"total": 0, "with_gene": 0}),
}
for row in ds:
label = normalise_label(row[a_field])
if label == "Other":
continue
s["total"] += 1
s["by_label"][label]["total"] += 1
gene = has_gene_mention(row[q_field])
if gene:
s["by_label"][label]["with_gene"] += 1
random_pred = rng.choice(("Pathogenic", "Benign"))
if random_pred == label:
s["random_correct"] += 1
strategy_pred = "Pathogenic" if gene else "Benign"
if strategy_pred == label:
s["strategy_correct"] += 1
return s
def main() -> None:
parser = argparse.ArgumentParser(
description="Demonstrate gene-name leakage in wanglab/variant_effect_coding."
)
parser.add_argument("--max-rows", type=int, default=None,
help="Cap rows per split (smoke test).")
parser.add_argument("--seed", type=int, default=42)
parser.add_argument("--splits", nargs="+", default=("train", "test"))
args = parser.parse_args()
console = Console()
overall: dict = {
"total": 0,
"random_correct": 0,
"strategy_correct": 0,
"by_label": defaultdict(lambda: {"total": 0, "with_gene": 0}),
}
splits_table = Table(title=f"{DATASET}: 'Gene-name in prompt' strategy")
splits_table.add_column("Split", style="cyan")
splits_table.add_column("N", justify="right")
splits_table.add_column("Random Acc", justify="right")
splits_table.add_column("Strategy Acc", justify="right", style="green")
splits_table.add_column("Boost", justify="right", style="yellow")
for split in args.splits:
try:
s = analyse_split(split, args.max_rows, args.seed)
except (ValueError, KeyError, RuntimeError) as exc:
console.print(f"[red]Skipped {split}: {exc}[/red]")
continue
if s["total"] == 0:
continue
ra = s["random_correct"] / s["total"] * 100
sa = s["strategy_correct"] / s["total"] * 100
boost = sa - ra
splits_table.add_row(
split, str(s["total"]), f"{ra:.1f}%", f"{sa:.1f}%",
f"+{boost:.1f}%" if boost >= 0 else f"{boost:.1f}%",
)
overall["total"] += s["total"]
overall["random_correct"] += s["random_correct"]
overall["strategy_correct"] += s["strategy_correct"]
for k, v in s["by_label"].items():
overall["by_label"][k]["total"] += v["total"]
overall["by_label"][k]["with_gene"] += v["with_gene"]
if overall["total"]:
splits_table.add_section()
ra = overall["random_correct"] / overall["total"] * 100
sa = overall["strategy_correct"] / overall["total"] * 100
splits_table.add_row(
"TOTAL", str(overall["total"]), f"{ra:.1f}%", f"{sa:.1f}%",
f"+{sa - ra:.1f}%", style="bold",
)
console.print(splits_table)
breakdown = Table(title="Gene-name mention rate by ground-truth label")
breakdown.add_column("Label", style="cyan")
breakdown.add_column("N", justify="right")
breakdown.add_column("With gene mention", justify="right", style="green")
breakdown.add_column("Rate", justify="right", style="yellow")
for label in sorted(overall["by_label"]):
v = overall["by_label"][label]
rate = v["with_gene"] / v["total"] * 100 if v["total"] else 0.0
breakdown.add_row(label, str(v["total"]), str(v["with_gene"]), f"{rate:.1f}%")
console.print(breakdown)
if __name__ == "__main__":
main()