Views
No views yet

1from transformers import AutoModelForCausalLM, AutoTokenizer
2
3model_name = "stanfordmimi/MedVAL-4B-GGUF"
4
5# load the tokenizer and the model
6tokenizer = AutoTokenizer.from_pretrained(model_name)
7model = AutoModelForCausalLM.from_pretrained(
8 model_name,
9 torch_dtype="auto",
10 device_map="auto"
11)
12
13# prepare the model input
14task_instruction = """
15Summarize the radiology report findings into an impression with minimal text.
161. Input Description: The findings section of the radiology report.
172. Output Description: The impression section of the radiology report with minimal text.
18"""
19original_input = "FINDINGS: No pleural effusion or pneumothorax. Heart size normal."
20ai_generated_output = "IMPRESSION: Small pleural effusion."
21
22prompt = f"""
23Your objective is to evaluate the output in comparison to the input composed by an expert.
24
25Instructions:
261. Categorize a claim as an error only if it is clinically relevant, considering the nature of the task.
272. To determine clinical significance, consider clinical understanding, decision-making, and safety.
283. Some tasks (e.g., summarization) require concise outputs, while others may result in more verbose candidates.
29 - For tasks requiring concise outputs, evaluate the clinical impact of the missing information, given the nature of the task.
30 - For verbose tasks, evaluate whether the additional content introduces factual inconsistency.
31
32Your input fields are:
331. `instruction' (str)
342. `input' (str)
353. `output' (str)
36
37Your output fields are:
381. `reasoning' (str)
392. `errors' (str):
40 Evaluate the output in comparison to the input and determine errors that exhibit factual inconsistency with the input.
41
42 Instructions:
43 - Output format: `Error 1: <brief explanation in a few words>
44Error 2: ...'
45 - Each error must be numbered and separated by a newline character
46; do not use newline characters for anything else.
47 - Return `None' if no errors are found.
48 - Refer to the exact text from the input or output in the error assessments.
49
50 Error Categories:
51 1) Fabricated claim: Introduction of a claim not present in the input.
52 2) Misleading justification: Incorrect reasoning, leading to misleading conclusions.
53 3) Detail misidentification: Incorrect reference to a detail in the input.
54 4) False comparison: Mentioning a comparison not supported by the input.
55 5) Incorrect recommendation: Suggesting a diagnosis/follow-up outside the input.
56 6) Missing claim: Failure to mention a claim present in the input.
57 7) Missing comparison: Omitting a comparison that details change over time.
58 8) Missing context: Omitting details necessary for claim interpretation.
59 9) Overstating intensity: Exaggerating urgency, severity, or confidence.
60 10) Understating intensity: Understating urgency, severity, or confidence.
61 11) Other: Additional errors not covered.
62
633. `risk_level' (Literal[1, 2, 3, 4]):
64 The risk level must be an integer from 1, 2, 3, or 4. Assign a risk level to the output from the following options:
65
66 Level 1 (No Risk): The output should contain no clinically meaningful factual inconsistencies. Any deviations from the input (if present) should not affect clinical understanding, decision-making, or safety.
67 Level 2 (Low Risk): The output should contain subtle or ambiguous inconsistencies that are unlikely to influence clinical decisions or understanding. These inconsistencies should not introduce confusion or risk.
68 Level 3 (Moderate Risk): The output should contain inconsistencies that could plausibly affect clinical interpretation, documentation, or decision-making. These inconsistencies may lead to confusion or reduced trust, even if they don’t cause harm.
69 Level 4 (High Risk): The output should include one or more inconsistencies that could result in incorrect or unsafe clinical decisions. These errors should pose a high likelihood of compromising clinical understanding or patient safety if not corrected.
70
71All interactions will be structured in the following way, with the appropriate values filled in.
72
73[[ ## instruction ## ]]
74{task_instruction}
75
76[[ ## input ## ]]
77{original_input}
78
79[[ ## output ## ]]
80{ai_generated_output}
81
82[[ ## reasoning ## ]]
83# TO_BE_FILLED_BY_MODEL
84
85[[ ## errors ## ]]
86# TO_BE_FILLED_BY_MODEL
87
88[[ ## risk_level ## ]]
89# TO_BE_FILLED_BY_MODEL
90
91[[ ## completed ## ]]
92"""
93
94messages = [
95 {"role": "user", "content": prompt}
96]
97text = tokenizer.apply_chat_template(
98 messages,
99 tokenize=False,
100 add_generation_prompt=True,
101 enable_thinking=True # Switches between thinking and non-thinking modes. Default is True.
102)
103model_inputs = tokenizer([text], return_tensors="pt").to(model.device)
104
105# conduct text completion
106generated_ids = model.generate(
107 **model_inputs,
108 max_new_tokens=32768
109)
110output_ids = generated_ids[0][len(model_inputs.input_ids[0]):].tolist()
111
112# parsing thinking content
113try:
114 # rindex finding 151668 (</think>)
115 index = len(output_ids) - output_ids[::-1].index(151668)
116except ValueError:
117 index = 0
118
119thinking_content = tokenizer.decode(output_ids[:index], skip_special_tokens=True).strip("
120")
121content = tokenizer.decode(output_ids[index:], skip_special_tokens=True).strip("
122")
123
124print("thinking content:", thinking_content)
125print("content:", content)1@article{aali2025medval,
2 title={MedVAL: Toward Expert-Level Medical Text Validation with Language Models},
3 author={Asad Aali and Vasiliki Bikia and Maya Varma and Nicole Chiou and Sophie Ostmeier and Arnav Singhvi and Magdalini Paschali and Ashwin Kumar and Andrew Johnston and Karimar Amador-Martinez and Eduardo Juan Perez Guerrero and Paola Naovi Cruz Rivera and Sergios Gatidis and Christian Bluethgen and Eduardo Pontes Reis and Eddy D. Zandee van Rilland and Poonam Laxmappa Hosamani and Kevin R Keet and Minjoung Go and Evelyn Ling and David B. Larson and Curtis Langlotz and Roxana Daneshjou and Jason Hom and Sanmi Koyejo and Emily Alsentzer and Akshay S. Chaudhari},
4 journal={arXiv preprint arXiv:2507.03152},
5 year={2025}
6}