Datasets:

DOI:
naturally-intuitive commited on
Commit
1769068
·
verified ·
1 Parent(s): 80a8c36

Upload folder using huggingface_hub

Browse files
README.md ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Pentabrid 27B — Reproducibility Package
2
+
3
+ Artifacts supporting the Nature Medicine Matters Arising response to Oermann & Vishwanath (2026), "General-purpose LLMs outperform specialized clinical AI tools on medical benchmarks" (s41591-026-04431-5).
4
+
5
+ ## Core finding
6
+ At fixed scale and offline (no retrieval), the specialization procedure determines medical reasoning performance. A short-CoT fine-tune (V13) collapsed the base model's reasoning (about 3,100 to about 760 tokens) and dropped MedXpertQA accuracy by 16.9 points; a corrected long-CoT approach (V14) restored reasoning length and recovered accuracy to near-parity. Framing: recovery to near-parity (41.7 vs 43.8), reversing the regression, not superiority over the base model.
7
+
8
+ ## Results (MedXpertQA, full 2,450 questions; scorer-verified)
9
+ See results_summary.csv. Base 43.76, V13 26.90, V14 41.67, V15 41.35, V16 (alpha=64) 42.20. V15 and V16 are two independent null ablations confirming the recovery is robust to configuration.
10
+
11
+ ## Contents
12
+ - scripts/merge_medxpertqa.py — the scorer (exact match on 'Answer: X'; audit this for the no-inflation claim)
13
+ - scripts/eval_generic_medxpertqa.slurm, eval_mcq_hf.* — evaluation harnesses
14
+ - scripts/train_v14.py + .sbatch, merge_lora_v14.py — training and adapter merge
15
+ - scripts/probe_*.py — reasoning-structure probes
16
+ - results_summary.csv — the locked results table
17
+
18
+ ## Base model and benchmarks (not redistributed here)
19
+ Base: Qwen3.6-27B (official Qwen repository). Benchmarks: MedXpertQA, MedQA, MedMCQA, used under their own licenses, not included here.
20
+
21
+ ## Authors
22
+ Prof. Adnan Agha (ORCID 0000-0002-2704-8931) and Eram Anwar (ORCID 0009-0006-9335-9208), UAEU College of Medicine and Health Sciences / Tawam Hospital. IP: UAEU Application #2442.
23
+
24
+ ## License
25
+ CC-BY-NC-ND-4.0
results_summary.csv ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ model,mix,medxpertqa_2450,medqa_500,medmcqa_500,median_think_tokens
2
+ Base,-,43.76,86.8,73.8,3100
3
+ V13,curated-heavy short-CoT,26.90,84.4,71.6,760
4
+ V14,74pct RFT / 26pct curated,41.67,84.4,76.0,3700
5
+ V15,50/50,41.35,84.4,74.6,3738
6
+ V16,50/50 alpha=64,42.20,83.8,73.4,4000
scripts/eval_generic_medxpertqa.slurm ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # PENTABRID - generic MedXpertQA-Text eval (reusable for ANY model).
3
+ # Pass MODEL_DIR and OUT_DIR at submit time; num-shards auto-matches the array width.
4
+ #
5
+ # # V13 re-run (finishes fast - it stops early):
6
+ # sbatch --array=0-3 --job-name=v13_8k \
7
+ # --export=ALL,MODEL_DIR=$HOME/pentabrid/runs/V13_27B_merged,OUT_DIR=$HOME/pentabrid/runs/V13_eval_8k \
8
+ # ~/pentabrid/scripts/eval_generic_medxpertqa.slurm
9
+ #
10
+ # # BASE re-run (the slow one - it reasons long; use more shards):
11
+ # sbatch --array=0-7 --job-name=base_8k \
12
+ # --export=ALL,MODEL_DIR=/home/adnanagha/pentabrid/base_models/Qwen3.6-27B,OUT_DIR=$HOME/pentabrid/runs/BASE_eval_8k \
13
+ # ~/pentabrid/scripts/eval_generic_medxpertqa.slurm
14
+ #
15
+ #SBATCH --partition=gpuq
16
+ #SBATCH --gres=gpu:1
17
+ #SBATCH --array=0-3
18
+ #SBATCH --time=24:00:00
19
+ #SBATCH --mem=120G
20
+ #SBATCH --job-name=medx_gen
21
+ #SBATCH --output=medx_%x_%A_%a.out
22
+
23
+ module load cuda/12.2
24
+ source ~/miniforge3/bin/activate pentabrid
25
+
26
+ : "${MODEL_DIR:?set MODEL_DIR via --export}"
27
+ : "${OUT_DIR:?set OUT_DIR via --export}"
28
+ export MEDX_DIR=${MEDX_DIR:-$HOME/pentabrid/datasets/MedXpertQA}
29
+ export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True
30
+ mkdir -p "$OUT_DIR"
31
+
32
+ echo "host=$(hostname) task=$SLURM_ARRAY_TASK_ID/$SLURM_ARRAY_TASK_COUNT model=$MODEL_DIR out=$OUT_DIR $(date)"
33
+ nvidia-smi --query-gpu=name,memory.total --format=csv,noheader
34
+
35
+ python ~/pentabrid/scripts/eval_medxpertqa_hf_v2.py \
36
+ --shard-id "$SLURM_ARRAY_TASK_ID" --num-shards "$SLURM_ARRAY_TASK_COUNT" --batch-size 8
37
+
38
+ echo "task=$SLURM_ARRAY_TASK_ID done $(date)"
scripts/eval_mcq_hf.py ADDED
@@ -0,0 +1,191 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ PENTABRID - generation-based MCQ evaluator (MedMCQA / MedQA), fixed parser.
4
+ ===========================================================================
5
+ Same HF-generation method and v2 parser as the MedXpert evaluator, so V13 and
6
+ base are scored identically and the "answer is" -> "I" trap is gone. Saves the
7
+ full answer text per question (re-analysable) and writes a score json.
8
+
9
+ Run on a single A100 (these sets are small). Cache the dataset on the LOGIN node
10
+ first (compute nodes are offline), then run with HF_DATASETS_OFFLINE=1.
11
+
12
+ SMOKE FIRST (verify the schema parsed correctly before the full run):
13
+ MODEL_DIR=$HOME/pentabrid/runs/V13_27B_merged OUT_DIR=$HOME/pentabrid/runs/V13_mcq \
14
+ python eval_mcq_hf.py --dataset medmcqa --limit 3 --batch-size 1
15
+ -> prints the detected (question, options, gold) for the first few rows. If gold
16
+ letters and option text look right, drop --limit and run for real.
17
+
18
+ FULL RUNS (examples):
19
+ # MedMCQA, 1000 questions, V13:
20
+ MODEL_DIR=$HOME/pentabrid/runs/V13_27B_merged OUT_DIR=$HOME/pentabrid/runs/V13_mcq \
21
+ python eval_mcq_hf.py --dataset medmcqa --limit 1000 --seed 62
22
+ # MedQA-500 (seed 62), base:
23
+ MODEL_DIR=/home/adnanagha/pentabrid/base_models/Qwen3.6-27B OUT_DIR=$HOME/pentabrid/runs/BASE_mcq \
24
+ python eval_mcq_hf.py --dataset medqa --limit 500 --seed 62
25
+
26
+ Data source: by default loads the dataset from the HF cache (set the id with --hf
27
+ if yours differs). Or point --jsonl at a local file you already downloaded.
28
+ """
29
+ import os, re, json, argparse, random
30
+ from pathlib import Path
31
+ import torch
32
+ from transformers import AutoModelForCausalLM, AutoTokenizer
33
+
34
+ ap = argparse.ArgumentParser()
35
+ ap.add_argument("--dataset", choices=["medmcqa", "medqa"], help="built-in schema + default HF id/split")
36
+ ap.add_argument("--hf", default=None, help="override HF dataset id")
37
+ ap.add_argument("--config", default=None, help="HF dataset config name (if any)")
38
+ ap.add_argument("--split", default=None, help="override split (medmcqa->validation, medqa->test)")
39
+ ap.add_argument("--jsonl", default=None, help="load from a local jsonl instead of HF")
40
+ ap.add_argument("--limit", type=int, default=0, help="cap number of questions (0 = all)")
41
+ ap.add_argument("--seed", type=int, default=62, help="seed for the subsample shuffle")
42
+ ap.add_argument("--batch-size", type=int, default=8)
43
+ args = ap.parse_args()
44
+
45
+ MODEL = os.environ["MODEL_DIR"]
46
+ OUTDIR = Path(os.environ.get("OUT_DIR", MODEL)); OUTDIR.mkdir(parents=True, exist_ok=True)
47
+ tag = args.dataset or "custom"
48
+ OUT = OUTDIR / f"{tag}_results.jsonl"
49
+ SCORE = OUTDIR / f"{tag}_score.json"
50
+
51
+ # ---------------------------------------------------------------------------
52
+ # schema registry: (default HF id, default split, row->(question, options{}, gold))
53
+ # ---------------------------------------------------------------------------
54
+ def _med_mcqa(r):
55
+ opts = {"A": r.get("opa",""), "B": r.get("opb",""), "C": r.get("opc",""), "D": r.get("opd","")}
56
+ cop = r.get("cop", r.get("answer", ""))
57
+ gold = ""
58
+ if isinstance(cop, int): gold = "ABCD"[cop] if 0 <= cop < 4 else ""
59
+ elif isinstance(cop, str):
60
+ s = cop.strip()
61
+ if s.isdigit() and 0 <= int(s) < 4: gold = "ABCD"[int(s)]
62
+ elif s[:1].upper() in "ABCD": gold = s[:1].upper()
63
+ return r.get("question",""), opts, gold
64
+
65
+ def _med_qa(r):
66
+ q = r.get("question","")
67
+ o = r.get("options")
68
+ if isinstance(o, dict): options = {k.upper(): v for k, v in o.items()}
69
+ elif isinstance(o, list): options = {chr(65+i): v for i, v in enumerate(o)}
70
+ else: options = {}
71
+ a = r.get("answer_idx", r.get("answer", r.get("answer_letter","")))
72
+ gold = ""
73
+ if isinstance(a, int): gold = chr(65+a)
74
+ elif isinstance(a, str) and len(a.strip()) <= 2 and a.strip()[:1].upper() in "ABCDEFGHIJ":
75
+ gold = a.strip()[:1].upper()
76
+ elif isinstance(a, str): # answer given as full text -> match option
77
+ na = re.sub(r"\s+"," ",a.lower()).strip()
78
+ for k, v in options.items():
79
+ if re.sub(r"\s+"," ",str(v).lower()).strip() == na: gold = k; break
80
+ return q, options, gold
81
+
82
+ REGISTRY = {
83
+ "medmcqa": ("openlifescienceai/medmcqa", "validation", _med_mcqa),
84
+ "medqa": ("GBaker/MedQA-USMLE-4-options", "test", _med_qa),
85
+ }
86
+
87
+ # ---------------------------------------------------------------------------
88
+ # load rows
89
+ # ---------------------------------------------------------------------------
90
+ if args.jsonl:
91
+ rows = [json.loads(l) for l in open(args.jsonl) if l.strip()]
92
+ extract = REGISTRY[args.dataset][2] if args.dataset else None
93
+ if extract is None:
94
+ raise SystemExit("With --jsonl you must also pass --dataset for the schema (medmcqa/medqa).")
95
+ src = args.jsonl
96
+ else:
97
+ if not args.dataset and not args.hf:
98
+ raise SystemExit("Pass --dataset medmcqa|medqa (or --hf <id> with --dataset for schema).")
99
+ hf_id, split, extract = REGISTRY[args.dataset]
100
+ hf_id = args.hf or hf_id
101
+ split = args.split or split
102
+ from datasets import load_dataset
103
+ ds = load_dataset(hf_id, args.config, split=split) if args.config else load_dataset(hf_id, split=split)
104
+ rows = [dict(x) for x in ds]
105
+ src = f"{hf_id}:{split}"
106
+ print(f"Loaded {len(rows)} rows from {src}", flush=True)
107
+
108
+ # reproducible subsample
109
+ if args.limit and args.limit > 0 and args.limit < len(rows):
110
+ rnd = random.Random(args.seed); idx = list(range(len(rows))); rnd.shuffle(idx)
111
+ rows = [rows[i] for i in idx[:args.limit]]
112
+ print(f"Subsampled to {len(rows)} (seed {args.seed})", flush=True)
113
+
114
+ # ---------------------------------------------------------------------------
115
+ # prompt + v2 parser (identical to eval_medxpertqa_hf_v2.py)
116
+ # ---------------------------------------------------------------------------
117
+ def build_prompt(q, options):
118
+ lines = [q, ""]
119
+ for k in sorted(options): lines.append(f"{k}. {options[k]}")
120
+ lines += ["", "Think step by step, then end with exactly: 'Answer: X' where X is the letter."]
121
+ return "\n".join(lines)
122
+
123
+ _PATS = [
124
+ r"\bfinal\s+answer\b\s*(?:is|:|=|-)?\s*\(?\*{0,2}([A-J])\b",
125
+ r"\bcorrect\s+(?:answer|option|choice)\b\s*(?:is|:|=|-)?\s*\(?\*{0,2}([A-J])\b",
126
+ r"\banswer\s*(?:is|:|=|-)\s*\(?\*{0,2}([A-J])\b",
127
+ r"\bthe answer is\b\s*\(?\*{0,2}([A-J])\b",
128
+ r"\banswer\s+\(?\*{0,2}([A-J])\b",
129
+ r"\b(?:option|choice)\s*(?:is|:|=|-)?\s*\(?\*{0,2}([A-J])\b",
130
+ ]
131
+ def parse_letter(text):
132
+ if not text: return ""
133
+ seg = text.rsplit("</think>", 1)[-1]; seg = seg if seg.strip() else text
134
+ for pat in _PATS:
135
+ m = re.findall(pat, seg, re.IGNORECASE)
136
+ if m: return m[-1].upper()
137
+ m = re.findall(r"\banswer\s*(?:is|:|=|-)?\s*\(?\*{0,2}([A-J])\b", text, re.IGNORECASE)
138
+ if m: return m[-1].upper()
139
+ m = re.findall(r"\*\*\s*([A-J])\s*\*\*|\(\s*([A-J])\s*\)", seg)
140
+ flat=[x for p in m for x in p if x]
141
+ if flat: return flat[-1].upper()
142
+ m = re.findall(r"\b([A-J])\b", seg)
143
+ return m[-1].upper() if m else ""
144
+
145
+ # parse all rows up front; show a sample so schema errors are caught immediately
146
+ parsed = []
147
+ for i, r in enumerate(rows):
148
+ q, options, gold = extract(r)
149
+ parsed.append((str(r.get("id", i)), q, options, gold))
150
+ print("\n--- schema check (first up to 3 rows) ---", flush=True)
151
+ for rid, q, options, gold in parsed[:3]:
152
+ print(f" id={rid} gold={gold!r} #opts={len(options)} q[:80]={q[:80]!r}", flush=True)
153
+ for k in sorted(options): print(f" {k}. {str(options[k])[:60]}", flush=True)
154
+ bad_gold = sum(1 for _,_,_,g in parsed if not g)
155
+ if bad_gold: print(f" WARNING: {bad_gold}/{len(parsed)} rows have no parseable gold - check the schema/split.", flush=True)
156
+ print("--- end schema check ---\n", flush=True)
157
+
158
+ # ---------------------------------------------------------------------------
159
+ # load model
160
+ # ---------------------------------------------------------------------------
161
+ print(f"Loading model from {MODEL} ...", flush=True)
162
+ tok = AutoTokenizer.from_pretrained(MODEL); tok.padding_side = "left"
163
+ if tok.pad_token is None: tok.pad_token = tok.eos_token
164
+ model = AutoModelForCausalLM.from_pretrained(MODEL, torch_dtype=torch.bfloat16, device_map="cuda").eval()
165
+ print("model loaded.", flush=True)
166
+
167
+ # ---------------------------------------------------------------------------
168
+ # batched greedy generation (section-5 return_dict fix)
169
+ # ---------------------------------------------------------------------------
170
+ B = max(1, args.batch_size); correct = run = 0
171
+ with open(OUT, "w") as fout:
172
+ for start in range(0, len(parsed), B):
173
+ batch = parsed[start:start+B]
174
+ msgs = [[{"role":"user","content":build_prompt(q, o)}] for _,q,o,_ in batch]
175
+ enc = tok.apply_chat_template(msgs, add_generation_prompt=True,
176
+ return_tensors="pt", return_dict=True, padding=True).to(model.device)
177
+ with torch.no_grad():
178
+ out = model.generate(**enc, max_new_tokens=2048, do_sample=False, pad_token_id=tok.pad_token_id)
179
+ gen = out[:, enc["input_ids"].shape[1]:]
180
+ texts = tok.batch_decode(gen, skip_special_tokens=True)
181
+ for (rid,q,o,gold), text in zip(batch, texts):
182
+ pred = parse_letter(text); ok = bool(pred) and pred == gold
183
+ correct += int(ok); run += 1
184
+ fout.write(json.dumps({"id":rid,"pred":pred,"gold":gold,"correct":ok,"text":text})+"\n")
185
+ fout.flush()
186
+ print(f" {run}/{len(parsed)} done acc {100.0*correct/max(1,run):.1f}%", flush=True)
187
+
188
+ acc = 100.0*correct/max(1,len(parsed))
189
+ SCORE.write_text(json.dumps({"dataset":tag,"raw":correct,"total":len(parsed),
190
+ "accuracy_pct":round(acc,2),"parser":"fixed_v2"}, indent=2))
191
+ print(f"\n{tag} raw={correct}/{len(parsed)} accuracy={acc:.2f}%\nWrote {SCORE}", flush=True)
scripts/measure_reasoning_v14.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ PENTABRID V14 — MEASURE REASONING LENGTH (Gate G1)
4
+ ==================================================
5
+ Reads MedXpertQA eval result shards (medxpertqa_results_shard*.jsonl, each row
6
+ {id, pred, gold, correct, text}) and reports the distribution of REASONING
7
+ tokens, so you can compare V14 vs base.
8
+ Target: V14 median ~= base (~3,000), far above V13's collapsed ~760.
9
+
10
+ Tokens are counted with the base model's tokenizer (CPU only, no GPU needed).
11
+ The "reasoning" is the text inside <think>...</think> if present, else everything
12
+ before the final 'Answer:' line.
13
+
14
+ USAGE:
15
+ python3 measure_reasoning_v14.py <results_dir>
16
+ e.g.
17
+ python3 measure_reasoning_v14.py ~/pentabrid/runs/BASE_eval_8k
18
+ python3 measure_reasoning_v14.py ~/pentabrid/runs/V14_27B_merged
19
+ """
20
+ import sys, os, re, json, glob, statistics
21
+
22
+ TOKENIZER_SRC = os.environ.get("TOKENIZER_SRC",
23
+ "/home/adnanagha/pentabrid/base_models/Qwen3.6-27B")
24
+
25
+
26
+ def reasoning_part(text):
27
+ m = re.search(r"<think>(.*?)</think>", text, re.DOTALL)
28
+ if m:
29
+ return m.group(1)
30
+ idx = text.rfind("Answer:")
31
+ return text[:idx] if idx > 0 else text
32
+
33
+
34
+ def main(results_dir):
35
+ files = glob.glob(os.path.join(results_dir, "medxpertqa_results_shard*.jsonl"))
36
+ if not files:
37
+ sys.exit(f"No medxpertqa_results_shard*.jsonl found in {results_dir}")
38
+
39
+ try:
40
+ from transformers import AutoTokenizer
41
+ tok = AutoTokenizer.from_pretrained(TOKENIZER_SRC)
42
+ count = lambda s: len(tok.encode(s, add_special_tokens=False))
43
+ method = "tokenizer"
44
+ except Exception as e:
45
+ print(f"(tokenizer unavailable: {e}\n using chars/4 estimate instead)")
46
+ count = lambda s: len(s) // 4
47
+ method = "chars/4"
48
+
49
+ lengths = []
50
+ for fp in files:
51
+ for line in open(fp):
52
+ line = line.strip()
53
+ if not line:
54
+ continue
55
+ try:
56
+ r = json.loads(line)
57
+ except Exception:
58
+ continue
59
+ lengths.append(count(reasoning_part(r.get("text", ""))))
60
+
61
+ lengths.sort()
62
+ n = len(lengths)
63
+ if n == 0:
64
+ sys.exit("no records found")
65
+ pct = lambda q: lengths[min(n - 1, int(q * n))]
66
+ print(f"results dir : {results_dir}")
67
+ print(f"records : {n} (token method: {method})")
68
+ print(f"reasoning tokens median={statistics.median(lengths):.0f} "
69
+ f"mean={statistics.mean(lengths):.0f} p25={pct(0.25)} p75={pct(0.75)} "
70
+ f"min={lengths[0]} max={lengths[-1]}")
71
+ print(f" long (>=1500 tok): {sum(1 for x in lengths if x >= 1500)}/{n} "
72
+ f"short (<800 tok): {sum(1 for x in lengths if x < 800)}/{n}")
73
+
74
+
75
+ if __name__ == "__main__":
76
+ if len(sys.argv) < 2:
77
+ sys.exit("usage: python3 measure_reasoning_v14.py <results_dir>")
78
+ main(sys.argv[1])
scripts/merge_lora_v14.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ PENTABRID V14 — MERGE LoRA ADAPTER INTO BASE
4
+ ============================================
5
+ Produces a standalone merged model the eval script can load directly
6
+ (same loader as eval_medxpertqa_hf.py, no trust_remote_code).
7
+
8
+ Run on ONE GPU (fits a 27B bf16 copy on an 80 GB A100). USAGE:
9
+ srun --partition=gpuq --gres=gpu:1 --time=01:00:00 --pty bash
10
+ # then on the node:
11
+ module load cuda/12.6
12
+ source /home/adnanagha/miniforge3/etc/profile.d/conda.sh && conda activate pentabrid
13
+ python3 ~/pentabrid/scripts/merge_lora_v14.py
14
+ """
15
+ import os
16
+ import torch
17
+ from transformers import AutoModelForCausalLM, AutoTokenizer
18
+ from peft import PeftModel
19
+
20
+ BASE = os.environ.get("BASE", "/home/adnanagha/pentabrid/base_models/Qwen3.6-27B")
21
+ ADAPTER = os.environ.get("ADAPTER", "/home/adnanagha/pentabrid/runs/V14_lora")
22
+ OUT = os.environ.get("OUT", "/home/adnanagha/pentabrid/runs/V14_27B_merged")
23
+
24
+ print(f"loading base from {BASE} ...", flush=True)
25
+ base = AutoModelForCausalLM.from_pretrained(BASE, torch_dtype=torch.bfloat16)
26
+ print(f"applying adapter from {ADAPTER} ...", flush=True)
27
+ model = PeftModel.from_pretrained(base, ADAPTER)
28
+ print("merging adapter into weights ...", flush=True)
29
+ model = model.merge_and_unload()
30
+ print(f"saving merged model -> {OUT} ...", flush=True)
31
+ model.save_pretrained(OUT, safe_serialization=True)
32
+ AutoTokenizer.from_pretrained(BASE).save_pretrained(OUT)
33
+ print(f"DONE. For evaluation, set MODEL_DIR={OUT}", flush=True)
scripts/merge_medxpertqa.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ PENTABRID V13 (27B) - merge sharded MedXpertQA-Text results into one score.
4
+ Run AFTER every array task has finished.
5
+
6
+ MODEL_DIR=$HOME/pentabrid/runs/V13_27B_merged \
7
+ MEDX_DIR=$HOME/pentabrid/datasets/MedXpertQA \
8
+ python merge_medxpertqa.py
9
+
10
+ Writes medxpertqa_text_score.json with the same schema as the original vLLM
11
+ script: {"raw": int, "total": int, "accuracy_pct": float}.
12
+ De-dupes by question id, so a re-run shard cannot double-count, and sanity-checks
13
+ the total against the test-set size to catch a missing or still-running shard.
14
+ NOTE: only reads medxpertqa_results_shard*.jsonl - smoke files
15
+ (medxpertqa_smoketest_*.jsonl) are deliberately ignored.
16
+ """
17
+ import os, json, glob
18
+ from pathlib import Path
19
+
20
+ MODEL = os.environ["MODEL_DIR"]
21
+ MEDX = os.environ.get("MEDX_DIR", f"{os.environ['HOME']}/pentabrid/datasets/MedXpertQA")
22
+
23
+ # expected total = number of questions in the Text test set
24
+ cands = glob.glob(f"{MEDX}/**/Text/**/test*.jsonl", recursive=True) + \
25
+ glob.glob(f"{MEDX}/**/test*.jsonl", recursive=True)
26
+ expected = None
27
+ if cands:
28
+ test_file = sorted(cands)[0]
29
+ expected = sum(1 for l in open(test_file) if l.strip())
30
+
31
+ # gather every real shard file (NOT the smoke files)
32
+ shard_files = sorted(glob.glob(f"{MODEL}/medxpertqa_results_shard*.jsonl"))
33
+ if not shard_files:
34
+ raise SystemExit(f"No shard result files found under {MODEL}")
35
+ print(f"Merging {len(shard_files)} shard file(s):")
36
+ for f in shard_files:
37
+ print(" -", f)
38
+
39
+ seen = {} # id -> correct(bool); de-dupes across/within shards
40
+ for f in shard_files:
41
+ for line in open(f):
42
+ line = line.strip()
43
+ if not line:
44
+ continue
45
+ rec = json.loads(line)
46
+ seen[rec["id"]] = bool(rec["correct"])
47
+
48
+ total = len(seen)
49
+ correct = sum(1 for v in seen.values() if v)
50
+ acc = 100.0 * correct / max(1, total)
51
+
52
+ print(f"\nMedXpertQA-Text raw={correct}/{total} accuracy={acc:.2f}%")
53
+ if expected is not None:
54
+ if total == expected:
55
+ print(f"OK: counted all {expected} questions.")
56
+ else:
57
+ print(f"WARNING: expected {expected} questions but merged {total}. "
58
+ f"A shard may be missing, failed, or still running.")
59
+
60
+ out = Path(MODEL) / "medxpertqa_text_score.json"
61
+ out.write_text(json.dumps(
62
+ {"raw": correct, "total": total, "accuracy_pct": round(acc, 2)}, indent=2))
63
+ print(f"\nWrote {out}")
scripts/prep_mcr_baseline.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re, json, os
2
+ from datasets import load_dataset
3
+ HOME=os.environ["HOME"]
4
+ MEDX=f"{HOME}/pentabrid/datasets/MedXpertQA/Text/test.jsonl"
5
+ OUT=f"{HOME}/pentabrid/datasets/mcr_clinician_baseline.jsonl"
6
+ def dequote(s):
7
+ s=str(s)
8
+ for ch in ['\u201c','\u201d','\u201e','\u201f','\u2033','"']: s=s.replace(ch,'')
9
+ return re.sub(r'[ \t]+',' ',s).strip()
10
+ def words(s): return re.findall(r"[a-z0-9]+", str(s).lower())
11
+ def grams(t,n): return set(tuple(t[i:i+n]) for i in range(len(t)-n+1)) if len(t)>=n else set()
12
+ G13=set(); nref=0
13
+ with open(MEDX) as f:
14
+ for line in f:
15
+ line=line.strip()
16
+ if not line: continue
17
+ r=json.loads(line); parts=[str(v) for v in r.values() if isinstance(v,str)]
18
+ for v in r.values():
19
+ if isinstance(v,dict): parts+=[str(x) for x in v.values()]
20
+ G13|=grams(words(" ".join(parts)),13); nref+=1
21
+ print(f"decontam ref: {nref} MedXpertQA questions, {len(G13)} 13-grams")
22
+ mcr=load_dataset("zou-lab/MedCaseReasoning",split="train")
23
+ kept=[]; dc=0
24
+ for ex in mcr:
25
+ cp=str(ex.get("case_prompt","")).strip(); dr=dequote(ex.get("diagnostic_reasoning","")); dx=str(ex.get("final_diagnosis","")).strip()
26
+ if not cp or not dr or not dx: continue
27
+ if grams(words(cp),13)&G13: dc+=1; continue
28
+ instr=cp+"\n\nReason through the differential diagnosis step by step, then give the single most likely diagnosis on a final line as 'Diagnosis: <name>'."
29
+ output="<think>\n"+dr+"\n</think>\n\nDiagnosis: "+dx
30
+ kept.append({"instruction":instr,"input":"","output":output,"source":"medcasereasoning"})
31
+ with open(OUT,"w") as f:
32
+ for r in kept: f.write(json.dumps(r,ensure_ascii=False)+"\n")
33
+ print(f"kept={len(kept)} dropped_contam={dc} -> {OUT} ({os.path.getsize(OUT)/1e6:.1f} MB)")
scripts/probe_bayesian_v14.py ADDED
@@ -0,0 +1,184 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ PENTABRID — ZERO-COST LATENT-CAPABILITY PROBE (V14)
4
+ ====================================================
5
+ Question: does V14 ALREADY know how to reason in likelihood ratios, and we just
6
+ never asked it to on MedXpertQA? The golden cases were TRAINED with the instruction
7
+ "Analyze this clinical case using systematic Bayesian reasoning. Apply likelihood
8
+ ratios where possible..." but the MedXpertQA eval prompt only says "Think step by
9
+ step." So the capability may be latent — present but not triggered by the eval prompt.
10
+
11
+ This runs V14 on the SAME small slice of MedXpertQA TWICE:
12
+ PROMPT A (neutral) : the exact eval prompt ("Think step by step...")
13
+ PROMPT B (bayesian) : explicitly asks for pre-test probability + likelihood ratios
14
+
15
+ Then it compares, for each arm:
16
+ - accuracy on the slice
17
+ - how many answers contain LR / Bayesian markers, and how dense they are
18
+
19
+ INTERPRETATION
20
+ - If B shows MANY more LR markers than A -> the capability is LATENT. You can get
21
+ Bayesian reasoning for FREE by changing the eval/inference prompt. No V16 needed
22
+ to elicit the BEHAVIOR (though scoring it is a separate question).
23
+ - If B shows roughly the SAME (near-zero) LR markers as A -> the capability is NOT
24
+ really there; prompting won't summon it, and only a stronger teacher / RL would
25
+ instil it. That tells you a data-mix V16 is the wrong tool.
26
+ - Watch accuracy too: if B reasons in LRs but accuracy DROPS, the LR style isn't
27
+ helping the answer (important to know before building a whole model around it).
28
+
29
+ ONE GPU, ~20 min for the default 60-question slice.
30
+
31
+ USAGE (on a GPU node):
32
+ module load cuda/12.6
33
+ source /home/adnanagha/miniforge3/etc/profile.d/conda.sh && conda activate pentabrid
34
+ MODEL_DIR=$HOME/pentabrid/runs/V14_27B_merged python3 ~/pentabrid/scripts/probe_bayesian_v14.py --limit 60
35
+ """
36
+ import os, re, json, glob, time, argparse
37
+ from pathlib import Path
38
+ import torch
39
+ from transformers import AutoModelForCausalLM, AutoTokenizer
40
+
41
+ MODEL = os.environ["MODEL_DIR"]
42
+ MEDX = os.environ.get("MEDX_DIR", f"{os.environ['HOME']}/pentabrid/datasets/MedXpertQA")
43
+ OUTDIR = Path(os.environ.get("OUTDIR", f"{os.environ['HOME']}/pentabrid/runs/bayesian_probe"))
44
+
45
+ # ---- the two prompts. Only the final instruction line differs. ----
46
+ NEUTRAL_TAIL = "Think step by step, then end with exactly: 'Answer: X' where X is the letter."
47
+ BAYESIAN_TAIL = (
48
+ "Reason as a diagnostician using EXPLICIT Bayesian logic: state the pre-test "
49
+ "probability of the leading diagnoses, cite approximate likelihood ratios (LR+ / LR-) "
50
+ "for the key findings, update to a post-test probability, and rule alternatives in or "
51
+ "out using pertinent positives and negatives. Then end with exactly: 'Answer: X' "
52
+ "where X is the letter."
53
+ )
54
+
55
+ # ---- markers that indicate genuine Bayesian / LR reasoning ----
56
+ LR_PATTERNS = [
57
+ r"likelihood ratio", r"\bLR[+\-]?\b", r"pre-?test", r"post-?test",
58
+ r"prior probability", r"posterior", r"\bbayes", r"pertinent (?:positive|negative)",
59
+ r"\bodds\b", r"sensitivity", r"specificity",
60
+ ]
61
+ _lr_re = re.compile("|".join(LR_PATTERNS), re.IGNORECASE)
62
+
63
+
64
+ def build_prompt(r, tail):
65
+ q = r.get("question", "")
66
+ opts = r.get("options")
67
+ lines = [q, ""]
68
+ if isinstance(opts, dict):
69
+ for k in sorted(opts): lines.append(f"{k}. {opts[k]}")
70
+ elif isinstance(opts, list):
71
+ for i, o in enumerate(opts): lines.append(f"{chr(65+i)}. {o}")
72
+ lines += ["", tail]
73
+ return "\n".join(lines)
74
+
75
+
76
+ def gold_letter(r):
77
+ g = str(r.get("label", r.get("answer", ""))).strip()
78
+ m = re.search(r"[A-Z]", g.upper())
79
+ return m.group(0) if m else g.upper()
80
+
81
+
82
+ def parse_letter(text):
83
+ m = re.findall(r"[Aa]nswer\s*[:\-]?\s*([A-Za-z])", text)
84
+ if m: return m[-1].upper()
85
+ m = re.findall(r"\b([A-J])\b", text)
86
+ return m[-1].upper() if m else ""
87
+
88
+
89
+ def lr_markers(text):
90
+ return len(_lr_re.findall(text or ""))
91
+
92
+
93
+ def run_arm(model, tok, rows, tail, label):
94
+ correct = 0
95
+ total_markers = 0
96
+ answers_with_markers = 0
97
+ recs = []
98
+ for i, r in enumerate(rows):
99
+ msgs = [{"role": "user", "content": build_prompt(r, tail)}]
100
+ enc = tok.apply_chat_template(
101
+ [msgs], add_generation_prompt=True,
102
+ return_tensors="pt", return_dict=True, padding=True).to(model.device)
103
+ with torch.no_grad():
104
+ out = model.generate(**enc, max_new_tokens=1536,
105
+ do_sample=False, pad_token_id=tok.pad_token_id)
106
+ gen = out[:, enc["input_ids"].shape[1]:]
107
+ text = tok.batch_decode(gen, skip_special_tokens=True)[0]
108
+ pred, gold = parse_letter(text), gold_letter(r)
109
+ ok = bool(pred) and pred == gold
110
+ mk = lr_markers(text)
111
+ correct += int(ok)
112
+ total_markers += mk
113
+ answers_with_markers += int(mk > 0)
114
+ recs.append({"id": r.get("id"), "pred": pred, "gold": gold, "correct": ok,
115
+ "lr_markers": mk, "text": text})
116
+ print(f" [{label}] {i+1}/{len(rows)} acc={100*correct/(i+1):.0f}% "
117
+ f"lr_markers_so_far={total_markers}", flush=True)
118
+ return {
119
+ "label": label, "n": len(rows),
120
+ "accuracy_pct": round(100 * correct / max(1, len(rows)), 1),
121
+ "answers_with_any_lr_marker": answers_with_markers,
122
+ "total_lr_markers": total_markers,
123
+ "mean_lr_markers_per_answer": round(total_markers / max(1, len(rows)), 2),
124
+ }, recs
125
+
126
+
127
+ def main():
128
+ ap = argparse.ArgumentParser()
129
+ ap.add_argument("--limit", type=int, default=60, help="questions to test (same set for both arms)")
130
+ args = ap.parse_args()
131
+
132
+ cands = glob.glob(f"{MEDX}/**/Text/**/test*.jsonl", recursive=True) + \
133
+ glob.glob(f"{MEDX}/**/test*.jsonl", recursive=True)
134
+ if not cands:
135
+ raise SystemExit(f"Could not find MedXpertQA Text test.jsonl under {MEDX}")
136
+ rows = [json.loads(l) for l in open(sorted(cands)[0]) if l.strip()][:args.limit]
137
+
138
+ OUTDIR.mkdir(parents=True, exist_ok=True)
139
+ tok = AutoTokenizer.from_pretrained(MODEL)
140
+ tok.padding_side = "left"
141
+ if tok.pad_token is None:
142
+ tok.pad_token = tok.eos_token
143
+ print(f"loading {MODEL} ...", flush=True)
144
+ model = AutoModelForCausalLM.from_pretrained(
145
+ MODEL, torch_dtype=torch.bfloat16, device_map="cuda").eval()
146
+
147
+ t0 = time.perf_counter()
148
+ sa, ra = run_arm(model, tok, rows, NEUTRAL_TAIL, "neutral")
149
+ sb, rb = run_arm(model, tok, rows, BAYESIAN_TAIL, "bayesian")
150
+ mins = (time.perf_counter() - t0) / 60
151
+
152
+ (OUTDIR / "neutral_records.jsonl").write_text(
153
+ "\n".join(json.dumps(x, ensure_ascii=False) for x in ra), encoding="utf-8")
154
+ (OUTDIR / "bayesian_records.jsonl").write_text(
155
+ "\n".join(json.dumps(x, ensure_ascii=False) for x in rb), encoding="utf-8")
156
+ summary = {"model": MODEL, "n": len(rows), "minutes": round(mins, 1),
157
+ "neutral": sa, "bayesian": sb}
158
+ (OUTDIR / "probe_summary.json").write_text(json.dumps(summary, indent=2))
159
+
160
+ print("\n" + "=" * 60)
161
+ print("BAYESIAN LATENT-CAPABILITY PROBE — V14")
162
+ print("=" * 60)
163
+ print(f"{'arm':10}{'acc%':>8}{'ans w/LR':>11}{'total LR':>11}{'LR/ans':>9}")
164
+ for s in (sa, sb):
165
+ print(f"{s['label']:10}{s['accuracy_pct']:>8}{s['answers_with_any_lr_marker']:>11}"
166
+ f"{s['total_lr_markers']:>11}{s['mean_lr_markers_per_answer']:>9}")
167
+ print("-" * 60)
168
+ dm = sb["mean_lr_markers_per_answer"] - sa["mean_lr_markers_per_answer"]
169
+ da = sb["accuracy_pct"] - sa["accuracy_pct"]
170
+ print(f"LR-marker change (bayesian - neutral): {dm:+.2f} per answer")
171
+ print(f"accuracy change (bayesian - neutral): {da:+.1f} pts")
172
+ if dm >= 1.0:
173
+ print("\n=> Bayesian reasoning is LATENT: the model produces far more LR reasoning")
174
+ print(" when asked. You can elicit the BEHAVIOR for free via the prompt.")
175
+ if da < -2:
176
+ print(" BUT accuracy dropped — the LR style isn't improving answers here.")
177
+ else:
178
+ print("\n=> Prompting did NOT summon LR reasoning. The capability isn't really")
179
+ print(" present; a data-mix V16 won't instil it (would need a stronger teacher/RL).")
180
+ print(f"\nWrote -> {OUTDIR}/probe_summary.json (+ per-answer records)")
181
+
182
+
183
+ if __name__ == "__main__":
184
+ main()
scripts/probe_protocol_base.py ADDED
@@ -0,0 +1,217 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ PROTOCOL PROBE -- BASE MODEL, 100 IDENTICAL QUESTIONS
3
+ =======================================================
4
+ Prof. Adnan's 9-step diagnostic protocol vs the base model's natural reasoning.
5
+
6
+ WHY THIS IS A REAL TEST (not another reword):
7
+ The four prior arms all LOST to neutral (21% on 100 base Q). But those were loose
8
+ "flag pathognomonic features + note LRs" nudges. THIS prompt is a structured MCQ
9
+ protocol with techniques none of them had:
10
+ - options-first (build the differential from the answers before the vignette)
11
+ - explicit red-herring / distractor naming
12
+ - a bias audit (anchoring, premature closure, confirmation, availability, framing)
13
+ - "the answer must BEAT every alternative, not merely fit"
14
+ That last one attacks the specific MCQ failure mode (plausible-but-not-best answer)
15
+ that none of the prior arms addressed. So this could genuinely differ.
16
+
17
+ TWO ARMS ONLY (no forced-Bayesian -- confirmed dead 3x; no gated -- superseded):
18
+ 1. neutral : base's natural reasoning (CONTROL -- compare to the 21% we measured)
19
+ 2. protocol : the 9-step diagnostic protocol
20
+
21
+ RAISED TOKEN CAP (2600 vs 1536): the protocol is long; it must reach 'Answer: X'
22
+ before being cut off, or accuracy is measuring truncation, not reasoning.
23
+
24
+ VERDICT = ACCURACY vs neutral.
25
+ - protocol > neutral by >3 pts on 100Q => the structured protocol genuinely helps.
26
+ THEN it's worth testing on V15, and worth reporting.
27
+ - protocol ~= neutral => structure doesn't help even done well; natural reasoning wins.
28
+ - protocol < neutral => consistent with the prior pattern; structure hurts.
29
+
30
+ Run (fire-and-forget; 2 arms x 100 q x 2600 tok ~ 4-5h -> sbatch):
31
+ MODEL_DIR=$HOME/pentabrid/base_models/Qwen3.6-27B \
32
+ python3 ~/pentabrid/scripts/probe_protocol_base.py --limit 100
33
+ """
34
+ import os, re, json, glob, time, argparse
35
+ from pathlib import Path
36
+ import torch
37
+ from transformers import AutoTokenizer, AutoModelForCausalLM
38
+
39
+ MODEL = os.environ["MODEL_DIR"]
40
+ MEDX = os.environ.get("MEDX_DIR", f"{os.environ['HOME']}/pentabrid/datasets/MedXpertQA")
41
+ OUTDIR = Path(os.environ.get("OUTDIR", f"{os.environ['HOME']}/pentabrid/runs/protocol_probe"))
42
+
43
+ NEUTRAL_TAIL = "Think step by step, then end with exactly: 'Answer: X' where X is the letter."
44
+
45
+ # Prof. Adnan's 9-step protocol, verbatim (only the closing-line instruction is shared).
46
+ PROTOCOL_TAIL = (
47
+ "You are answering a clinical multiple-choice question. Follow this protocol:\n"
48
+ "1. OPTIONS FIRST - Before reading the vignette, read every answer option. For each, "
49
+ "recall its classic presentation and the 1-2 findings that would best rule it in or out. "
50
+ "These options are your working differential.\n"
51
+ "2. PRETEST PROBABILITY - From demographics, risk factors, and setting alone, rank the "
52
+ "options by baseline likelihood (avoid base-rate neglect: common things are common; rare "
53
+ "diagnoses need strong evidence).\n"
54
+ "3. EXTRACT ALL DATA - Read the vignette line by line. List every positive finding AND "
55
+ "pertinent negative (history, vitals, exam, labs, imaging, time course). Tag each as: "
56
+ "supports / opposes / discriminates between options / non-specific.\n"
57
+ "4. BAYESIAN UPDATE - Revise your ranking finding by finding. Cite a likelihood ratio ONLY "
58
+ "where it is genuinely well established; never invent numbers. If no reliable LR exists, "
59
+ "update qualitatively ('markedly raises / slightly lowers probability'). Highly specific "
60
+ "findings shift probability most; sensitive-but-nonspecific findings shift it little.\n"
61
+ "5. PATHOGNOMONIC CHECK - Flag any pathognomonic or highly specific feature, then verify the "
62
+ "rest of the picture (demographics, tempo, associated findings) is consistent with it. A "
63
+ "buzzword contradicted by other data is a trap, not an answer.\n"
64
+ "6. RED HERRINGS - Explicitly name any distractor findings (incidental, non-specific, "
65
+ "explained by a comorbidity, or planted to suggest a wrong option) and state why each does "
66
+ "not change your ranking.\n"
67
+ "7. ELIMINATE - Address every option one by one. Reject an option only by citing the specific "
68
+ "finding(s) that make it incompatible or improbable. The chosen answer must beat every "
69
+ "alternative, not merely fit the case.\n"
70
+ "8. BIAS AUDIT - One line each before finalizing: Anchoring: am I stuck on my first "
71
+ "impression? Premature closure: did I check ALL options against ALL findings before stopping? "
72
+ "Confirmation bias: did I weigh contradictory evidence as seriously as supporting evidence? "
73
+ "Availability / representativeness: am I choosing this because it is memorable or 'looks "
74
+ "typical,' rather than because the data fit? Framing / diagnosis momentum: am I accepting a "
75
+ "label given in the stem without verifying it?\n"
76
+ "9. FINAL CHECK - The answer must explain the chief complaint, the key positives, AND the "
77
+ "pertinent negatives better than every rejected option. If two options remain close, name the "
78
+ "single discriminating finding that decides between them.\n"
79
+ "End your entire response with this final line and nothing after it (no punctuation, no text):\n"
80
+ "Answer: X\n"
81
+ "where X is the letter of the chosen option."
82
+ )
83
+
84
+ ARMS = [("neutral", NEUTRAL_TAIL), ("protocol", PROTOCOL_TAIL)]
85
+
86
+ LR_PATTERNS = [r"likelihood ratio", r"\bLR[+\-]?\b", r"pre-?test", r"post-?test",
87
+ r"prior probability", r"posterior", r"\bbayes", r"pertinent (?:positive|negative)",
88
+ r"\bodds\b", r"sensitivity", r"specificity"]
89
+ _lr_re = re.compile("|".join(LR_PATTERNS), re.IGNORECASE)
90
+ PATHO_PATTERNS = [r"pathognomonic", r"highly specific", r"hallmark", r"classic(?:ally)?\b",
91
+ r"diagnostic of", r"characteristic of"]
92
+ _patho_re = re.compile("|".join(PATHO_PATTERNS), re.IGNORECASE)
93
+
94
+
95
+ def build_prompt(r, tail, protocol=False):
96
+ q = r.get("question", "")
97
+ opts = r.get("options")
98
+ olines = []
99
+ if isinstance(opts, dict):
100
+ for k in sorted(opts): olines.append(f"{k}. {opts[k]}")
101
+ elif isinstance(opts, list):
102
+ for i, o in enumerate(opts): olines.append(f"{chr(65+i)}. {o}")
103
+ # For the protocol arm, put the protocol FIRST so 'options first' is followed,
104
+ # then the question + options. For neutral, question first then the tail.
105
+ if protocol:
106
+ return tail + "\n\nQUESTION:\n" + q + "\n\nOPTIONS:\n" + "\n".join(olines)
107
+ return "\n".join([q, ""] + olines + ["", tail])
108
+
109
+
110
+ def gold_letter(r):
111
+ g = str(r.get("label", r.get("answer", ""))).strip()
112
+ m = re.search(r"[A-Z]", g.upper())
113
+ return m.group(0) if m else g.upper()
114
+
115
+
116
+ def parse_letter(text):
117
+ m = re.findall(r"[Aa]nswer\s*[:\-]?\s*([A-Za-z])", text)
118
+ if m: return m[-1].upper()
119
+ m = re.findall(r"\b([A-J])\b", text)
120
+ return m[-1].upper() if m else ""
121
+
122
+
123
+ def run_arm(model, tok, rows, tail, label):
124
+ is_proto = (label == "protocol")
125
+ correct = 0; total_lr = 0; total_patho = 0; truncated = 0; recs = []
126
+ for i, r in enumerate(rows):
127
+ msgs = [{"role": "user", "content": build_prompt(r, tail, protocol=is_proto)}]
128
+ enc = tok.apply_chat_template(
129
+ [msgs], add_generation_prompt=True,
130
+ return_tensors="pt", return_dict=True, padding=True).to(model.device)
131
+ with torch.no_grad():
132
+ out = model.generate(**enc, max_new_tokens=2600,
133
+ do_sample=False, pad_token_id=tok.pad_token_id)
134
+ gen = out[:, enc["input_ids"].shape[1]:]
135
+ text = tok.batch_decode(gen, skip_special_tokens=True)[0]
136
+ pred, gold = parse_letter(text), gold_letter(r)
137
+ ok = bool(pred) and pred == gold
138
+ # did it run out of room before writing an answer line?
139
+ no_answer_line = ("nswer" not in text)
140
+ lr = len(_lr_re.findall(text or "")); pa = len(_patho_re.findall(text or ""))
141
+ correct += int(ok); total_lr += lr; total_patho += pa; truncated += int(no_answer_line)
142
+ recs.append({"id": r.get("id"), "pred": pred, "gold": gold, "correct": ok,
143
+ "lr_markers": lr, "patho_markers": pa, "no_answer_line": no_answer_line,
144
+ "text": text})
145
+ print(f" [{label}] {i+1}/{len(rows)} acc={100*correct/(i+1):.0f}% "
146
+ f"lr={total_lr} patho={total_patho} no_ans={truncated}", flush=True)
147
+ return {
148
+ "label": label, "n": len(rows),
149
+ "accuracy_pct": round(100 * correct / max(1, len(rows)), 1),
150
+ "total_lr_markers": total_lr,
151
+ "mean_lr_markers_per_answer": round(total_lr / max(1, len(rows)), 2),
152
+ "mean_pathognomonic_per_answer": round(total_patho / max(1, len(rows)), 2),
153
+ "answers_missing_answer_line": truncated,
154
+ }, recs
155
+
156
+
157
+ def main():
158
+ ap = argparse.ArgumentParser()
159
+ ap.add_argument("--limit", type=int, default=100)
160
+ args = ap.parse_args()
161
+
162
+ cands = glob.glob(f"{MEDX}/**/Text/**/test*.jsonl", recursive=True) + \
163
+ glob.glob(f"{MEDX}/**/test*.jsonl", recursive=True)
164
+ if not cands:
165
+ raise SystemExit(f"Could not find MedXpertQA Text test.jsonl under {MEDX}")
166
+ rows = [json.loads(l) for l in open(sorted(cands)[0]) if l.strip()][:args.limit]
167
+
168
+ OUTDIR.mkdir(parents=True, exist_ok=True)
169
+ tok = AutoTokenizer.from_pretrained(MODEL)
170
+ tok.padding_side = "left"
171
+ if tok.pad_token is None:
172
+ tok.pad_token = tok.eos_token
173
+ print(f"loading {MODEL} ...", flush=True)
174
+ model = AutoModelForCausalLM.from_pretrained(
175
+ MODEL, torch_dtype=torch.bfloat16, device_map="cuda").eval()
176
+
177
+ t0 = time.perf_counter()
178
+ summaries = {}
179
+ for label, tail in ARMS:
180
+ s, recs = run_arm(model, tok, rows, tail, label)
181
+ summaries[label] = s
182
+ (OUTDIR / f"{label}_records.jsonl").write_text(
183
+ "\n".join(json.dumps(x, ensure_ascii=False) for x in recs), encoding="utf-8")
184
+ mins = (time.perf_counter() - t0) / 60
185
+
186
+ out = {"model": MODEL, "n": len(rows), "minutes": round(mins, 1), **summaries}
187
+ (OUTDIR / "protocol_summary.json").write_text(json.dumps(out, indent=2))
188
+
189
+ base = summaries["neutral"]["accuracy_pct"]
190
+ proto = summaries["protocol"]["accuracy_pct"]
191
+ print("\n" + "=" * 70)
192
+ print("PROTOCOL PROBE -- BASE MODEL, 100 IDENTICAL QUESTIONS")
193
+ print("=" * 70)
194
+ print(f"{'arm':10}{'acc%':>8}{'vs neutral':>12}{'LR/ans':>9}{'patho/ans':>11}{'no-ans':>8}")
195
+ for label, _ in ARMS:
196
+ s = summaries[label]
197
+ d = "(control)" if label == "neutral" else f"{s['accuracy_pct']-base:+.1f} pts"
198
+ print(f"{s['label']:10}{s['accuracy_pct']:>8}{d:>12}{s['mean_lr_markers_per_answer']:>9}"
199
+ f"{s['mean_pathognomonic_per_answer']:>11}{s['answers_missing_answer_line']:>8}")
200
+ print("-" * 70)
201
+ dd = proto - base
202
+ if dd > 3:
203
+ print(f"=> PROTOCOL HELPS: {dd:+.1f} pts over natural reasoning. Worth testing on V15,")
204
+ print(" and worth reporting. Your structured protocol beat the plain prompt.")
205
+ elif dd >= -3:
206
+ print(f"=> PROTOCOL ~= neutral ({dd:+.1f} pts, within noise). Even a well-built protocol")
207
+ print(" doesn't beat the base's natural reasoning here.")
208
+ else:
209
+ print(f"=> PROTOCOL WORSE ({dd:+.1f} pts). Consistent with the prior pattern: structure hurts.")
210
+ if summaries["protocol"]["answers_missing_answer_line"] > 8:
211
+ print(f" NOTE: {summaries['protocol']['answers_missing_answer_line']}/100 protocol answers "
212
+ f"had no answer line (truncation) -- raise max_new_tokens and rerun if this is high.")
213
+ print(f"\nWrote -> {OUTDIR}/protocol_summary.json (+ per-arm records)")
214
+
215
+
216
+ if __name__ == "__main__":
217
+ main()
scripts/probe_twopronged_base.py ADDED
@@ -0,0 +1,214 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ TWO-PRONGED REASONING PROBE -- BASE MODEL, 100 IDENTICAL QUESTIONS
3
+ ====================================================================
4
+ Prof. Adnan's refinement, done properly:
5
+
6
+ WHY BASE, NOT A V-MODEL:
7
+ We are testing whether a REASONING PROMPT helps -- so we want the cleanest
8
+ substrate, with no fine-tuning effects tangled in. The untuned base isolates
9
+ the prompt's effect. (Also: this is exactly the controlled-contrast spirit of
10
+ the Matters Arising -- base model, offline, no retrieval.)
11
+
12
+ WHY 100 QUESTIONS (not 30):
13
+ 30 was too noisy (each Q = 3.3 pts). 100 halves the noise so a 3-4 pt effect
14
+ is real, not sampling wobble. Same 100 for every arm -> paired comparison.
15
+
16
+ THE KEY NEW IDEA -- "TWO-PRONGED" (augment, don't replace):
17
+ Every prior intervention (forced-Bayesian, gated-replace) SUPPRESSED the model's
18
+ natural chain-of-thought and accuracy DROPPED. The natural reasoning was carrying
19
+ the accuracy. So this arm KEEPS the natural reasoning and ADDS the clinical
20
+ scaffolding on top -- pathognomonic-features-first + note LRs where genuinely
21
+ known -- as a SUPPLEMENT, not a substitute.
22
+
23
+ FOUR ARMS, all on the same 100 questions:
24
+ 1. neutral : the base's own natural reasoning (CONTROL -- the number to beat)
25
+ 2. two_pronged : natural reasoning + pathognomonic/LR overlay (THE NEW IDEA)
26
+ 3. gated_replace : the replace-style gate (to prove augment beats replace)
27
+ 4. bayesian_force : force full Bayesian on everything (to confirm it still hurts)
28
+
29
+ THE VERDICT IS ACCURACY.
30
+ - two_pronged > neutral by a clear margin (~+3 pts on 100Q) => real, promptable gain.
31
+ Worth reporting, and a candidate reasoning policy.
32
+ - two_pronged ~= neutral => the base's natural reasoning can't be improved by
33
+ prompting; reasoning quality is intrinsic (this SUPPORTS the paper's thesis).
34
+ - two_pronged < neutral => augmenting still hurts; keep it plain.
35
+
36
+ Run (fire-and-forget; ~5-6h for 4 arms x 100 q at 1536 tok -> sbatch):
37
+ MODEL_DIR=$HOME/pentabrid/base_models/Qwen3.6-27B \
38
+ python3 ~/pentabrid/scripts/probe_twopronged_base.py --limit 100
39
+ """
40
+ import os, re, json, glob, time, argparse
41
+ from pathlib import Path
42
+ import torch
43
+ from transformers import AutoTokenizer, AutoModelForCausalLM
44
+
45
+ MODEL = os.environ["MODEL_DIR"]
46
+ MEDX = os.environ.get("MEDX_DIR", f"{os.environ['HOME']}/pentabrid/datasets/MedXpertQA")
47
+ OUTDIR = Path(os.environ.get("OUTDIR", f"{os.environ['HOME']}/pentabrid/runs/twopronged_probe"))
48
+
49
+ # ---- the prompts. Only the final instruction line differs. ----
50
+ NEUTRAL_TAIL = "Think step by step, then end with exactly: 'Answer: X' where X is the letter."
51
+
52
+ # THE NEW IDEA: keep natural reasoning, ADD the clinical overlay on top.
53
+ TWO_PRONGED_TAIL = (
54
+ "Work the case in your own natural clinical reasoning, and IN ADDITION do two things "
55
+ "as you go. First, explicitly flag any pathognomonic or highly specific feature that "
56
+ "points strongly to one diagnosis. Second, where a likelihood ratio for a key finding "
57
+ "is genuinely well established, note it briefly to support your reasoning -- but do NOT "
58
+ "invent likelihood-ratio values, and do NOT force Bayesian arithmetic where it doesn't "
59
+ "fit; if you don't know an LR, reason qualitatively. Let your normal step-by-step "
60
+ "reasoning drive the conclusion, with these as support. Then end with exactly: "
61
+ "'Answer: X' where X is the letter."
62
+ )
63
+
64
+ # The replace-style gate from the last probe (kept, to prove augment beats replace).
65
+ GATED_REPLACE_TAIL = (
66
+ "Reason like an expert clinician, in this order. STEP 1: Identify any pathognomonic or "
67
+ "highly specific features that point directly to one diagnosis; if present, commit to it "
68
+ "without likelihood-ratio calculation. STEP 2: Only if still uncertain, weigh discriminating "
69
+ "findings using established likelihood ratios only -- do not invent LR values. STEP 3: Rule "
70
+ "alternatives in/out with pertinent positives and negatives. Then end with exactly: "
71
+ "'Answer: X' where X is the letter."
72
+ )
73
+
74
+ # Force full Bayesian on everything (to confirm on the base that it still hurts).
75
+ BAYESIAN_FORCE_TAIL = (
76
+ "Reason using EXPLICIT Bayesian logic: state the pre-test probability of the leading "
77
+ "diagnoses, cite approximate likelihood ratios (LR+ / LR-) for the key findings, update "
78
+ "to a post-test probability, and rule alternatives in or out. Then end with exactly: "
79
+ "'Answer: X' where X is the letter."
80
+ )
81
+
82
+ ARMS = [
83
+ ("neutral", NEUTRAL_TAIL),
84
+ ("two_pronged", TWO_PRONGED_TAIL),
85
+ ("gated_replace", GATED_REPLACE_TAIL),
86
+ ("bayesian_force", BAYESIAN_FORCE_TAIL),
87
+ ]
88
+
89
+ LR_PATTERNS = [
90
+ r"likelihood ratio", r"\bLR[+\-]?\b", r"pre-?test", r"post-?test",
91
+ r"prior probability", r"posterior", r"\bbayes", r"pertinent (?:positive|negative)",
92
+ r"\bodds\b", r"sensitivity", r"specificity",
93
+ ]
94
+ _lr_re = re.compile("|".join(LR_PATTERNS), re.IGNORECASE)
95
+ PATHO_PATTERNS = [r"pathognomonic", r"highly specific", r"hallmark", r"classic(?:ally)?\b",
96
+ r"diagnostic of", r"characteristic of"]
97
+ _patho_re = re.compile("|".join(PATHO_PATTERNS), re.IGNORECASE)
98
+
99
+
100
+ def build_prompt(r, tail):
101
+ q = r.get("question", "")
102
+ opts = r.get("options")
103
+ lines = [q, ""]
104
+ if isinstance(opts, dict):
105
+ for k in sorted(opts): lines.append(f"{k}. {opts[k]}")
106
+ elif isinstance(opts, list):
107
+ for i, o in enumerate(opts): lines.append(f"{chr(65+i)}. {o}")
108
+ lines += ["", tail]
109
+ return "\n".join(lines)
110
+
111
+
112
+ def gold_letter(r):
113
+ g = str(r.get("label", r.get("answer", ""))).strip()
114
+ m = re.search(r"[A-Z]", g.upper())
115
+ return m.group(0) if m else g.upper()
116
+
117
+
118
+ def parse_letter(text):
119
+ m = re.findall(r"[Aa]nswer\s*[:\-]?\s*([A-Za-z])", text)
120
+ if m: return m[-1].upper()
121
+ m = re.findall(r"\b([A-J])\b", text)
122
+ return m[-1].upper() if m else ""
123
+
124
+
125
+ def run_arm(model, tok, rows, tail, label):
126
+ correct = 0; total_lr = 0; total_patho = 0; with_lr = 0; recs = []
127
+ for i, r in enumerate(rows):
128
+ msgs = [{"role": "user", "content": build_prompt(r, tail)}]
129
+ enc = tok.apply_chat_template(
130
+ [msgs], add_generation_prompt=True,
131
+ return_tensors="pt", return_dict=True, padding=True).to(model.device)
132
+ with torch.no_grad():
133
+ out = model.generate(**enc, max_new_tokens=1536,
134
+ do_sample=False, pad_token_id=tok.pad_token_id)
135
+ gen = out[:, enc["input_ids"].shape[1]:]
136
+ text = tok.batch_decode(gen, skip_special_tokens=True)[0]
137
+ pred, gold = parse_letter(text), gold_letter(r)
138
+ ok = bool(pred) and pred == gold
139
+ lr = len(_lr_re.findall(text or "")); pa = len(_patho_re.findall(text or ""))
140
+ correct += int(ok); total_lr += lr; total_patho += pa; with_lr += int(lr > 0)
141
+ recs.append({"id": r.get("id"), "pred": pred, "gold": gold, "correct": ok,
142
+ "lr_markers": lr, "patho_markers": pa, "text": text})
143
+ print(f" [{label}] {i+1}/{len(rows)} acc={100*correct/(i+1):.0f}% "
144
+ f"lr={total_lr} patho={total_patho}", flush=True)
145
+ return {
146
+ "label": label, "n": len(rows),
147
+ "accuracy_pct": round(100 * correct / max(1, len(rows)), 1),
148
+ "answers_with_any_lr_marker": with_lr,
149
+ "total_lr_markers": total_lr,
150
+ "mean_lr_markers_per_answer": round(total_lr / max(1, len(rows)), 2),
151
+ "total_pathognomonic_markers": total_patho,
152
+ "mean_pathognomonic_per_answer": round(total_patho / max(1, len(rows)), 2),
153
+ }, recs
154
+
155
+
156
+ def main():
157
+ ap = argparse.ArgumentParser()
158
+ ap.add_argument("--limit", type=int, default=100, help="questions (same set for all arms)")
159
+ args = ap.parse_args()
160
+
161
+ cands = glob.glob(f"{MEDX}/**/Text/**/test*.jsonl", recursive=True) + \
162
+ glob.glob(f"{MEDX}/**/test*.jsonl", recursive=True)
163
+ if not cands:
164
+ raise SystemExit(f"Could not find MedXpertQA Text test.jsonl under {MEDX}")
165
+ rows = [json.loads(l) for l in open(sorted(cands)[0]) if l.strip()][:args.limit]
166
+
167
+ OUTDIR.mkdir(parents=True, exist_ok=True)
168
+ tok = AutoTokenizer.from_pretrained(MODEL)
169
+ tok.padding_side = "left"
170
+ if tok.pad_token is None:
171
+ tok.pad_token = tok.eos_token
172
+ print(f"loading {MODEL} ...", flush=True)
173
+ model = AutoModelForCausalLM.from_pretrained(
174
+ MODEL, torch_dtype=torch.bfloat16, device_map="cuda").eval()
175
+
176
+ t0 = time.perf_counter()
177
+ summaries = {}
178
+ for label, tail in ARMS:
179
+ s, recs = run_arm(model, tok, rows, tail, label)
180
+ summaries[label] = s
181
+ (OUTDIR / f"{label}_records.jsonl").write_text(
182
+ "\n".join(json.dumps(x, ensure_ascii=False) for x in recs), encoding="utf-8")
183
+ mins = (time.perf_counter() - t0) / 60
184
+
185
+ out = {"model": MODEL, "n": len(rows), "minutes": round(mins, 1), **summaries}
186
+ (OUTDIR / "twopronged_summary.json").write_text(json.dumps(out, indent=2))
187
+
188
+ base = summaries["neutral"]["accuracy_pct"]
189
+ print("\n" + "=" * 70)
190
+ print("TWO-PRONGED REASONING PROBE -- BASE MODEL, 100 IDENTICAL QUESTIONS")
191
+ print("=" * 70)
192
+ print(f"{'arm':16}{'acc%':>8}{'vs neutral':>12}{'LR/ans':>9}{'patho/ans':>12}")
193
+ for label, _ in ARMS:
194
+ s = summaries[label]
195
+ d = s["accuracy_pct"] - base
196
+ dstr = "(control)" if label == "neutral" else f"{d:+.1f} pts"
197
+ print(f"{s['label']:16}{s['accuracy_pct']:>8}{dstr:>12}"
198
+ f"{s['mean_lr_markers_per_answer']:>9}{s['mean_pathognomonic_per_answer']:>12}")
199
+ print("-" * 70)
200
+ tp = summaries["two_pronged"]["accuracy_pct"] - base
201
+ if tp > 3:
202
+ print(f"=> TWO-PRONGED helps: {tp:+.1f} pts over the base's natural reasoning.")
203
+ print(" A promptable reasoning gain. Worth reporting + a candidate policy.")
204
+ elif tp >= -3:
205
+ print(f"=> TWO-PRONGED ~= neutral ({tp:+.1f} pts, within noise on 100Q).")
206
+ print(" The base's natural reasoning can't be improved by prompting here --")
207
+ print(" consistent with the paper's thesis that reasoning quality is intrinsic.")
208
+ else:
209
+ print(f"=> TWO-PRONGED WORSE ({tp:+.1f} pts). Even augmenting hurts; keep it plain.")
210
+ print(f"\nWrote -> {OUTDIR}/twopronged_summary.json (+ per-arm records)")
211
+
212
+
213
+ if __name__ == "__main__":
214
+ main()
scripts/train_v14.py ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ PENTABRID V14 — LoRA TRAINER (27B, attention-only, ZeRO-2)
4
+ ==========================================================
5
+ Locked config: LoRA r16 / alpha16, attention-only, 1 epoch, LR 1.5e-5 cosine +
6
+ 3% warmup, MAX_SEQ_LEN 8192, bf16, DeepSpeed ZeRO-2 (NOT ZeRO-3: no NVLink on
7
+ these A100s). Loss is masked to the answer only (the prompt is not trained on).
8
+
9
+ ** SMOKE FIRST ** Launch once with SMOKE=1 -> trains ~20 steps on 64 rows to
10
+ prove it loads, fits in memory, and steps without crashing. Only then do the full
11
+ run. This is the single riskiest step (future transformers/PEFT API + Qwen3.6
12
+ chat template), so we validate cheaply before committing hours.
13
+
14
+ Three things to VERIFY on the smoke (Claude will check the smoke log with you):
15
+ 1. target_modules names are right for Qwen3.6 (q_proj/k_proj/v_proj/o_proj).
16
+ 2. the chat template doesn't double-wrap the <think> tags already in `output`.
17
+ 3. no CUDA OOM at seq 8192 (if OOM: drop MAXLEN to 6144, or set LOAD_4BIT=1).
18
+
19
+ USAGE (via train_v14.sbatch; do not run by hand on the login node):
20
+ SMOKE=1 torchrun --standalone --nproc_per_node=2 train_v14.py # smoke
21
+ torchrun --standalone --nproc_per_node=2 train_v14.py # full
22
+ """
23
+ import os
24
+ import torch
25
+ from transformers import (AutoModelForCausalLM, AutoTokenizer,
26
+ TrainingArguments, Trainer)
27
+ from peft import LoraConfig, get_peft_model
28
+ from datasets import load_dataset
29
+
30
+ MODEL_DIR = os.environ.get("MODEL_DIR", "/home/adnanagha/pentabrid/base_models/Qwen3.6-27B")
31
+ DATA = os.environ.get("DATA", "/home/adnanagha/pentabrid/scripts/v14_train_final.jsonl")
32
+ OUT = os.environ.get("OUT", "/home/adnanagha/pentabrid/runs/V14_lora")
33
+ MAXLEN = int(os.environ.get("MAXLEN", "8192"))
34
+ SMOKE = os.environ.get("SMOKE", "") not in ("", "0", "false")
35
+ RESUME = bool(os.environ.get("RESUME"))
36
+ if os.path.isdir(OUT) and os.listdir(OUT) and not RESUME:
37
+ raise SystemExit("REFUSING to overwrite non-empty OUT dir: " + OUT + " (use a new OUT=... or set RESUME=1)")
38
+
39
+ # DeepSpeed ZeRO-2 (full frozen base kept on each GPU; only optimizer/grads sharded)
40
+ DS_CONFIG = {
41
+ "bf16": {"enabled": True},
42
+ "zero_optimization": {
43
+ "stage": 2,
44
+ "overlap_comm": True,
45
+ "contiguous_gradients": True,
46
+ "reduce_bucket_size": 2e8,
47
+ "allgather_bucket_size": 2e8,
48
+ },
49
+ "gradient_accumulation_steps": "auto",
50
+ "train_micro_batch_size_per_gpu": "auto",
51
+ "gradient_clipping": "auto",
52
+ }
53
+
54
+ tok = AutoTokenizer.from_pretrained(MODEL_DIR)
55
+ if tok.pad_token is None:
56
+ tok.pad_token = tok.eos_token
57
+
58
+
59
+ def _ids(out):
60
+ """Return a plain list[int] of token ids from apply_chat_template, regardless
61
+ of whether this transformers version returns a list, a tensor, or an Encoding/
62
+ BatchEncoding (the latter triggers an Arrow OverflowError if passed through)."""
63
+ if hasattr(out, "input_ids"): # BatchEncoding / Encoding
64
+ out = out.input_ids
65
+ if hasattr(out, "ids"): # tokenizers.Encoding
66
+ out = out.ids
67
+ if hasattr(out, "tolist"): # tensor / numpy
68
+ out = out.tolist()
69
+ if out and isinstance(out[0], list): # nested [[...]] -> first row
70
+ out = out[0]
71
+ return [int(t) for t in out]
72
+
73
+
74
+ def to_example(row):
75
+ """Tokenize one row; mask the prompt so loss falls only on the answer."""
76
+ user = row["instruction"] + (("\n\n" + row["input"]) if row.get("input") else "")
77
+ msgs = [{"role": "user", "content": user}]
78
+ prompt_ids = _ids(tok.apply_chat_template(msgs, add_generation_prompt=True, tokenize=True))
79
+ full_ids = _ids(tok.apply_chat_template(
80
+ msgs + [{"role": "assistant", "content": row["output"]}],
81
+ add_generation_prompt=False, tokenize=True))
82
+ input_ids = full_ids[:MAXLEN]
83
+ labels = list(input_ids)
84
+ for i in range(min(len(prompt_ids), len(labels))):
85
+ labels[i] = -100
86
+ return {"input_ids": input_ids, "labels": labels, "attention_mask": [1] * len(input_ids)}
87
+
88
+
89
+ ds = load_dataset("json", data_files=DATA, split="train")
90
+ if SMOKE:
91
+ ds = ds.select(range(min(64, len(ds))))
92
+ ds = ds.map(to_example, remove_columns=ds.column_names, desc="tokenizing")
93
+
94
+
95
+ def collate(batch):
96
+ m = max(len(b["input_ids"]) for b in batch)
97
+ pad = lambda s, v: s + [v] * (m - len(s))
98
+ return {
99
+ "input_ids": torch.tensor([pad(b["input_ids"], tok.pad_token_id) for b in batch]),
100
+ "labels": torch.tensor([pad(b["labels"], -100) for b in batch]),
101
+ "attention_mask": torch.tensor([pad(b["attention_mask"], 0) for b in batch]),
102
+ }
103
+
104
+
105
+ load_kwargs = dict(torch_dtype=torch.bfloat16)
106
+ if os.environ.get("LOAD_4BIT"):
107
+ from transformers import BitsAndBytesConfig
108
+ load_kwargs["quantization_config"] = BitsAndBytesConfig(
109
+ load_in_4bit=True, bnb_4bit_compute_dtype=torch.bfloat16, bnb_4bit_quant_type="nf4")
110
+
111
+ model = AutoModelForCausalLM.from_pretrained(MODEL_DIR, **load_kwargs)
112
+ model.config.use_cache = False
113
+ model.gradient_checkpointing_enable()
114
+ model.enable_input_require_grads() # required for PEFT + gradient checkpointing
115
+
116
+ lora = LoraConfig(
117
+ r=16, lora_alpha=int(os.environ.get("ALPHA", "16")), lora_dropout=0.0, bias="none", task_type="CAUSAL_LM",
118
+ target_modules=["q_proj", "k_proj", "v_proj", "o_proj"], # attention-only
119
+ )
120
+ model = get_peft_model(model, lora)
121
+ model.print_trainable_parameters()
122
+
123
+ args = TrainingArguments(
124
+ output_dir=OUT,
125
+ num_train_epochs=1,
126
+ max_steps=(20 if SMOKE else -1),
127
+ per_device_train_batch_size=1,
128
+ gradient_accumulation_steps=16,
129
+ learning_rate=1.5e-5,
130
+ lr_scheduler_type="cosine",
131
+ warmup_ratio=0.03,
132
+ bf16=True,
133
+ logging_steps=5,
134
+ save_strategy="steps",
135
+ save_steps=200,
136
+ save_total_limit=4,
137
+ eval_strategy="no",
138
+ report_to="none",
139
+ gradient_checkpointing=True,
140
+ deepspeed=DS_CONFIG,
141
+ )
142
+
143
+ trainer = Trainer(model=model, args=args, train_dataset=ds, data_collator=collate)
144
+ trainer.train(resume_from_checkpoint=RESUME)
145
+ trainer.save_model(OUT) # saves the LoRA adapter (not the full model)
146
+ tok.save_pretrained(OUT)
147
+ print(f"DONE -> LoRA adapter saved at {OUT}")
scripts/train_v14.sbatch ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ #SBATCH --job-name=v14_train
3
+ #SBATCH --partition=gpuq
4
+ #SBATCH --nodes=1
5
+ #SBATCH --gres=gpu:2
6
+ #SBATCH --time=2-00:00:00
7
+ #SBATCH --output=/home/adnanagha/pentabrid/runs/v14_train.log
8
+ # Single node, 2 GPUs (data-parallel + ZeRO-2). ~half a day for the full mix;
9
+ # 2-day walltime gives margin. If a node drops, resubmit with RESUME=1 (below).
10
+
11
+ module load cuda/12.6
12
+ export TORCH_CUDA_ARCH_LIST="8.0"
13
+ source /home/adnanagha/miniforge3/etc/profile.d/conda.sh
14
+ conda activate pentabrid
15
+ cd /home/adnanagha/pentabrid/scripts
16
+
17
+ export MODEL_DIR=/home/adnanagha/pentabrid/base_models/Qwen3.6-27B
18
+ export DATA=/home/adnanagha/pentabrid/scripts/v14_train_final.jsonl
19
+ export OUT=/home/adnanagha/pentabrid/runs/V14_lora
20
+
21
+ # --- toggles (uncomment as needed) ---
22
+ # export SMOKE=1 # 20-step smoke on 64 rows -> ALWAYS run this first
23
+ # export RESUME=1 # resume full run from newest checkpoint after a node drop
24
+ # export LOAD_4BIT=1 # only if the smoke hits CUDA OOM at seq 8192
25
+ # export MAXLEN=6144 # alternative OOM fix
26
+
27
+ # --- Triton kernel-cache fix (the .ptx FileNotFoundError) ---
28
+ # A shared cache makes the 2 GPUs race to compile/read the same kernel file.
29
+ # 1) Give this job a private cache dir...
30
+ export TRITON_CACHE_DIR=/tmp/triton_cache_${SLURM_JOB_ID}
31
+ mkdir -p "$TRITON_CACHE_DIR"
32
+ # 2) ...and pre-compile the kernels on ONE GPU first, so the file exists before
33
+ # the 2-GPU run ever looks for it (a few SMOKE steps, output discarded).
34
+ echo "[$(date)] pre-warming Triton kernels on 1 GPU ..."
35
+ SMOKE=1 CUDA_VISIBLE_DEVICES=0 python3 train_v14.py > /home/adnanagha/pentabrid/runs/v14_prewarm.log 2>&1 || true
36
+
37
+ echo "[$(date)] V14 train starting on $(hostname) (SMOKE=${SMOKE:-0})"
38
+ torchrun --standalone --nproc_per_node=2 train_v14.py
39
+ echo "[$(date)] V14 train finished (exit $?)"