Views
No views yet
1pip install git+https://github.com/huggingface/transformers.git@88d960937c81a32bfb63356a2e8ecf7999619681
2pip install protobuf
3pip install peft
4pip install sentencepiece
5pip install Pillow1from transformers import AutoModelForCausalLM, AutoProcessor, AutoConfig
2from peft import PeftConfig, PeftModel
3import torch
4import requests
5from PIL import Image
6
7# 1. Load PEFT adapter configuration to get the base model
8peft_config = PeftConfig.from_pretrained("StanfordAIMI/maira2-srrg-impression")
9base_model_name = peft_config.base_model_name_or_path
10
11# 2. Initialize device
12device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
13
14# 3. Load the model config and ensure parallelize is a dict to avoid NoneType iteration errors
15config = AutoConfig.from_pretrained(
16 base_model_name,
17 trust_remote_code=True
18)
19# config.parallelize = {}
20
21# 4. Load the base MAIRA-2 model with the patched config
22model = AutoModelForCausalLM.from_pretrained(
23 base_model_name,
24 config=config,
25 trust_remote_code=True
26)
27
28# 5. Attach the LoRA adapter
29model = PeftModel.from_pretrained(
30 model,
31 "StanfordAIMI/maira2-srrg-impression",
32 torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
33 device_map="auto"
34)
35model.eval().to(device)
36
37# 6. Initialize the vision-language processor
38global processor
39processor = AutoProcessor.from_pretrained(
40 base_model_name,
41 trust_remote_code=True
42)
43
44# 7. Helper to fetch example chest X-rays
45def get_sample_data():
46 urls = {
47 "frontal": "https://openi.nlm.nih.gov/imgs/512/145/145/CXR145_IM-0290-1001.png",
48 "lateral": "https://openi.nlm.nih.gov/imgs/512/145/145/CXR145_IM-0290-2001.png"
49 }
50 def _download(url):
51 response = requests.get(url, headers={"User-Agent": "MAIRA-2"}, stream=True)
52 return Image.open(response.raw).convert("RGB")
53 return {
54 "frontal": _download(urls["frontal"]), # we use frontal only
55 "indication": "Dyspnea.", # actual indication goes here or ""
56 "comparison": "None.", # actual comparison goes here or ""
57 "technique": "PA and lateral views of the chest.", # actual technique goes here or ""
58 }
59
60# 8. Run a non-grounded forward pass
61sample = get_sample_data()
62inputs = processor.format_and_preprocess_reporting_input(
63 current_frontal=sample["frontal"],
64 current_lateral=None,
65 prior_frontal=None,
66 indication=sample["indication"],
67 technique=sample["technique"],
68 comparison=sample["comparison"],
69 prior_report=None,
70 return_tensors="pt",
71 get_grounding=False
72).to(device)
73
74with torch.no_grad():
75 output_ids = model.generate(
76 **inputs,
77 max_new_tokens=300,
78 use_cache=True
79 )
80
81# 9. Decode and print impression
82prompt_len = inputs["input_ids"].shape[-1]
83decoded = processor.decode(output_ids[0][prompt_len:], skip_special_tokens=True).lstrip()
84prediction = processor.convert_output_to_plaintext_or_grounded_sequence(decoded)
85print("Generated Impression:\n", prediction)Generated Impression:
1. Large right pleural effusion with associated compressive atelectasis of the right lower lobe.
2. The left lung is clear.
3. No evidence of pneumothorax.
4. No signs of pulmonary edema.
5. Cardiac and mediastinal contours are normal.
6. No acute bony abnormalities.