""" PROTOCOL PROBE -- BASE MODEL, 100 IDENTICAL QUESTIONS ======================================================= Prof. Adnan's 9-step diagnostic protocol vs the base model's natural reasoning. WHY THIS IS A REAL TEST (not another reword): The four prior arms all LOST to neutral (21% on 100 base Q). But those were loose "flag pathognomonic features + note LRs" nudges. THIS prompt is a structured MCQ protocol with techniques none of them had: - options-first (build the differential from the answers before the vignette) - explicit red-herring / distractor naming - a bias audit (anchoring, premature closure, confirmation, availability, framing) - "the answer must BEAT every alternative, not merely fit" That last one attacks the specific MCQ failure mode (plausible-but-not-best answer) that none of the prior arms addressed. So this could genuinely differ. TWO ARMS ONLY (no forced-Bayesian -- confirmed dead 3x; no gated -- superseded): 1. neutral : base's natural reasoning (CONTROL -- compare to the 21% we measured) 2. protocol : the 9-step diagnostic protocol RAISED TOKEN CAP (2600 vs 1536): the protocol is long; it must reach 'Answer: X' before being cut off, or accuracy is measuring truncation, not reasoning. VERDICT = ACCURACY vs neutral. - protocol > neutral by >3 pts on 100Q => the structured protocol genuinely helps. THEN it's worth testing on V15, and worth reporting. - protocol ~= neutral => structure doesn't help even done well; natural reasoning wins. - protocol < neutral => consistent with the prior pattern; structure hurts. Run (fire-and-forget; 2 arms x 100 q x 2600 tok ~ 4-5h -> sbatch): MODEL_DIR=$HOME/pentabrid/base_models/Qwen3.6-27B \ python3 ~/pentabrid/scripts/probe_protocol_base.py --limit 100 """ import os, re, json, glob, time, argparse from pathlib import Path import torch from transformers import AutoTokenizer, AutoModelForCausalLM 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/protocol_probe")) NEUTRAL_TAIL = "Think step by step, then end with exactly: 'Answer: X' where X is the letter." # Prof. Adnan's 9-step protocol, verbatim (only the closing-line instruction is shared). PROTOCOL_TAIL = ( "You are answering a clinical multiple-choice question. Follow this protocol:\n" "1. OPTIONS FIRST - Before reading the vignette, read every answer option. For each, " "recall its classic presentation and the 1-2 findings that would best rule it in or out. " "These options are your working differential.\n" "2. PRETEST PROBABILITY - From demographics, risk factors, and setting alone, rank the " "options by baseline likelihood (avoid base-rate neglect: common things are common; rare " "diagnoses need strong evidence).\n" "3. EXTRACT ALL DATA - Read the vignette line by line. List every positive finding AND " "pertinent negative (history, vitals, exam, labs, imaging, time course). Tag each as: " "supports / opposes / discriminates between options / non-specific.\n" "4. BAYESIAN UPDATE - Revise your ranking finding by finding. Cite a likelihood ratio ONLY " "where it is genuinely well established; never invent numbers. If no reliable LR exists, " "update qualitatively ('markedly raises / slightly lowers probability'). Highly specific " "findings shift probability most; sensitive-but-nonspecific findings shift it little.\n" "5. PATHOGNOMONIC CHECK - Flag any pathognomonic or highly specific feature, then verify the " "rest of the picture (demographics, tempo, associated findings) is consistent with it. A " "buzzword contradicted by other data is a trap, not an answer.\n" "6. RED HERRINGS - Explicitly name any distractor findings (incidental, non-specific, " "explained by a comorbidity, or planted to suggest a wrong option) and state why each does " "not change your ranking.\n" "7. ELIMINATE - Address every option one by one. Reject an option only by citing the specific " "finding(s) that make it incompatible or improbable. The chosen answer must beat every " "alternative, not merely fit the case.\n" "8. BIAS AUDIT - One line each before finalizing: Anchoring: am I stuck on my first " "impression? Premature closure: did I check ALL options against ALL findings before stopping? " "Confirmation bias: did I weigh contradictory evidence as seriously as supporting evidence? " "Availability / representativeness: am I choosing this because it is memorable or 'looks " "typical,' rather than because the data fit? Framing / diagnosis momentum: am I accepting a " "label given in the stem without verifying it?\n" "9. FINAL CHECK - The answer must explain the chief complaint, the key positives, AND the " "pertinent negatives better than every rejected option. If two options remain close, name the " "single discriminating finding that decides between them.\n" "End your entire response with this final line and nothing after it (no punctuation, no text):\n" "Answer: X\n" "where X is the letter of the chosen option." ) ARMS = [("neutral", NEUTRAL_TAIL), ("protocol", PROTOCOL_TAIL)] 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) PATHO_PATTERNS = [r"pathognomonic", r"highly specific", r"hallmark", r"classic(?:ally)?\b", r"diagnostic of", r"characteristic of"] _patho_re = re.compile("|".join(PATHO_PATTERNS), re.IGNORECASE) def build_prompt(r, tail, protocol=False): q = r.get("question", "") opts = r.get("options") olines = [] if isinstance(opts, dict): for k in sorted(opts): olines.append(f"{k}. {opts[k]}") elif isinstance(opts, list): for i, o in enumerate(opts): olines.append(f"{chr(65+i)}. {o}") # For the protocol arm, put the protocol FIRST so 'options first' is followed, # then the question + options. For neutral, question first then the tail. if protocol: return tail + "\n\nQUESTION:\n" + q + "\n\nOPTIONS:\n" + "\n".join(olines) return "\n".join([q, ""] + olines + ["", tail]) 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 run_arm(model, tok, rows, tail, label): is_proto = (label == "protocol") correct = 0; total_lr = 0; total_patho = 0; truncated = 0; recs = [] for i, r in enumerate(rows): msgs = [{"role": "user", "content": build_prompt(r, tail, protocol=is_proto)}] 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=2600, 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 # did it run out of room before writing an answer line? no_answer_line = ("nswer" not in text) lr = len(_lr_re.findall(text or "")); pa = len(_patho_re.findall(text or "")) correct += int(ok); total_lr += lr; total_patho += pa; truncated += int(no_answer_line) recs.append({"id": r.get("id"), "pred": pred, "gold": gold, "correct": ok, "lr_markers": lr, "patho_markers": pa, "no_answer_line": no_answer_line, "text": text}) print(f" [{label}] {i+1}/{len(rows)} acc={100*correct/(i+1):.0f}% " f"lr={total_lr} patho={total_patho} no_ans={truncated}", flush=True) return { "label": label, "n": len(rows), "accuracy_pct": round(100 * correct / max(1, len(rows)), 1), "total_lr_markers": total_lr, "mean_lr_markers_per_answer": round(total_lr / max(1, len(rows)), 2), "mean_pathognomonic_per_answer": round(total_patho / max(1, len(rows)), 2), "answers_missing_answer_line": truncated, }, recs def main(): ap = argparse.ArgumentParser() ap.add_argument("--limit", type=int, default=100) 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() summaries = {} for label, tail in ARMS: s, recs = run_arm(model, tok, rows, tail, label) summaries[label] = s (OUTDIR / f"{label}_records.jsonl").write_text( "\n".join(json.dumps(x, ensure_ascii=False) for x in recs), encoding="utf-8") mins = (time.perf_counter() - t0) / 60 out = {"model": MODEL, "n": len(rows), "minutes": round(mins, 1), **summaries} (OUTDIR / "protocol_summary.json").write_text(json.dumps(out, indent=2)) base = summaries["neutral"]["accuracy_pct"] proto = summaries["protocol"]["accuracy_pct"] print("\n" + "=" * 70) print("PROTOCOL PROBE -- BASE MODEL, 100 IDENTICAL QUESTIONS") print("=" * 70) print(f"{'arm':10}{'acc%':>8}{'vs neutral':>12}{'LR/ans':>9}{'patho/ans':>11}{'no-ans':>8}") for label, _ in ARMS: s = summaries[label] d = "(control)" if label == "neutral" else f"{s['accuracy_pct']-base:+.1f} pts" print(f"{s['label']:10}{s['accuracy_pct']:>8}{d:>12}{s['mean_lr_markers_per_answer']:>9}" f"{s['mean_pathognomonic_per_answer']:>11}{s['answers_missing_answer_line']:>8}") print("-" * 70) dd = proto - base if dd > 3: print(f"=> PROTOCOL HELPS: {dd:+.1f} pts over natural reasoning. Worth testing on V15,") print(" and worth reporting. Your structured protocol beat the plain prompt.") elif dd >= -3: print(f"=> PROTOCOL ~= neutral ({dd:+.1f} pts, within noise). Even a well-built protocol") print(" doesn't beat the base's natural reasoning here.") else: print(f"=> PROTOCOL WORSE ({dd:+.1f} pts). Consistent with the prior pattern: structure hurts.") if summaries["protocol"]["answers_missing_answer_line"] > 8: print(f" NOTE: {summaries['protocol']['answers_missing_answer_line']}/100 protocol answers " f"had no answer line (truncation) -- raise max_new_tokens and rerun if this is high.") print(f"\nWrote -> {OUTDIR}/protocol_summary.json (+ per-arm records)") if __name__ == "__main__": main()