"""rad-decider: answer one typed radiology workflow question in a single forward pass (no text generation). pip install "transformers>=5.18" peft torch python inference.py # runs the three card examples The model reads a STATE (order / DICOM header / history / report fields) and a QUESTION with lettered OPTIONS, and returns a probability for every option from the logits of the option letters at the answer slot. Probabilities are temperature-calibrated per trained question (calibration.json); custom questions use T = 1.0 (uncalibrated). """ from __future__ import annotations import json import os import torch from peft import PeftModel from transformers import AutoModelForCausalLM, AutoTokenizer BASE = "Qwen/Qwen3.5-0.8B" ADAPTER = os.environ.get("RAD_DECIDER", "Rology/rad-decider") # hub id or local folder HEADER = ("You are a decision model inside a teleradiology workflow. Read the state and answer the question with the letter of exactly " "one option.") LETTERS = [chr(ord("A") + i) for i in range(26)] def render(state: dict, instructions: str, options: list[tuple[str, str]]) -> str: """The exact training prompt (layout 'state_first'): fields as `key: value` lines, options lettered A, B, ... in the given order.""" lines = [f"{k}: {' '.join(str(v).split())}" for k, v in state.items() if v is not None and str(v).strip()] opts = [f"{LETTERS[i]}. {k}" + (f": {d}" if d else "") for i, (k, d) in enumerate(options)] return (f"{HEADER}\n\n### State\n" + "\n".join(lines) + f"\n\n### Question\n{instructions.strip()}\n\n### Options\n" + "\n".join(opts) + "\n\n### Answer\n") class RadDecider: def __init__(self, adapter: str = ADAPTER, device: str | None = None): self.device = device or ("cuda" if torch.cuda.is_available() else "cpu") self.tok = AutoTokenizer.from_pretrained(BASE) self.tok.padding_side = "left" base = AutoModelForCausalLM.from_pretrained(BASE, dtype=torch.bfloat16 if self.device == "cuda" else torch.float32) self.model = PeftModel.from_pretrained(base, adapter).to(self.device).eval() self.letter_ids = [self.tok.encode(x, add_special_tokens=False)[0] for x in LETTERS] cal = os.path.join(adapter, "calibration.json") if os.path.isdir(adapter) else None if cal is None: from huggingface_hub import hf_hub_download cal = hf_hub_download(adapter, "calibration.json") self.temperatures = json.load(open(cal))["temperatures"] @torch.no_grad() def ask(self, state: dict, question: dict, question_key: str | None = None) -> dict: """question = {"type": "noul"|"choice"|"score", "instructions": str, "options": [(key, definition), ...]} (noul: yes/no).""" options = [("yes", None), ("no", None)] if question["type"] == "noul" else list(question["options"]) enc = self.tok(render(state, question["instructions"], options), return_tensors="pt").to(self.device) pos = (enc["attention_mask"].long().cumsum(-1) - 1).clamp(min=0) logits = self.model(**enc, position_ids=pos, use_cache=False, logits_to_keep=1).logits[0, -1].float() t = float(self.temperatures.get(question_key, 1.0)) if question_key else 1.0 p = torch.softmax(logits[self.letter_ids[: len(options)]] / t, dim=-1).tolist() best = max(range(len(options)), key=lambda i: p[i]) return {"answer": options[best][0], "probabilities": {k: round(v, 4) for (k, _), v in zip(options, p)}, "calibrated": question_key in self.temperatures if question_key else False} EXAMPLES = [ ("dp4.contrast_mismatch", {"exam": "CT abdomen and pelvis without contrast", "ordered_side": "n/a", "contrast_given": "No", "sex": "F", "age_years": 54, "indication": "Right lower quadrant pain", "findings": "Following intravenous contrast, the liver enhances homogeneously. The appendix is normal.", "impression": "No acute abnormality."}, {"type": "noul", "instructions": "Does the report's description of contrast conflict with whether contrast was given?"}), ("dp4.laterality_mismatch", {"exam": "XR knee left", "ordered_side": "left", "dicom_laterality": "L", "sex": "M", "age_years": 61, "indication": "Knee pain", "findings": "Moderate medial joint space narrowing of the right knee. No fracture.", "impression": "Degenerative change of the right knee."}, {"type": "noul", "instructions": "Does the report describe a side that conflicts with the ordered side or the DICOM laterality? A normal comparison of " "the other side (for example 'the right knee is normal' on a left knee examination) is not a conflict."}), ("dp1.urgency", {"modality": "CT", "study_description": "CT HEAD WO CONTRAST", "body_part_examined": "HEAD", "ordered_procedure": "CT head without contrast", "reason_for_exam": "Sudden left-sided weakness and slurred speech, onset 40 minutes ago", "clinical_history": "Atrial fibrillation, not anticoagulated.", "patient_class": "Emergency", "order_priority": "STAT", "age_years": 72, "sex": "M"}, {"type": "score", "instructions": "How urgently should this study be read, based on clinical history, patient class and priority?", "options": [("routine", "Outpatient or follow-up, no acute concern"), ("urgent", "Acute symptoms, read within hours"), ("stat", "Emergency, read immediately"), ("critical_suspected", "History suggests a life-threatening finding (stroke, bleed, PE, dissection)")]}), ] if __name__ == "__main__": rd = RadDecider() for key, state, q in EXAMPLES: print(key, rd.ask(state, q, key))