from transformers import AutoModelForCausalLM, AutoTokenizer model_name = "stanfordmimi/MedVAL-4B" # load the tokenizer and the modeltokenizer = AutoTokenizer.from_pretrained(model_name)model = AutoModelForCausalLM.from_pretrained( model_name, torch_dtype="auto", device_map="auto") # prepare the model inputtask_instruction = """Summarize the radiology report findings into an impression with minimal text.1. Input Description: The findings section of the radiology report.2. Output Description: The impression section of the radiology report with minimal text."""original_input = "FINDINGS: No pleural effusion or pneumothorax. Heart size normal."ai_generated_output = "IMPRESSION: Small pleural effusion." prompt = f"""Your objective is to evaluate the output in comparison to the input composed by an expert. Instructions:1. Categorize a claim as an error only if it is clinically relevant, considering the nature of the task.2. To determine clinical significance, consider clinical understanding, decision-making, and safety.3. Some tasks (e.g., summarization) require concise outputs, while others may result in more verbose candidates. - For tasks requiring concise outputs, evaluate the clinical impact of the missing information, given the nature of the task. - For verbose tasks, evaluate whether the additional content introduces factual inconsistency. Your input fields are:1. `instruction' (str)2. `input' (str)3. `output' (str) Your output fields are:1. `reasoning' (str)2. `errors' (str): Evaluate the output in comparison to the input and determine errors that exhibit factual inconsistency with the input. Instructions: - Output format: `Error 1: <brief explanation in a few words>Error 2: ...' - Each error must be numbered and separated by a newline character ; do not use newline characters for anything else. - Return `None' if no errors are found. - Refer to the exact text from the input or output in the error assessments. Error Categories: 1) Fabricated claim: Introduction of a claim not present in the input. 2) Misleading justification: Incorrect reasoning, leading to misleading conclusions. 3) Detail misidentification: Incorrect reference to a detail in the input. 4) False comparison: Mentioning a comparison not supported by the input. 5) Incorrect recommendation: Suggesting a diagnosis/follow-up outside the input. 6) Missing claim: Failure to mention a claim present in the input. 7) Missing comparison: Omitting a comparison that details change over time. 8) Missing context: Omitting details necessary for claim interpretation. 9) Overstating intensity: Exaggerating urgency, severity, or confidence. 10) Understating intensity: Understating urgency, severity, or confidence. 11) Other: Additional errors not covered. 3. `risk_level' (Literal[1, 2, 3, 4]): The risk level must be an integer from 1, 2, 3, or 4. Assign a risk level to the output from the following options: 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. 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. 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. 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. All interactions will be structured in the following way, with the appropriate values filled in. [[ ## instruction ## ]]{task_instruction} [[ ## input ## ]]{original_input} [[ ## output ## ]]{ai_generated_output} [[ ## reasoning ## ]]# TO_BE_FILLED_BY_MODEL [[ ## errors ## ]]# TO_BE_FILLED_BY_MODEL [[ ## risk_level ## ]]# TO_BE_FILLED_BY_MODEL [[ ## completed ## ]]""" messages = [ {"role": "user", "content": prompt}]text = tokenizer.apply_chat_template( messages, tokenize=False, add_generation_prompt=True, enable_thinking=True # Switches between thinking and non-thinking modes. Default is True.)model_inputs = tokenizer([text], return_tensors="pt").to(model.device) # conduct text completiongenerated_ids = model.generate( **model_inputs, max_new_tokens=32768)output_ids = generated_ids[0][len(model_inputs.input_ids[0]):].tolist() # parsing thinking contenttry: # rindex finding 151668 (</think>) index = len(output_ids) - output_ids[::-1].index(151668)except ValueError: index = 0 thinking_content = tokenizer.decode(output_ids[:index], skip_special_tokens=True).strip("")content = tokenizer.decode(output_ids[index:], skip_special_tokens=True).strip("") print("thinking content:", thinking_content)print("content:", content)