Datasets:

DOI:
pentabrid-reproducibility / scripts /probe_bayesian_v14.py
naturally-intuitive's picture
Upload folder using huggingface_hub
1769068 verified
Raw
History Blame Contribute Delete
8.26 kB
#!/usr/bin/env python3
"""
PENTABRID — ZERO-COST LATENT-CAPABILITY PROBE (V14)
====================================================
Question: does V14 ALREADY know how to reason in likelihood ratios, and we just
never asked it to on MedXpertQA? The golden cases were TRAINED with the instruction
"Analyze this clinical case using systematic Bayesian reasoning. Apply likelihood
ratios where possible..." but the MedXpertQA eval prompt only says "Think step by
step." So the capability may be latent — present but not triggered by the eval prompt.
This runs V14 on the SAME small slice of MedXpertQA TWICE:
PROMPT A (neutral) : the exact eval prompt ("Think step by step...")
PROMPT B (bayesian) : explicitly asks for pre-test probability + likelihood ratios
Then it compares, for each arm:
- accuracy on the slice
- how many answers contain LR / Bayesian markers, and how dense they are
INTERPRETATION
- If B shows MANY more LR markers than A -> the capability is LATENT. You can get
Bayesian reasoning for FREE by changing the eval/inference prompt. No V16 needed
to elicit the BEHAVIOR (though scoring it is a separate question).
- If B shows roughly the SAME (near-zero) LR markers as A -> the capability is NOT
really there; prompting won't summon it, and only a stronger teacher / RL would
instil it. That tells you a data-mix V16 is the wrong tool.
- Watch accuracy too: if B reasons in LRs but accuracy DROPS, the LR style isn't
helping the answer (important to know before building a whole model around it).
ONE GPU, ~20 min for the default 60-question slice.
USAGE (on a GPU node):
module load cuda/12.6
source /home/adnanagha/miniforge3/etc/profile.d/conda.sh && conda activate pentabrid
MODEL_DIR=$HOME/pentabrid/runs/V14_27B_merged python3 ~/pentabrid/scripts/probe_bayesian_v14.py --limit 60
"""
import os, re, json, glob, time, argparse
from pathlib import Path
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
MODEL = os.environ["MODEL_DIR"]
MEDX = os.environ.get("MEDX_DIR", f"{os.environ['HOME']}/pentabrid/datasets/MedXpertQA")
OUTDIR = Path(os.environ.get("OUTDIR", f"{os.environ['HOME']}/pentabrid/runs/bayesian_probe"))
# ---- the two prompts. Only the final instruction line differs. ----
NEUTRAL_TAIL = "Think step by step, then end with exactly: 'Answer: X' where X is the letter."
BAYESIAN_TAIL = (
"Reason as a diagnostician using EXPLICIT Bayesian logic: state the pre-test "
"probability of the leading diagnoses, cite approximate likelihood ratios (LR+ / LR-) "
"for the key findings, update to a post-test probability, and rule alternatives in or "
"out using pertinent positives and negatives. Then end with exactly: 'Answer: X' "
"where X is the letter."
)
# ---- markers that indicate genuine Bayesian / LR reasoning ----
LR_PATTERNS = [
r"likelihood ratio", r"\bLR[+\-]?\b", r"pre-?test", r"post-?test",
r"prior probability", r"posterior", r"\bbayes", r"pertinent (?:positive|negative)",
r"\bodds\b", r"sensitivity", r"specificity",
]
_lr_re = re.compile("|".join(LR_PATTERNS), re.IGNORECASE)
def build_prompt(r, tail):
q = r.get("question", "")
opts = r.get("options")
lines = [q, ""]
if isinstance(opts, dict):
for k in sorted(opts): lines.append(f"{k}. {opts[k]}")
elif isinstance(opts, list):
for i, o in enumerate(opts): lines.append(f"{chr(65+i)}. {o}")
lines += ["", tail]
return "\n".join(lines)
def gold_letter(r):
g = str(r.get("label", r.get("answer", ""))).strip()
m = re.search(r"[A-Z]", g.upper())
return m.group(0) if m else g.upper()
def parse_letter(text):
m = re.findall(r"[Aa]nswer\s*[:\-]?\s*([A-Za-z])", text)
if m: return m[-1].upper()
m = re.findall(r"\b([A-J])\b", text)
return m[-1].upper() if m else ""
def lr_markers(text):
return len(_lr_re.findall(text or ""))
def run_arm(model, tok, rows, tail, label):
correct = 0
total_markers = 0
answers_with_markers = 0
recs = []
for i, r in enumerate(rows):
msgs = [{"role": "user", "content": build_prompt(r, tail)}]
enc = tok.apply_chat_template(
[msgs], add_generation_prompt=True,
return_tensors="pt", return_dict=True, padding=True).to(model.device)
with torch.no_grad():
out = model.generate(**enc, max_new_tokens=1536,
do_sample=False, pad_token_id=tok.pad_token_id)
gen = out[:, enc["input_ids"].shape[1]:]
text = tok.batch_decode(gen, skip_special_tokens=True)[0]
pred, gold = parse_letter(text), gold_letter(r)
ok = bool(pred) and pred == gold
mk = lr_markers(text)
correct += int(ok)
total_markers += mk
answers_with_markers += int(mk > 0)
recs.append({"id": r.get("id"), "pred": pred, "gold": gold, "correct": ok,
"lr_markers": mk, "text": text})
print(f" [{label}] {i+1}/{len(rows)} acc={100*correct/(i+1):.0f}% "
f"lr_markers_so_far={total_markers}", flush=True)
return {
"label": label, "n": len(rows),
"accuracy_pct": round(100 * correct / max(1, len(rows)), 1),
"answers_with_any_lr_marker": answers_with_markers,
"total_lr_markers": total_markers,
"mean_lr_markers_per_answer": round(total_markers / max(1, len(rows)), 2),
}, recs
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--limit", type=int, default=60, help="questions to test (same set for both arms)")
args = ap.parse_args()
cands = glob.glob(f"{MEDX}/**/Text/**/test*.jsonl", recursive=True) + \
glob.glob(f"{MEDX}/**/test*.jsonl", recursive=True)
if not cands:
raise SystemExit(f"Could not find MedXpertQA Text test.jsonl under {MEDX}")
rows = [json.loads(l) for l in open(sorted(cands)[0]) if l.strip()][:args.limit]
OUTDIR.mkdir(parents=True, exist_ok=True)
tok = AutoTokenizer.from_pretrained(MODEL)
tok.padding_side = "left"
if tok.pad_token is None:
tok.pad_token = tok.eos_token
print(f"loading {MODEL} ...", flush=True)
model = AutoModelForCausalLM.from_pretrained(
MODEL, torch_dtype=torch.bfloat16, device_map="cuda").eval()
t0 = time.perf_counter()
sa, ra = run_arm(model, tok, rows, NEUTRAL_TAIL, "neutral")
sb, rb = run_arm(model, tok, rows, BAYESIAN_TAIL, "bayesian")
mins = (time.perf_counter() - t0) / 60
(OUTDIR / "neutral_records.jsonl").write_text(
"\n".join(json.dumps(x, ensure_ascii=False) for x in ra), encoding="utf-8")
(OUTDIR / "bayesian_records.jsonl").write_text(
"\n".join(json.dumps(x, ensure_ascii=False) for x in rb), encoding="utf-8")
summary = {"model": MODEL, "n": len(rows), "minutes": round(mins, 1),
"neutral": sa, "bayesian": sb}
(OUTDIR / "probe_summary.json").write_text(json.dumps(summary, indent=2))
print("\n" + "=" * 60)
print("BAYESIAN LATENT-CAPABILITY PROBE — V14")
print("=" * 60)
print(f"{'arm':10}{'acc%':>8}{'ans w/LR':>11}{'total LR':>11}{'LR/ans':>9}")
for s in (sa, sb):
print(f"{s['label']:10}{s['accuracy_pct']:>8}{s['answers_with_any_lr_marker']:>11}"
f"{s['total_lr_markers']:>11}{s['mean_lr_markers_per_answer']:>9}")
print("-" * 60)
dm = sb["mean_lr_markers_per_answer"] - sa["mean_lr_markers_per_answer"]
da = sb["accuracy_pct"] - sa["accuracy_pct"]
print(f"LR-marker change (bayesian - neutral): {dm:+.2f} per answer")
print(f"accuracy change (bayesian - neutral): {da:+.1f} pts")
if dm >= 1.0:
print("\n=> Bayesian reasoning is LATENT: the model produces far more LR reasoning")
print(" when asked. You can elicit the BEHAVIOR for free via the prompt.")
if da < -2:
print(" BUT accuracy dropped — the LR style isn't improving answers here.")
else:
print("\n=> Prompting did NOT summon LR reasoning. The capability isn't really")
print(" present; a data-mix V16 won't instil it (would need a stronger teacher/RL).")
print(f"\nWrote -> {OUTDIR}/probe_summary.json (+ per-answer records)")
if __name__ == "__main__":
main()