Master-Shi commited on
Commit
3607dd8
·
verified ·
1 Parent(s): 1345c65

Add files using upload-large-folder tool

Browse files
Files changed (20) hide show
  1. benchmarks/VGMED/image_folder/SAMed2D_v1/endoscopy/images/endoscopy_00--kvasir_seg--cju5ymyd8mmdc0801ry3by1xr--2d_none.png +3 -0
  2. 之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/HuatuoGPT-Vision/results_attnbias/HuatuoGPT-Vision-7B/sam_none/HuatuoGPT-Vision-7B_medical_multimodel_evaluation_data_none.json +0 -0
  3. 之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/HuatuoGPT-Vision/results_attnbias/HuatuoGPT-Vision-7B/sam_none/HuatuoGPT-Vision-7B_medical_multimodel_evaluation_data_none_result.json +22 -0
  4. 之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/HuatuoGPT-Vision/results_attnbias/HuatuoGPT-Vision-7B/sam_none/_snapshot/eval_attnbias_sam.py +1192 -0
  5. 之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/HuatuoGPT-Vision/results_attnbias/HuatuoGPT-Vision-7B/sam_none/_snapshot/run_all_attnbias_sam.sh +28 -0
  6. 之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/HuatuoGPT-Vision/results_attnbias/HuatuoGPT-Vision-7B/sam_none/_snapshot/run_eval.sh +14 -0
  7. 之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/HuatuoGPT-Vision/results_attnbias/HuatuoGPT-Vision-7B/sam_none/_snapshot/run_eval_attnbias_sam_both.sh +40 -0
  8. 之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/HuatuoGPT-Vision/results_attnbias/HuatuoGPT-Vision-7B/sam_none/_snapshot/run_eval_attnbias_sam_none.sh +40 -0
  9. 之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/HuatuoGPT-Vision/results_attnbias/HuatuoGPT-Vision-7B/sam_none/_snapshot/run_eval_attnbias_sam_text.sh +40 -0
  10. 之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/HuatuoGPT-Vision/results_attnbias/HuatuoGPT-Vision-7B/sam_none/_snapshot/run_eval_attnbias_sam_vis.sh +40 -0
  11. 之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/HuatuoGPT-Vision/results_attnbias/HuatuoGPT-Vision-7B/sam_text/HuatuoGPT-Vision-7B_medical_multimodel_evaluation_data_text.json +0 -0
  12. 之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/HuatuoGPT-Vision/results_attnbias/HuatuoGPT-Vision-7B/sam_text/HuatuoGPT-Vision-7B_medical_multimodel_evaluation_data_text_result.json +22 -0
  13. 之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/HuatuoGPT-Vision/results_attnbias/HuatuoGPT-Vision-7B/sam_text/_snapshot/eval_attnbias_sam.py +1192 -0
  14. 之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/HuatuoGPT-Vision/results_attnbias/HuatuoGPT-Vision-7B/sam_text/_snapshot/run_all_attnbias_sam.sh +28 -0
  15. 之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/HuatuoGPT-Vision/results_attnbias/HuatuoGPT-Vision-7B/sam_text/_snapshot/run_eval.sh +14 -0
  16. 之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/HuatuoGPT-Vision/results_attnbias/HuatuoGPT-Vision-7B/sam_text/_snapshot/run_eval_attnbias_sam_both.sh +40 -0
  17. 之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/HuatuoGPT-Vision/results_attnbias/HuatuoGPT-Vision-7B/sam_text/_snapshot/run_eval_attnbias_sam_none.sh +40 -0
  18. 之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/HuatuoGPT-Vision/results_attnbias/HuatuoGPT-Vision-7B/sam_text/_snapshot/run_eval_attnbias_sam_text.sh +40 -0
  19. 之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/HuatuoGPT-Vision/results_attnbias/HuatuoGPT-Vision-7B/sam_text/_snapshot/run_eval_attnbias_sam_vis.sh +40 -0
  20. 之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/HuatuoGPT-Vision/results_attnbias/HuatuoGPT-Vision-7B/sam_vis/_snapshot/run_eval_attnbias_sam_none.sh +40 -0
benchmarks/VGMED/image_folder/SAMed2D_v1/endoscopy/images/endoscopy_00--kvasir_seg--cju5ymyd8mmdc0801ry3by1xr--2d_none.png ADDED

Git LFS Details

  • SHA256: b5506f424d906aad50fd7d4c9de1775302272ecb35ba8d2eb065f1ac570dbfcf
  • Pointer size: 131 Bytes
  • Size of remote file: 408 kB
之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/HuatuoGPT-Vision/results_attnbias/HuatuoGPT-Vision-7B/sam_none/HuatuoGPT-Vision-7B_medical_multimodel_evaluation_data_none.json ADDED
The diff for this file is too large to render. See raw diff
 
之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/HuatuoGPT-Vision/results_attnbias/HuatuoGPT-Vision-7B/sam_none/HuatuoGPT-Vision-7B_medical_multimodel_evaluation_data_none_result.json ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "OmniMedVQA": 0.7409205321826681,
3
+ "PMC-VQA_test": 0.546,
4
+ "PathVQA_test": 0.5779298036882807,
5
+ "VQA-RAD_test": 0.6175298804780877,
6
+ "SLAKE_test": 0.7548076923076923,
7
+ "MMMU_Medical_Validation": 0.503448275862069,
8
+ "The total score for multiple-choice questions": 0.6832581801364319,
9
+ "OmniMedVQA_MR (Mag-netic Resonance Imaging)": 0.725990099009901,
10
+ "OmniMedVQA_ultrasound": 0.7688330871491876,
11
+ "OmniMedVQA_OCT (Optical Coherence Tomography": 0.8666666666666667,
12
+ "OmniMedVQA_Dermoscopy": 0.714824120603015,
13
+ "OmniMedVQA_X-Ray": 0.8047105004906772,
14
+ "OmniMedVQA_CT(Computed Tomography)": 0.6569563033651431,
15
+ "OmniMedVQA_Fundus Photography": 0.8178913738019169,
16
+ "OmniMedVQA_Microscopy Images": 0.7760989010989011,
17
+ "MMMU_Medical_Validation_validation_Public_Health": 0.43333333333333335,
18
+ "MMMU_Medical_Validation_validation_Pharmacy": 0.5555555555555556,
19
+ "MMMU_Medical_Validation_validation_Basic_Medical_Science": 0.5714285714285714,
20
+ "MMMU_Medical_Validation_validation_Clinical_Medicine": 0.6333333333333333,
21
+ "MMMU_Medical_Validation_validation_Diagnostics_and_Laboratory_Medicine": 0.3333333333333333
22
+ }
之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/HuatuoGPT-Vision/results_attnbias/HuatuoGPT-Vision-7B/sam_none/_snapshot/eval_attnbias_sam.py ADDED
@@ -0,0 +1,1192 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Code for finetune_huatuo"""
2
+
3
+ import os
4
+ import re
5
+ import copy
6
+ import json
7
+ import torch
8
+ import logging
9
+ import argparse
10
+ from transformers.generation.utils import LogitsProcessorList
11
+ from transformers.generation.logits_process import LogitsProcessor
12
+ import sys
13
+ import ast
14
+
15
+ from tqdm import tqdm
16
+ import torch.distributed as dist
17
+ from torch.utils.data import Dataset, DataLoader
18
+ from accelerate import Accelerator, DeepSpeedPlugin
19
+ from transformers import set_seed
20
+ import datasets
21
+ import shutil
22
+ import json
23
+ import random
24
+ from scorer import score_mix_llava
25
+ from cli import HuatuoChatbot
26
+
27
+
28
+ from transformers import AutoModelForCausalLM, AutoTokenizer, AutoModel, AutoModelWithLMHead
29
+ os.umask(0)
30
+
31
+
32
+ logger = logging.getLogger(__name__)
33
+ logging.basicConfig(level='INFO')
34
+
35
+ # Additional imports for attention intervention
36
+ import gc
37
+ import math
38
+ import types
39
+ import numpy as np
40
+ import torch.nn.functional as F
41
+ from PIL import Image
42
+
43
+ import matplotlib
44
+ matplotlib.use("Agg") # non-interactive backend: avoids X11 display / forwarding prompts on remote sessions
45
+
46
+
47
+ # ══════════════════════════════════════════════════════════════════════════════
48
+ # Constants
49
+ # ══════════════════════════════════════════════════════════════════════════════
50
+
51
+ HUATUO_NUM_IMG_TOKENS = 576
52
+ HUATUO_PATCHES = 24
53
+
54
+
55
+ _sci_nlp = None
56
+
57
+ def _get_sci_nlp():
58
+ global _sci_nlp
59
+ if _sci_nlp is None:
60
+ try:
61
+ import spacy
62
+ _sci_nlp = spacy.load("en_core_sci_sm")
63
+ print("[scispaCy] en_core_sci_sm loaded")
64
+ except Exception as e:
65
+ print(f"[scispaCy] load failed ({e}), falling back to rule filter.")
66
+ _sci_nlp = None
67
+ return _sci_nlp
68
+
69
+
70
+ _PAREN_RE = re.compile(r"\([^)]*\)")
71
+
72
+
73
+ def _strip_parens(text: str) -> str:
74
+ return re.sub(r"\s{2,}", " ", _PAREN_RE.sub("", text)).strip()
75
+
76
+
77
+ def _get_medical_entities(text: str) -> set:
78
+ nlp = _get_sci_nlp()
79
+ if nlp is None:
80
+ return set()
81
+ doc = nlp(text)
82
+ return {ent.text.lower().strip() for ent in doc.ents if len(ent.text.strip()) >= 2}
83
+
84
+
85
+ # ══════════════════════════════════════════════════════════════════════════════
86
+ # TestDataset
87
+
88
+ class TestDataset(torch.utils.data.Dataset):
89
+ def __init__(self, config, data_path):
90
+ self.config = config
91
+ self.dataset = {}
92
+ with open(data_path) as f:
93
+ self.dataset = json.load(f)
94
+ self.datas = []
95
+
96
+ test_id = 1
97
+ for da in self.dataset:
98
+ da['query'] = self.llava_prompt(da)
99
+ da['test_id'] = test_id
100
+ test_id += 1
101
+ self.datas.append(da)
102
+
103
+ def mmmu_prompt(self,da):
104
+ self.query_prompt = "Please answer the multiple-choice questions below.\n{}\n{}"
105
+ opt_title = ['A','B','C','D','E','F','G']
106
+ if isinstance(da['options'],str):
107
+ da['options'] = ast.literal_eval(da['options'])
108
+ option_str = '\n'.join(f'{opt}. {ops}' for opt,ops in zip(opt_title,da['options']))
109
+ return self.query_prompt.format(da['question'],option_str)
110
+
111
+ def OmniMedVQA_prompt(self,entity):
112
+ q_str = entity['question'] + f'Here are {len(entity["options"])} candidate answers:' + str(entity["options"])+' Only return what you think is the correct answer from the candidate answers, do not return any other irrelevant text!'
113
+ return q_str
114
+
115
+ def llava_prompt(self,da):
116
+ self.query_prompt = "{}\n{}\nAnswer with the option's letter from the given choices directly."
117
+ opt_title = ['A','B','C','D','E','F','G','H','I','J','K']
118
+ if isinstance(da['options'],str):
119
+ da['options'] = ast.literal_eval(da['options'])
120
+ option_str = '\n'.join(f'{opt}. {ops}' for opt,ops in zip(opt_title,da['options']))
121
+ return self.query_prompt.format(da['question'],option_str)
122
+
123
+ def __getitem__(self, index):
124
+ da = self.datas[index]
125
+ return {
126
+ 'data': da,
127
+ 'query': da['query'],
128
+ 'image': da['image']
129
+ }
130
+
131
+ def __len__(self):
132
+ return len(self.datas)
133
+
134
+ def collate_fn(self, batch):
135
+ out_batch = {}
136
+ out_batch['query'] = [x['query'] for x in batch]
137
+ out_batch['data'] = [x['data'] for x in batch]
138
+ out_batch['image'] = [x['image'] for x in batch]
139
+ return out_batch
140
+
141
+
142
+ def get_response(inputs,outputs,tokenizer,num_return):
143
+ responses_list=[]
144
+ batch_return=[]
145
+ for i, output in enumerate(outputs):
146
+ input_len = len(inputs[0])
147
+ generated_output = output[input_len:]
148
+ batch_return.append(tokenizer.decode(generated_output, skip_special_tokens=True))
149
+ if i%num_return==num_return-1:
150
+ responses_list.append(batch_return)
151
+ batch_return=[]
152
+ return responses_list
153
+
154
+ def table_to_csv_string(table):
155
+ rows = [",".join(table.columns)]
156
+ for row in table.data:
157
+ rows.append(",".join(map(str, row)))
158
+ return "\n".join(rows)
159
+
160
+
161
+ # ══════════════════════════════════════════════════════════════════════════════
162
+ # Top-K layer selection
163
+ # ══════════════════════════════════════════════════════════════════════════════
164
+
165
+ def _load_mean_div(pt_path):
166
+ data = torch.load(pt_path, map_location="cpu", weights_only=False)
167
+ if isinstance(data, torch.Tensor):
168
+ arr = data.float().numpy()
169
+ return arr if arr.ndim == 1 else arr.mean(axis=0)
170
+ stacked = np.stack([np.array(x) for x in data], axis=0)
171
+ return stacked.mean(axis=0)
172
+
173
+
174
+ def load_top_layers(pt_path, topk, pt_path_random=None):
175
+ mean = _load_mean_div(pt_path)
176
+ if pt_path_random is not None:
177
+ rand = _load_mean_div(pt_path_random)
178
+ diff = mean - rand
179
+ idx = np.argsort(diff)[::-1][:topk]
180
+ layers = [int(i) for i in idx]
181
+ print(f"[top-layers/diff] top-{topk}: {layers}")
182
+ return layers
183
+ idx = np.argsort(mean)[::-1][:topk]
184
+ layers = [int(i) for i in idx]
185
+ print(f"[top-layers] top-{topk}: {layers}")
186
+ return layers
187
+
188
+
189
+ def _parse_layer_list(s):
190
+ if s is None:
191
+ return None
192
+ if isinstance(s, int):
193
+ return [s]
194
+ return [int(x.strip()) for x in str(s).split(',') if x.strip()]
195
+
196
+
197
+ # ══════════════════════════════════════════════════════════════════════════════
198
+ # Attention forward utilities (manual RoPE + attention with pre-softmax key bias)
199
+ # ══════════════════════════════════════════════════════════════════════════════
200
+
201
+ def _rotate_half(x):
202
+ x1 = x[..., : x.shape[-1] // 2]
203
+ x2 = x[..., x.shape[-1] // 2 :]
204
+ return torch.cat((-x2, x1), dim=-1)
205
+
206
+
207
+ def _apply_rotary_pos_emb_local(q, k, cos, sin, unsqueeze_dim=1):
208
+ cos = cos.unsqueeze(unsqueeze_dim)
209
+ sin = sin.unsqueeze(unsqueeze_dim)
210
+ q_embed = (q * cos) + (_rotate_half(q) * sin)
211
+ k_embed = (k * cos) + (_rotate_half(k) * sin)
212
+ return q_embed, k_embed
213
+
214
+
215
+ def _repeat_kv_local(hidden_states, n_rep):
216
+ if n_rep == 1:
217
+ return hidden_states
218
+ bsz, n_kv_heads, slen, head_dim = hidden_states.shape
219
+ hidden_states = hidden_states[:, :, None, :, :].expand(
220
+ bsz, n_kv_heads, n_rep, slen, head_dim
221
+ )
222
+ return hidden_states.reshape(bsz, n_kv_heads * n_rep, slen, head_dim)
223
+
224
+
225
+ def _patch_attn_forward_with_key_bias(
226
+ attn_module, key_positions, tag: str = "",
227
+ bias_vec_fn=None):
228
+ key_positions = sorted({int(p) for p in key_positions if p is not None and int(p) >= 0})
229
+ old_forward = attn_module.forward
230
+
231
+ def _new_forward(self, hidden_states, attention_mask=None, position_ids=None,
232
+ past_key_value=None, output_attentions=False, use_cache=False,
233
+ cache_position=None, position_embeddings=None, **kwargs):
234
+ bsz, q_len, _ = hidden_states.size()
235
+
236
+ num_heads = getattr(self, "num_heads",
237
+ getattr(self.config, "num_attention_heads", None))
238
+ num_kv_heads = getattr(self, "num_key_value_heads",
239
+ getattr(self.config, "num_key_value_heads", num_heads))
240
+ head_dim = getattr(self, "head_dim",
241
+ hidden_states.shape[-1] // num_heads)
242
+ num_kv_groups = getattr(self, "num_key_value_groups",
243
+ num_heads // num_kv_heads)
244
+
245
+ query_states = self.q_proj(hidden_states)
246
+ key_states = self.k_proj(hidden_states)
247
+ value_states = self.v_proj(hidden_states)
248
+
249
+ query_states = query_states.view(bsz, q_len, num_heads, head_dim).transpose(1, 2)
250
+ key_states = key_states.view(bsz, q_len, num_kv_heads, head_dim).transpose(1, 2)
251
+ value_states = value_states.view(bsz, q_len, num_kv_heads, head_dim).transpose(1, 2)
252
+
253
+ if position_embeddings is None:
254
+ if not hasattr(self, "rotary_emb"):
255
+ return old_forward(hidden_states, attention_mask=attention_mask,
256
+ position_ids=position_ids, past_key_value=past_key_value,
257
+ output_attentions=output_attentions, use_cache=use_cache,
258
+ cache_position=cache_position, **kwargs)
259
+ kv_seq_len = key_states.shape[-2]
260
+ if past_key_value is not None:
261
+ try:
262
+ kv_seq_len += past_key_value.get_usable_length(
263
+ kv_seq_len, getattr(self, "layer_idx", 0))
264
+ except Exception:
265
+ try:
266
+ kv_seq_len += past_key_value.get_seq_length(
267
+ getattr(self, "layer_idx", 0))
268
+ except Exception:
269
+ pass
270
+ try:
271
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
272
+ except TypeError:
273
+ cos, sin = self.rotary_emb(value_states, position_ids)
274
+ else:
275
+ cos, sin = position_embeddings
276
+
277
+ try:
278
+ from transformers.models.qwen2.modeling_qwen2 import apply_rotary_pos_emb
279
+ try:
280
+ query_states, key_states = apply_rotary_pos_emb(
281
+ query_states, key_states, cos, sin, position_ids)
282
+ except TypeError:
283
+ query_states, key_states = apply_rotary_pos_emb(
284
+ query_states, key_states, cos, sin)
285
+ except Exception:
286
+ if position_ids is not None and getattr(cos, "dim", lambda: 0)() == 2:
287
+ cos_sel = cos[position_ids].to(dtype=query_states.dtype)
288
+ sin_sel = sin[position_ids].to(dtype=query_states.dtype)
289
+ query_states, key_states = _apply_rotary_pos_emb_local(
290
+ query_states, key_states, cos_sel, sin_sel)
291
+ else:
292
+ query_states, key_states = _apply_rotary_pos_emb_local(
293
+ query_states, key_states, cos, sin)
294
+
295
+ if past_key_value is not None:
296
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
297
+ key_states, value_states = past_key_value.update(
298
+ key_states, value_states, getattr(self, "layer_idx", 0), cache_kwargs)
299
+
300
+ key_states = _repeat_kv_local(key_states, num_kv_groups)
301
+ value_states = _repeat_kv_local(value_states, num_kv_groups)
302
+
303
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) \
304
+ / math.sqrt(head_dim)
305
+
306
+ if attention_mask is not None:
307
+ if attention_mask.dim() == 4:
308
+ causal_mask = attention_mask[:, :, :, :key_states.shape[-2]]
309
+ attn_weights = attn_weights + causal_mask
310
+ else:
311
+ attn_weights = attn_weights + attention_mask
312
+
313
+ kv_len = attn_weights.shape[-1]
314
+ valid_keys = [p for p in key_positions if p < kv_len]
315
+
316
+ # apply fine-grained bias before softmax if bias_vec_fn provided
317
+ if bias_vec_fn is not None:
318
+ bv = bias_vec_fn(valid_keys, kv_len).to(device=attn_weights.device, dtype=attn_weights.dtype)
319
+ if not getattr(self, f"_bias_printed_{tag}", False):
320
+ nonzero_pos = bv.nonzero(as_tuple=True)[0].tolist()
321
+ print(f"[AttnBias-{tag}] layer={getattr(self,'layer_idx','?')} "
322
+ f"kv_len={kv_len} nonzero={len(nonzero_pos)} positions: "
323
+ + ", ".join(f"{p}:{bv[p].item():.2f}" for p in nonzero_pos[:20])
324
+ + (" ..." if len(nonzero_pos) > 20 else ""))
325
+ setattr(self, f"_bias_printed_{tag}", True)
326
+ attn_weights[:, :, -1:, :] = attn_weights[:, :, -1:, :] + bv.view(1, 1, 1, kv_len)
327
+ # if not getattr(self, f"_bias_vec_printed_{tag}", False):
328
+ # print(f"[AttnBiasVec-{tag}] layer={getattr(self,'layer_idx','?')} kv_len={kv_len}")
329
+ # setattr(self, f"_bias_vec_printed_{tag}", True)
330
+
331
+ attn_weights = F.softmax(attn_weights, dim=-1,
332
+ dtype=torch.float32).to(query_states.dtype)
333
+
334
+ attn_weights = F.dropout(attn_weights,
335
+ p=getattr(self, "attention_dropout", 0.0),
336
+ training=self.training)
337
+ attn_output = torch.matmul(attn_weights, value_states)
338
+
339
+ if attn_output.size() != (bsz, num_heads, q_len, head_dim):
340
+ raise ValueError(
341
+ f"attn_output should be {(bsz, num_heads, q_len, head_dim)}, "
342
+ f"but is {attn_output.size()}"
343
+ )
344
+
345
+ attn_output = attn_output.transpose(1, 2).contiguous()
346
+ attn_output = attn_output.reshape(bsz, q_len, num_heads * head_dim)
347
+ attn_output = self.o_proj(attn_output)
348
+
349
+ if not output_attentions:
350
+ attn_weights = None
351
+ return attn_output, attn_weights, past_key_value
352
+
353
+ attn_module.forward = types.MethodType(_new_forward, attn_module)
354
+ return old_forward
355
+
356
+
357
+ def _get_attn_layers(bot):
358
+ try:
359
+ return [layer.self_attn for layer in bot.model.model.layers]
360
+ except AttributeError:
361
+ return [m for n, m in bot.model.named_modules()
362
+ if n.endswith(".self_attn") and hasattr(m, "q_proj")]
363
+
364
+
365
+ # ══════════════════════════════════════════════════════════════════════════════
366
+ # Step A: Extract key text token positions and option token positions
367
+ # ══════════════════════════════════════════════════════════════════════════════
368
+
369
+ def _get_attentions(output):
370
+ att = getattr(output, "attentions", None)
371
+ if att is None and isinstance(output, dict):
372
+ att = output.get("attentions")
373
+ if att is None:
374
+ raise RuntimeError("Model did not return attentions. Make sure eager attention is forced.")
375
+ return att
376
+
377
+
378
+ def _decode_token(tokenizer, token_id):
379
+ try:
380
+ return tokenizer.decode([int(token_id)], skip_special_tokens=True).strip().lower().lstrip("▁").strip()
381
+ except Exception:
382
+ return ""
383
+
384
+
385
+ def extract_key_positions(bot, prompt, image, question=None, attn_layer_indices=None, need_keywords=True):
386
+ """
387
+ Run one eager attention forward pass and return:
388
+ top_text_positions : [list[int]] — global positions of scispaCy keyword tokens (wrapped in a list)
389
+ all_text_positions : list[int] — all text token positions in the question segment
390
+ option_positions : list[int] — token positions of A./B./C./D. options
391
+ img_start : int
392
+ seq_len : int
393
+ attentions : tuple — all layer attentions, reused by Step B
394
+
395
+ need_keywords=False skips the scispaCy entity extraction below (img_start/seq_len/
396
+ option_positions are still computed — every intervention mode needs those), for use
397
+ by the "none" mode where keywords are never consumed.
398
+ """
399
+ text = bot.input_moderation(prompt)
400
+ text = bot.insert_image_placeholder(text, 1)
401
+ conv = bot.get_conv_without_history(text)
402
+ input_ids = bot.preprocess(conv, return_tensors="pt").unsqueeze(0).to(bot.device)
403
+ image_tensors = (torch.stack(bot.get_image_tensors([image]))
404
+ .to(dtype=torch.bfloat16).to(bot.device))
405
+
406
+ with torch.no_grad():
407
+ output = bot.model(input_ids, images=image_tensors,
408
+ output_attentions=True, output_hidden_states=False,
409
+ return_dict=True, use_cache=False)
410
+ attentions = _get_attentions(output)
411
+
412
+ ids_cpu = input_ids[0].cpu()
413
+ img_pos_list = torch.where(ids_cpu == -200)[0]
414
+ if img_pos_list.numel() == 0:
415
+ raise ValueError("Image placeholder token (-200) not found.")
416
+ img_start = int(img_pos_list[0].item())
417
+ seq_len = attentions[0].shape[-1]
418
+ vis_end = img_start + HUATUO_NUM_IMG_TOKENS
419
+
420
+ # expand single -200 placeholder to 576 tokens to align with actual sequence length
421
+ prefix = ids_cpu[:img_start]
422
+ img_fill = torch.full((HUATUO_NUM_IMG_TOKENS,), -200, dtype=ids_cpu.dtype)
423
+ suffix = ids_cpu[img_start + 1:]
424
+ ids_cpu = torch.cat([prefix, img_fill, suffix], dim=0)
425
+
426
+ # ── locate option token positions ────────────────────────────────────────
427
+ option_positions = []
428
+ first_option_pos = None
429
+ tokenizer = bot.tokenizer
430
+ text_ids = ids_cpu[vis_end:].tolist()
431
+ option_letters = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k'}
432
+ i = 0
433
+ while i < len(text_ids):
434
+ w = _decode_token(tokenizer, text_ids[i])
435
+ w_stripped = w.strip()
436
+ is_option = False
437
+
438
+ # must be preceded by a newline to avoid false positives inside words
439
+ # use raw decode (skip_special_tokens=False) to preserve \n
440
+ prev_raw = tokenizer.decode([text_ids[i - 1]], skip_special_tokens=False) if i > 0 else ""
441
+ cur_raw = tokenizer.decode([text_ids[i]], skip_special_tokens=False)
442
+ preceded_by_newline = '\n' in prev_raw or '\n' in cur_raw
443
+
444
+ # case 1: token is exactly a single letter e.g. "a", then next token contains "."
445
+ if preceded_by_newline and w_stripped.lower() in option_letters:
446
+ if i + 1 < len(text_ids) and '.' in _decode_token(tokenizer, text_ids[i + 1]):
447
+ is_option = True
448
+
449
+ # case 2: token is "a." or "A." (letter + dot, possibly with surrounding spaces)
450
+ if not is_option and preceded_by_newline and len(w_stripped) >= 2:
451
+ if w_stripped[0].lower() in option_letters and w_stripped[1] == '.':
452
+ is_option = True
453
+
454
+ if is_option:
455
+ if first_option_pos is None:
456
+ first_option_pos = vis_end + i
457
+ j = i
458
+ while j < len(text_ids):
459
+ option_positions.append(vis_end + j)
460
+ if '\n' in tokenizer.decode([text_ids[j]], skip_special_tokens=False):
461
+ break
462
+ j += 1
463
+ i += 1
464
+
465
+ text_end = first_option_pos if first_option_pos is not None else (seq_len - 1)
466
+ text_positions = list(range(vis_end, text_end))
467
+ if not text_positions:
468
+ text_positions = list(range(vis_end, seq_len - 1))
469
+
470
+ # print(f"[debug] first_option_pos={first_option_pos} text_positions count={len(list(range(vis_end, text_end if first_option_pos else seq_len-1)))}")
471
+ # for di in range(min(20, len(text_ids))):
472
+ # raw = tokenizer.decode([text_ids[di]], skip_special_tokens=False)
473
+ # print(f"[debug token] i={di} pos={vis_end+di} raw={repr(raw)}")
474
+ top_text_pos = []
475
+ sorted_ents = []
476
+ if need_keywords:
477
+ # ── scispaCy: extract medical entities from question, find their token positions ──
478
+ q_text = question if question else prompt
479
+ med_ents = _get_medical_entities(q_text)
480
+
481
+ pos_to_word = {}
482
+ for ti in text_positions:
483
+ if 0 <= ti < ids_cpu.shape[0]:
484
+ w = _decode_token(tokenizer, ids_cpu[ti].item())
485
+ if w:
486
+ pos_to_word[ti] = w
487
+
488
+ # build full text string with char-to-position mapping
489
+ # use raw decode (with ▁) to preserve word boundaries as spaces
490
+ full_text = ""
491
+ char_to_pos = []
492
+ for ti in text_positions:
493
+ if 0 <= ti < ids_cpu.shape[0]:
494
+ raw = tokenizer.decode([ids_cpu[ti].item()], skip_special_tokens=True)
495
+ # ▁ represents a space prefix in sentencepiece tokenizers
496
+ w = raw.replace("▁", " ").lower()
497
+ else:
498
+ w = ""
499
+ for _ in w:
500
+ char_to_pos.append(ti)
501
+ full_text += w
502
+ full_text_lower = full_text.lower()
503
+
504
+ def _find_entity_positions(ent):
505
+ ent_lower = ent.lower().strip()
506
+ idx = full_text_lower.find(ent_lower)
507
+ if idx == -1:
508
+ return []
509
+ end = idx + len(ent_lower)
510
+ # collect unique token positions covering this span
511
+ positions = []
512
+ seen_pos = set()
513
+ for ci in range(idx, min(end, len(char_to_pos))):
514
+ p = char_to_pos[ci]
515
+ if p not in seen_pos:
516
+ seen_pos.add(p)
517
+ positions.append(p)
518
+ return positions
519
+
520
+ # 每个实体词找到 token 位置,并用指定层注意力分数排序
521
+ ent_positions = {}
522
+ for ent in sorted(med_ents):
523
+ positions = _find_entity_positions(ent)
524
+ if positions:
525
+ ent_positions[ent] = positions
526
+
527
+ # 用 attn_layer_indices(调用方传入全部层)的注意力对实体词打分,取 top-k
528
+ if ent_positions and attn_layer_indices is not None and len(attn_layer_indices) > 0:
529
+ ent_scores = {}
530
+ for ent, positions in ent_positions.items():
531
+ valid_pos = [p for p in positions if p < seq_len]
532
+ if not valid_pos:
533
+ ent_scores[ent] = 0.0
534
+ continue
535
+ score_list = []
536
+ for layer in attn_layer_indices:
537
+ if layer < len(attentions):
538
+ # [1, heads, seq, seq] → 最后一个 query token 对这些位置的平均
539
+ att = attentions[layer][0, :, -1, valid_pos].float().mean().item()
540
+ score_list.append(att)
541
+ ent_scores[ent] = float(np.mean(score_list)) if score_list else 0.0
542
+ # 按分数降序,取 top-3
543
+ sorted_ents = sorted(ent_scores, key=lambda e: ent_scores[e], reverse=True)[:3]
544
+ print(f"[AttnRank] entity scores: { {e: f'{ent_scores[e]:.4f}' for e in sorted_ents} }")
545
+ else:
546
+ sorted_ents = list(ent_positions.keys())
547
+
548
+ for ent in sorted_ents:
549
+ top_text_pos.extend(ent_positions[ent])
550
+
551
+ # 确保疑问词 token 也被加入 key positions
552
+ wh_words = {'what', 'where', 'when', 'which', 'who', 'how'}
553
+ seen_pos = set(top_text_pos)
554
+ for ti in text_positions[:5]: # 只看问题前几个 token
555
+ if 0 <= ti < ids_cpu.shape[0]:
556
+ w = _decode_token(tokenizer, ids_cpu[ti].item())
557
+ if w.lower() in wh_words and ti not in seen_pos:
558
+ top_text_pos.append(ti)
559
+ seen_pos.add(ti)
560
+ print(f"[WH] added '{w}' at pos={ti}")
561
+ break
562
+
563
+ top_text_positions = [top_text_pos] if top_text_pos else [[]]
564
+ keywords = sorted_ents
565
+ return top_text_positions, text_positions, option_positions, img_start, seq_len, attentions, keywords
566
+
567
+
568
+ # ══════════════════════════════════════════════════════════════════════════════
569
+ # Step B: MedSAM3 visual localization
570
+ # ══════════════════════════════════════════════════════════════════════════════
571
+
572
+ def _bbox_to_patch_indices(bbox_xyxy, orig_size, img_pos, margin=2):
573
+ # cli.py's get_image_tensors() expand2square-pads the image to a square
574
+ # before resizing to the model's input grid, so bbox coords (in the
575
+ # original, unpadded image) must be shifted into the padded square's
576
+ # coordinate frame before converting to a patch fraction.
577
+ W, H = orig_size
578
+ side = max(W, H)
579
+ off_x = (side - W) // 2
580
+ off_y = (side - H) // 2
581
+ x1, y1, x2, y2 = bbox_xyxy
582
+ x1, x2 = x1 + off_x, x2 + off_x
583
+ y1, y2 = y1 + off_y, y2 + off_y
584
+ c1 = max(0, int(x1 / side * HUATUO_PATCHES) - margin)
585
+ r1 = max(0, int(y1 / side * HUATUO_PATCHES) - margin)
586
+ c2 = min(HUATUO_PATCHES - 1, int(x2 / side * HUATUO_PATCHES) + margin)
587
+ r2 = min(HUATUO_PATCHES - 1, int(y2 / side * HUATUO_PATCHES) + margin)
588
+ indices = []
589
+ for r in range(r1, r2 + 1):
590
+ for c in range(c1, c2 + 1):
591
+ indices.append(img_pos + r * HUATUO_PATCHES + c)
592
+ return indices
593
+
594
+
595
+ def _multi_bbox_to_patch_indices(bbox_list, orig_size, img_pos, margin=2):
596
+ seen, merged = set(), []
597
+ for bbox in bbox_list:
598
+ for idx in _bbox_to_patch_indices(bbox, orig_size, img_pos, margin):
599
+ if idx not in seen:
600
+ seen.add(idx)
601
+ merged.append(idx)
602
+ return merged
603
+
604
+
605
+ _vis_save_count = 0
606
+ _vis_save_dir = "vis_debug"
607
+
608
+
609
+ # ══════════════════════════════════════════════════════════════════════════════
610
+ # Step C: Attention intervention context manager
611
+ # ══════════════════════════════════════════════════════════════════════════════
612
+
613
+ class _AttnInterventionContext:
614
+ """
615
+ Within the with block, replaces attention forward of specified layers with a
616
+ pre-softmax key-bias intervention version.
617
+ both mode: key text tokens + option tokens + salient visual patches (union) get
618
+ a positive bias; all other positions get the non-key bias.
619
+ """
620
+ def __init__(self, bot, intervention,
621
+ top_text_positions=None,
622
+ all_text_positions=None,
623
+ option_positions=None,
624
+ attn_layer_indices_text=None,
625
+ key_bias_text=3.0, nonkey_bias_text=0.0,
626
+ img_pos=None, seq_len=None,
627
+ attn_layer_indices_vis=None,
628
+ key_bias_vis=3.0, nonkey_bias_vis=0.0,
629
+ vis_key_patches=None):
630
+ self._patched = []
631
+ self.intervention = intervention
632
+ self._img_pos = img_pos
633
+ self._option_positions = option_positions or []
634
+ all_layers = _get_attn_layers(bot)
635
+
636
+ # ── text-side keys: keyword tokens only (amplify, everything else unchanged) ─
637
+ seen, merged = set(), []
638
+ for ep in (top_text_positions or []):
639
+ for p in ep:
640
+ if p not in seen:
641
+ seen.add(p)
642
+ merged.append(p)
643
+ self._kw_positions = merged
644
+ self._all_text_positions = list(all_text_positions or [])
645
+ self._key_bias_text = float(key_bias_text)
646
+ self._nonkey_bias_text = float(nonkey_bias_text)
647
+ text_indices = [int(i) for i in (attn_layer_indices_text or []) if i is not None]
648
+ self._text_layers = [all_layers[i] for i in text_indices if 0 <= i < len(all_layers)]
649
+ self._text_layer_idx = [i for i in text_indices if 0 <= i < len(all_layers)]
650
+
651
+ # ── vis-side keys: SAM bbox patches only (amplify, everything else unchanged) ─
652
+ vis_seen, vis_merged = set(), []
653
+ for p in (vis_key_patches or []):
654
+ if p not in vis_seen:
655
+ vis_seen.add(p)
656
+ vis_merged.append(p)
657
+ self._vis_key_positions = vis_merged
658
+ self._key_bias_vis = float(key_bias_vis)
659
+ self._nonkey_bias_vis = float(nonkey_bias_vis)
660
+ vis_indices = [int(i) for i in (attn_layer_indices_vis or []) if i is not None]
661
+ self._vis_layers = [all_layers[i] for i in vis_indices if 0 <= i < len(all_layers)]
662
+ self._vis_layer_idx = [i for i in vis_indices if 0 <= i < len(all_layers)]
663
+
664
+ # ── both-mode keys: keyword tokens + SAM bbox patches (union) ────────
665
+ both_seen, both_merged = set(), []
666
+ for p in merged + vis_merged:
667
+ if p not in both_seen:
668
+ both_seen.add(p)
669
+ both_merged.append(p)
670
+ self._both_key_positions = both_merged
671
+
672
+ def __enter__(self):
673
+ if self.intervention == "none":
674
+ return self
675
+
676
+ img_pos = self._img_pos
677
+ img_set = set(range(img_pos, img_pos + HUATUO_NUM_IMG_TOKENS)) if img_pos is not None else set()
678
+ kw_set = set(self._kw_positions)
679
+ vis_set = set(self._vis_key_positions)
680
+ nonkey_img_set = img_set - vis_set
681
+
682
+ kbt = self._key_bias_text; nbt = self._nonkey_bias_text
683
+ kbv = self._key_bias_vis; nbv = self._nonkey_bias_vis
684
+
685
+ # precompute index tensors
686
+ all_text_set = set(self._all_text_positions)
687
+ nonkw_text_set = all_text_set - kw_set
688
+ kw_idx = torch.tensor(sorted(kw_set), dtype=torch.long) if kw_set else None
689
+ vis_idx = torch.tensor(sorted(vis_set), dtype=torch.long) if vis_set else None
690
+ nonkey_img_idx = torch.tensor(sorted(nonkey_img_set), dtype=torch.long) if nonkey_img_set else None
691
+ nonkw_text_idx = torch.tensor(sorted(nonkw_text_set), dtype=torch.long) if nonkw_text_set else None
692
+
693
+ if self.intervention == "text":
694
+ # default 0: prefix/suffix/prompt tokens untouched
695
+ # question non-keyword text: nbt, keyword text: kbt
696
+ def make_bias(key_positions, kv_len):
697
+ b = torch.zeros(kv_len)
698
+ if nonkw_text_idx is not None:
699
+ b[nonkw_text_idx[nonkw_text_idx < kv_len]] = nbt
700
+ if kw_idx is not None:
701
+ b[kw_idx[kw_idx < kv_len]] = kbt
702
+ return b
703
+ for layer in self._text_layers:
704
+ old_fwd = _patch_attn_forward_with_key_bias(
705
+ layer, self._kw_positions, tag="text",
706
+ bias_vec_fn=make_bias)
707
+ self._patched.append((layer, old_fwd))
708
+
709
+ elif self.intervention == "vis":
710
+ # key patches: +kbv, non-key patches: nbv, all text tokens: 0 (neutral)
711
+ def make_bias(key_positions, kv_len):
712
+ b = torch.zeros(kv_len)
713
+ if nonkey_img_idx is not None:
714
+ b[nonkey_img_idx[nonkey_img_idx < kv_len]] = nbv
715
+ if vis_idx is not None:
716
+ b[vis_idx[vis_idx < kv_len]] = kbv
717
+ return b
718
+ for layer in self._vis_layers:
719
+ old_fwd = _patch_attn_forward_with_key_bias(
720
+ layer, self._vis_key_positions, tag="vis",
721
+ bias_vec_fn=make_bias)
722
+ self._patched.append((layer, old_fwd))
723
+
724
+ elif self.intervention == "both":
725
+ # default 0: prefix/suffix/prompt/option tokens untouched
726
+ # question non-keyword text: nbt, keyword text: kbt
727
+ # non-key patches: nbv, key patches: kbv
728
+ def make_bias(key_positions, kv_len):
729
+ b = torch.zeros(kv_len)
730
+ if nonkw_text_idx is not None:
731
+ b[nonkw_text_idx[nonkw_text_idx < kv_len]] = nbt # non-keyword question text
732
+ if nonkey_img_idx is not None:
733
+ b[nonkey_img_idx[nonkey_img_idx < kv_len]] = nbv # non-key patches
734
+ if vis_idx is not None:
735
+ b[vis_idx[vis_idx < kv_len]] = kbv # key patches
736
+ if kw_idx is not None:
737
+ b[kw_idx[kw_idx < kv_len]] = kbt # keyword text
738
+ return b
739
+ all_tgt_layers = {id(l): l for l in set(self._text_layers + self._vis_layers)}
740
+ for _, layer in all_tgt_layers.items():
741
+ old_fwd = _patch_attn_forward_with_key_bias(
742
+ layer, self._both_key_positions, tag="both",
743
+ bias_vec_fn=make_bias)
744
+ self._patched.append((layer, old_fwd))
745
+
746
+ return self
747
+
748
+ def __exit__(self, *args):
749
+ for layer, old_fwd in self._patched:
750
+ layer.forward = old_fwd
751
+ for tag in ("text", "vis", "both"):
752
+ if hasattr(layer, f"_bias_printed_{tag}"):
753
+ delattr(layer, f"_bias_printed_{tag}")
754
+ self._patched = []
755
+
756
+
757
+ # ══════════════════════════════════════════════════════════════════════════════
758
+ # SAM bbox lookup helper
759
+ # ══════════════════════════════════════════════════════════════════════════════
760
+
761
+ def _set_attn_impl(model, impl):
762
+ for m in model.modules():
763
+ if hasattr(m, "_attn_implementation"):
764
+ m._attn_implementation = impl
765
+ if hasattr(m, "config") and hasattr(m.config, "_attn_implementation"):
766
+ m.config._attn_implementation = impl
767
+ model.config._attn_implementation = impl
768
+
769
+
770
+ def _get_sam_bbox_text(obj_name: str, pil_image, medsam3, max_bbox=1):
771
+ """Run SAM on a PIL image for obj_name, return at most max_bbox 'obj_name: [x1,y1,x2,y2]'
772
+ strings plus the combined segmentation mask (numpy array, or None if SAM produced no mask)."""
773
+ try:
774
+ bbox_list, mask, info = medsam3.predict_bbox(pil_image, obj_name)
775
+ if not bbox_list:
776
+ return [], None
777
+ lines = [f"{obj_name}: [{x1},{y1},{x2},{y2}]" for x1, y1, x2, y2 in bbox_list[:max_bbox]]
778
+ return lines, mask
779
+ except Exception as e:
780
+ print(f"[SAM] failed for '{obj_name}': {e}")
781
+ return [], None
782
+
783
+
784
+ def _build_objects_prompt(question: str, scispacy_keywords=None) -> str:
785
+ """Stage1 prompt: ask the model for SAM-segmentable objects only (no image caption).
786
+
787
+ scispacy_keywords are offered as candidates the model should prefer when they are
788
+ genuine segmentable structures; if none qualify (or more are needed), the model
789
+ fills the rest itself, up to 5 objects total.
790
+
791
+ Questions about the image's modality/scan type (e.g. "is this a CT or MRI?",
792
+ "what imaging technique was used?") have no segmentable target -- there is no
793
+ anatomical structure that "is" the modality. The prompt tells the model to reply
794
+ NONE for these instead of inventing organs/structures just to satisfy the format,
795
+ which would otherwise feed SAM a meaningless bbox.
796
+ """
797
+ exclusion_note = (
798
+ "A candidate only qualifies if SAM could draw a bounding box around it as a "
799
+ "distinct visual region -- a physical organ, bone, lesion, or anatomical "
800
+ "structure. Reject any candidate that is not itself a segmentable region: "
801
+ "directional/positional words (left, right, upper, lower, anterior, posterior, "
802
+ "proximal, distal, etc.), modifiers or descriptors (normal, abnormal, mild, "
803
+ "severe, etc.), symptoms, diagnoses, measurements, or image/modality properties "
804
+ "are NOT valid objects on their own, even if they appear in the question.\n"
805
+ )
806
+ if scispacy_keywords:
807
+ candidates_block = (
808
+ f"From the following candidate terms extracted from the question, "
809
+ f"select ONLY the ones that are themselves concrete anatomical structures "
810
+ f"or lesions visually present and segmentable in this image:\n"
811
+ f"Candidates: {', '.join(scispacy_keywords)}\n"
812
+ f"{exclusion_note}"
813
+ f"If none of the candidates qualify, or more relevant structures exist, "
814
+ f"you may add additional ones. List up to 5 total.\n"
815
+ )
816
+ else:
817
+ candidates_block = (
818
+ "Identify up to 5 anatomical structures or lesions most relevant to the "
819
+ "question that are visually present and physically segmentable in the image.\n"
820
+ f"{exclusion_note}"
821
+ )
822
+ return (
823
+ f"{candidates_block}"
824
+ f"Question: {question}\n"
825
+ "If the question is about the image's modality or scan type (e.g. CT vs MRI vs "
826
+ "X-ray vs ultrasound, or which imaging technique was used) rather than about a "
827
+ "specific anatomical structure or lesion, there is nothing to segment -- reply "
828
+ "with exactly: Objects: NONE\n"
829
+ "Otherwise reply with ONLY the object names, comma-separated, on a single line. "
830
+ "Use plain object names with no parentheses, no explanations, no extra text. "
831
+ "Format: Objects: <obj1>, <obj2>, ..."
832
+ )
833
+
834
+
835
+ def _parse_objects_response(response: str) -> list:
836
+ """Extract the object list from the Stage1 response, stripping any parenthetical asides.
837
+ Returns [] if the model replied NONE (e.g. modality/scan-type questions with no
838
+ segmentable target) -- the caller skips SAM entirely in that case."""
839
+ objects = []
840
+ for line in response.splitlines():
841
+ line = line.strip()
842
+ if line.lower().startswith("objects:"):
843
+ raw = line[len("objects:"):].strip()
844
+ if raw.strip().upper() == "NONE":
845
+ return []
846
+ objects = [_strip_parens(o) for o in raw.split(",") if _strip_parens(o)]
847
+ break
848
+ if not objects:
849
+ if response.strip().upper() == "NONE":
850
+ return []
851
+ objects = [o for o in (_strip_parens(o) for o in response.split(",")) if o]
852
+ return objects
853
+
854
+
855
+ # ══════════════════════════════════════════════════════════════════════════════
856
+ # test() — same structure as eval.py, only the inference call is replaced
857
+ # ══════════════════════════════════════════════════════════════════════════════
858
+
859
+ def test(args):
860
+ accelerator = Accelerator()
861
+ global _vis_save_dir
862
+ torch.cuda.set_device(accelerator.process_index)
863
+ accelerator.print(f'args:\n{args}')
864
+ _vis_save_dir = os.path.join(args.output_path, "vis_debug")
865
+
866
+ bot = HuatuoChatbot(args.model_path)
867
+ accelerator.print(f'load_finish')
868
+
869
+ bot.gen_kwargs['max_new_tokens'] = args.max_new_tokens
870
+
871
+ dataset = TestDataset(args, args.data_path)
872
+
873
+ if args.max_samples is not None:
874
+ dataset.datas = dataset.datas[:args.max_samples]
875
+
876
+ val_dataloader = DataLoader(dataset, batch_size=1, shuffle=False, drop_last=False, collate_fn=dataset.collate_fn)
877
+
878
+ val_dataloader = accelerator.prepare(val_dataloader)
879
+ accelerator.wait_for_everyone()
880
+
881
+ # Save code snapshot
882
+ if accelerator.is_main_process:
883
+ import shutil, glob as _glob
884
+ os.makedirs(args.output_path, exist_ok=True)
885
+ _snapshot_dir = os.path.join(args.output_path, '_snapshot')
886
+ os.makedirs(_snapshot_dir, exist_ok=True)
887
+ shutil.copy2(__file__, os.path.join(_snapshot_dir, os.path.basename(__file__)))
888
+ _sh_patterns = ('run_eval_attnbias_sam_*.sh', 'run_eval.sh', 'run_all_attnbias_sam.sh')
889
+ for _pattern in _sh_patterns:
890
+ for _sh in _glob.glob(os.path.join(os.path.dirname(__file__), _pattern)):
891
+ shutil.copy2(_sh, os.path.join(_snapshot_dir, os.path.basename(_sh)))
892
+ accelerator.print(f'[Snapshot] code snapshot saved to {_snapshot_dir}')
893
+
894
+ # Intervention layer selection
895
+ attn_layer_indices_text = _parse_layer_list(args.attn_layers_text)
896
+ if attn_layer_indices_text is None:
897
+ pt_path_text = args.pt_path_text or args.pt_path
898
+ if pt_path_text is None:
899
+ raise ValueError("Provide --attn_layers_text, or --pt_path/--pt_path_text to auto-select layers.")
900
+ attn_layer_indices_text = load_top_layers(
901
+ pt_path_text, args.attn_topk_text,
902
+ pt_path_random=args.pt_path_text_random or args.pt_path_random)
903
+
904
+ attn_layer_indices_vis = _parse_layer_list(args.attn_layers_vis)
905
+ if attn_layer_indices_vis is None:
906
+ if args.pt_path is None:
907
+ raise ValueError("Provide --attn_layers_vis, or --pt_path to auto-select layers.")
908
+ attn_layer_indices_vis = load_top_layers(
909
+ args.pt_path, args.attn_topk_vis, pt_path_random=args.pt_path_random)
910
+
911
+ accelerator.print(f'[layers] text={attn_layer_indices_text} vis={attn_layer_indices_vis}')
912
+
913
+ # entity scoring (extract_key_positions) always ranks over all layers,
914
+ # independent of the top-k layers selected above for the actual intervention
915
+ num_total_layers = len(_get_attn_layers(bot))
916
+ attn_layer_indices_score = list(range(num_total_layers))
917
+
918
+ # MedSAM3 initialization (only needed when SAM-based vis_patches actually feed the intervention)
919
+ _needs_sam = args.intervention in ("vis", "both")
920
+ medsam3 = None
921
+ if _needs_sam and args.medsam3_config:
922
+ try:
923
+ from medsam3_wrapper import MedSAM3Wrapper
924
+ except ImportError:
925
+ accelerator.print(
926
+ "[AttnBias] medsam3_wrapper.MedSAM3Wrapper not found; "
927
+ "continuing with medsam3=None (SAM bbox lookup degrades to the "
928
+ "full-image fallback in Stage2 below)."
929
+ )
930
+ MedSAM3Wrapper = None
931
+ if MedSAM3Wrapper is not None:
932
+ medsam3 = MedSAM3Wrapper(
933
+ config_path=args.medsam3_config,
934
+ device=args.medsam3_device or f"cuda:{accelerator.process_index}",
935
+ threshold=args.medsam3_threshold,
936
+ nms_iou=args.medsam3_nms_iou,
937
+ medsam3_dir=args.medsam3_dir,
938
+ )
939
+
940
+ # ── Pass 0: keyword extraction + Stage1 objects + SAM bbox for all samples (no VQA inference) ──
941
+ # Cache per-sample context: vis_patches, img_start, seq_len, orig_size
942
+ sample_list = []
943
+ with torch.no_grad():
944
+ dataloader_iterator = tqdm(val_dataloader, total=len(val_dataloader), desc="Stage1+SAM") if accelerator.is_main_process else val_dataloader
945
+ for batch in dataloader_iterator:
946
+ for da, query, image in zip(batch["data"], batch['query'], batch['image']):
947
+ image_paths = [os.path.join(os.path.dirname(args.data_path), x) for x in image]
948
+ for img in image_paths:
949
+ assert os.path.exists(img), f'{img} not exists'
950
+ img_path = image_paths[0] if image_paths else None
951
+ pil_img = Image.open(img_path).convert("RGB") if img_path else None
952
+
953
+ # extract img_start + keyword positions (eager forward; also needed for text/both)
954
+ orig_impl = bot.model.config._attn_implementation
955
+ _set_attn_impl(bot.model, "eager")
956
+ top_text_pos, all_text_pos, option_pos = [[]], [], []
957
+ keywords = []
958
+ img_start, seq_len = None, None
959
+ try:
960
+ top_text_pos, all_text_pos, option_pos, img_start, seq_len, _, keywords = \
961
+ extract_key_positions(bot, query, img_path, question=da.get('question', ''),
962
+ attn_layer_indices=attn_layer_indices_score,
963
+ need_keywords=(args.intervention != "none"))
964
+ except Exception as e:
965
+ print(f"[AttnBias] img_start extraction failed: {e}, using full-image fallback")
966
+ finally:
967
+ _set_attn_impl(bot.model, orig_impl)
968
+
969
+ print(f"[scispaCy] keywords: {keywords}")
970
+
971
+ # Stage1: ask the model for SAM-segmentable objects (scispaCy keywords as hint, no caption)
972
+ objects = []
973
+ if _needs_sam and medsam3 is not None and pil_img is not None:
974
+ _orig_max_new_tokens = bot.gen_kwargs.get("max_new_tokens", 32)
975
+ bot.gen_kwargs["max_new_tokens"] = 32
976
+ stage1_response = bot.inference(
977
+ _build_objects_prompt(da.get('question', '') or query, scispacy_keywords=keywords),
978
+ image_paths)
979
+ bot.gen_kwargs["max_new_tokens"] = _orig_max_new_tokens
980
+ stage1_text = stage1_response[0] if stage1_response else ""
981
+ objects = _parse_objects_response(stage1_text)
982
+ print(f"[Stage1] objects: {objects}")
983
+
984
+ # Stage2: SAM bbox + segmentation mask from Stage1 objects
985
+ all_bboxes = []
986
+ obj_masks = [] # [(obj_name, mask_ndarray), ...] -- one combined mask per object
987
+ if _needs_sam and medsam3 is not None and pil_img is not None:
988
+ for obj in objects[:10]:
989
+ lines, mask = _get_sam_bbox_text(obj, pil_img, medsam3, max_bbox=2)
990
+ for line in lines:
991
+ try:
992
+ coords = [int(v) for v in line.split("[")[1].rstrip("]").split(",")]
993
+ all_bboxes.append((obj, *coords))
994
+ except Exception:
995
+ pass
996
+ if mask is not None:
997
+ obj_masks.append((obj, mask))
998
+
999
+ # Visualization + mask persistence (only meaningful when SAM actually ran;
1000
+ # otherwise all_bboxes/obj_masks are always empty)
1001
+ global _vis_save_count
1002
+ if _needs_sam and pil_img is not None and _vis_save_count < 30:
1003
+ import matplotlib.pyplot as plt
1004
+ import matplotlib.patches as mpatches
1005
+ import matplotlib.colors as mcolors
1006
+ os.makedirs(_vis_save_dir, exist_ok=True)
1007
+
1008
+ # save each object's raw mask array, plus a combined mask across all objects
1009
+ for obj_name, mask in obj_masks:
1010
+ safe_name = re.sub(r"[^a-zA-Z0-9_-]+", "_", obj_name)[:40]
1011
+ np.save(os.path.join(_vis_save_dir,
1012
+ f"sam_{_vis_save_count:03d}_mask_{safe_name}.npy"), mask)
1013
+ if obj_masks:
1014
+ combined = obj_masks[0][1].astype(np.float32)
1015
+ for _, m in obj_masks[1:]:
1016
+ combined = np.maximum(combined, m.astype(np.float32))
1017
+ np.save(os.path.join(_vis_save_dir,
1018
+ f"sam_{_vis_save_count:03d}_mask_combined.npy"), combined)
1019
+
1020
+ fig, ax = plt.subplots(1, 1, figsize=(7, 7))
1021
+ ax.imshow(np.array(pil_img))
1022
+ colors = ["red", "lime", "cyan", "yellow", "magenta", "orange", "white", "blue"]
1023
+ # overlay each object's mask (semi-transparent) before drawing bbox/label
1024
+ for ci, (obj_name, mask) in enumerate(obj_masks):
1025
+ color = colors[ci % len(colors)]
1026
+ rgba = np.zeros((*mask.shape, 4))
1027
+ rgb = mcolors.to_rgb(color)
1028
+ rgba[..., :3] = rgb
1029
+ rgba[..., 3] = (mask > 0).astype(np.float32) * 0.45
1030
+ ax.imshow(rgba)
1031
+ for ci, entry in enumerate(all_bboxes):
1032
+ obj_name, x1, y1, x2, y2 = entry
1033
+ color = colors[ci % len(colors)]
1034
+ ax.add_patch(mpatches.Rectangle((x1, y1), x2-x1, y2-y1, linewidth=2, edgecolor=color, facecolor="none"))
1035
+ ax.text(x1, y1-4, obj_name, color=color, fontsize=7, bbox=dict(facecolor="black", alpha=0.4, pad=1))
1036
+ ax.set_title(f"objects: {objects}", fontsize=7, wrap=True)
1037
+ ax.axis("off")
1038
+ fig.savefig(os.path.join(_vis_save_dir, f"sam_{_vis_save_count:03d}.png"), dpi=120, bbox_inches="tight")
1039
+ plt.close(fig)
1040
+ _vis_save_count += 1
1041
+
1042
+ orig_size = pil_img.size if pil_img is not None else (1, 1)
1043
+ raw_bboxes = [[x1, y1, x2, y2] for (_, x1, y1, x2, y2) in all_bboxes]
1044
+ if not raw_bboxes and pil_img is not None:
1045
+ # No SAM result (e.g. SAM found nothing, or the question was a modality
1046
+ # question with no segmentable target -- see _build_objects_prompt).
1047
+ # Fall back to the bounding box of the non-zero (actual image content)
1048
+ # pixels rather than the full canvas, so black letterbox/background
1049
+ # padding common in medical scans isn't treated as "key region".
1050
+ W, H = orig_size
1051
+ img_arr = np.array(pil_img.convert("L"))
1052
+ ys, xs = np.where(img_arr > 0)
1053
+ if len(xs) > 0:
1054
+ raw_bboxes = [[int(xs.min()), int(ys.min()), int(xs.max()) + 1, int(ys.max()) + 1]]
1055
+ else:
1056
+ raw_bboxes = [[0, 0, W, H]]
1057
+ vis_patches = _multi_bbox_to_patch_indices(raw_bboxes, orig_size, img_start, margin=2) if img_start is not None else []
1058
+ print(f"[AttnBias] vis_patches={len(vis_patches)} from {len(raw_bboxes)} bboxes")
1059
+
1060
+ sample_list.append(dict(
1061
+ da=da, query=query, image_paths=image_paths, img_path=img_path,
1062
+ img_start=img_start, seq_len=seq_len,
1063
+ vis_patches=vis_patches, orig_size=orig_size,
1064
+ top_text_pos=top_text_pos, all_text_pos=all_text_pos,
1065
+ option_pos=option_pos, keywords=keywords, objects=objects,
1066
+ ))
1067
+
1068
+ # ── Helper: build intervention context (mode follows args.intervention; SAM vis_patches kept) ──
1069
+ def _make_attn_ctx(img_start, seq_len, vis_patches, top_text_pos=None, all_text_pos=None, option_pos=None):
1070
+ return _AttnInterventionContext(
1071
+ bot, args.intervention,
1072
+ top_text_positions=top_text_pos or [[]],
1073
+ all_text_positions=all_text_pos or [],
1074
+ option_positions=option_pos or [],
1075
+ attn_layer_indices_text=attn_layer_indices_text,
1076
+ key_bias_text=args.attn_key_bias_text,
1077
+ nonkey_bias_text=args.attn_nonkey_bias_text,
1078
+ img_pos=img_start, seq_len=seq_len,
1079
+ attn_layer_indices_vis=attn_layer_indices_vis,
1080
+ key_bias_vis=args.attn_key_bias_vis,
1081
+ nonkey_bias_vis=args.attn_nonkey_bias_vis,
1082
+ vis_key_patches=vis_patches,
1083
+ )
1084
+
1085
+ def _make_inputs(q, img_path):
1086
+ t = bot.input_moderation(q)
1087
+ t = bot.insert_image_placeholder(t, 1)
1088
+ cv = bot.get_conv_without_history(t)
1089
+ ids = bot.preprocess(cv, return_tensors="pt").unsqueeze(0).to(bot.device)
1090
+ imgs = (torch.stack(bot.get_image_tensors([img_path]))
1091
+ .to(dtype=torch.bfloat16).to(bot.device))
1092
+ return ids, imgs
1093
+
1094
+ orig_impl = bot.model.config._attn_implementation
1095
+
1096
+ # ── Pass 1+3: plain inference is only ever needed for "none" mode, or as a
1097
+ # fallback when img_start extraction failed for a sample -- for text/vis/both
1098
+ # with a successful extraction, the intervention pass below fully overwrites
1099
+ # it, so running it unconditionally for every sample would be wasted compute. ──
1100
+ set_seed(args.seed)
1101
+ with torch.no_grad():
1102
+ for s in tqdm(sample_list, desc="generate") if accelerator.is_main_process else sample_list:
1103
+ if args.intervention == "none" or s['img_start'] is None:
1104
+ s['da']['model_output'] = bot.inference(s['query'], s['image_paths'])[0]
1105
+ continue
1106
+ aug_ids, aug_imgs = _make_inputs(s['query'], s['img_path'])
1107
+ _set_attn_impl(bot.model, "eager")
1108
+ try:
1109
+ with torch.inference_mode():
1110
+ with _make_attn_ctx(s['img_start'], s['seq_len'], s['vis_patches'],
1111
+ top_text_pos=s['top_text_pos'], all_text_pos=s['all_text_pos'],
1112
+ option_pos=s['option_pos']):
1113
+ out_ids = bot.model.generate(aug_ids, images=aug_imgs, use_cache=True, **bot.gen_kwargs)
1114
+ finally:
1115
+ _set_attn_impl(bot.model, orig_impl)
1116
+ s['da']['model_output'] = bot.tokenizer.decode(out_ids[0], skip_special_tokens=True).strip()
1117
+
1118
+ torch.cuda.empty_cache()
1119
+ accelerator.wait_for_everyone()
1120
+
1121
+ cache_data = [s['da'] for s in sample_list]
1122
+ all_data = [None] * dist.get_world_size()
1123
+ dist.all_gather_object(all_data, cache_data)
1124
+ all_data = [item for sublist in all_data for item in sublist]
1125
+
1126
+ ress = all_data
1127
+
1128
+ if accelerator.is_main_process:
1129
+ import copy
1130
+ task_name = os.path.basename(args.model_path) + f'_{os.path.split(args.data_path)[-1].replace(".json","")}'+ f'_{args.intervention}'
1131
+
1132
+ def _save_and_score(ress_input, key, suffix):
1133
+ ress_copy = []
1134
+ for d in ress_input:
1135
+ dc = copy.deepcopy(d)
1136
+ dc['model_output'] = d.get(key, d['model_output'])
1137
+ ress_copy.append(dc)
1138
+ out_f = os.path.join(args.output_path, f'{task_name}{suffix}.json')
1139
+ with open(out_f, 'w') as fw:
1140
+ json.dump(ress_copy, fw, ensure_ascii=False, indent=2)
1141
+ val = score_mix_llava(ress_copy)
1142
+ accelerator.print(f'[{suffix}] {json.dumps(val, ensure_ascii=False, indent=2)}')
1143
+ with open(os.path.join(args.output_path, f'{task_name}{suffix}_result.json'), 'w') as fw:
1144
+ json.dump(val, fw, ensure_ascii=False, indent=2)
1145
+ print(f'{suffix} results: {out_f}')
1146
+
1147
+ print(f'question num: {len(ress)}')
1148
+ _save_and_score(ress, 'model_output', '')
1149
+
1150
+
1151
+ # ══════════════════════════════════════════════════════════════════════════════
1152
+ # Arguments — original eval.py args unchanged, intervention args added
1153
+ # ══════════════════════════════════════════════════════════════════════════════
1154
+
1155
+ if __name__ == '__main__':
1156
+ parser = argparse.ArgumentParser(description='Args of sft')
1157
+
1158
+ # Model Args
1159
+ parser.add_argument('--data_path', default='medical_multimodel_evaluation_data.json', type=str)
1160
+ parser.add_argument('--model_path', default='HuatuoGPT-Vision-7B', type=str)
1161
+ parser.add_argument('--max_new_tokens', default=256, type=int)
1162
+ parser.add_argument('--batch_size', default=2, type=int)
1163
+
1164
+ # Other Args
1165
+ parser.add_argument('--seed', default=42, type=int)
1166
+
1167
+ # Attention intervention Args
1168
+ parser.add_argument('--pt_path', type=str, default=None)
1169
+ parser.add_argument('--pt_path_random', type=str, default=None)
1170
+ parser.add_argument('--pt_path_text', type=str, default=None)
1171
+ parser.add_argument('--pt_path_text_random', type=str, default=None)
1172
+ parser.add_argument('--attn_layers_text', type=str, default=17)
1173
+ parser.add_argument('--attn_topk_text', type=int, default=1)
1174
+ parser.add_argument('--attn_layers_vis', type=str, default=17)
1175
+ parser.add_argument('--attn_topk_vis', type=int, default=1)
1176
+ parser.add_argument('--attn_key_bias_text', type=float, default=3.0)
1177
+ parser.add_argument('--attn_nonkey_bias_text', type=float, default=-3.0)
1178
+ parser.add_argument('--attn_key_bias_vis', type=float, default=3.0)
1179
+ parser.add_argument('--attn_nonkey_bias_vis', type=float, default=-3.0)
1180
+ parser.add_argument('--intervention', type=str, default='both', choices=['text', 'vis', 'both', 'none'])
1181
+ parser.add_argument('--medsam3_config', type=str, default=None)
1182
+ parser.add_argument('--medsam3_dir', type=str, default=None)
1183
+ parser.add_argument('--medsam3_device', type=str, default=None)
1184
+ parser.add_argument('--medsam3_threshold', type=float, default=0.3)
1185
+ parser.add_argument('--medsam3_nms_iou', type=float, default=0.5)
1186
+ parser.add_argument('--output_path', type=str, default='results_attnbias')
1187
+ parser.add_argument('--max_samples', type=int, default=None)
1188
+
1189
+ args = parser.parse_args()
1190
+
1191
+ set_seed(args.seed)
1192
+ test(args)
之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/HuatuoGPT-Vision/results_attnbias/HuatuoGPT-Vision-7B/sam_none/_snapshot/run_all_attnbias_sam.sh ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ cd "$(dirname "$0")"
3
+
4
+ # 先跑 baseline(无干预的 eval.py),再依次跑完 none / text / vis / both 四种干预模式
5
+ # 任意一个失败就停止,避免在错误的环境下继续浪费时间
6
+ set -e
7
+
8
+ # 默认使用 huatuovision conda 环境,不依赖调用者当前激活的环境
9
+ source "$(conda info --base)/etc/profile.d/conda.sh"
10
+ conda activate huatuovision
11
+
12
+ SCRIPTS=(
13
+ "run_eval.sh"
14
+ "run_eval_attnbias_sam_none.sh"
15
+ "run_eval_attnbias_sam_text.sh"
16
+ "run_eval_attnbias_sam_vis.sh"
17
+ "run_eval_attnbias_sam_both.sh"
18
+ )
19
+
20
+ for script in "${SCRIPTS[@]}"; do
21
+ echo "=================================================="
22
+ echo "[run_all] 开始运行 $script"
23
+ echo "=================================================="
24
+ bash "$script"
25
+ echo "[run_all] $script 运行完成"
26
+ done
27
+
28
+ echo "[run_all] 全部干预模式运行完成"
之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/HuatuoGPT-Vision/results_attnbias/HuatuoGPT-Vision-7B/sam_none/_snapshot/run_eval.sh ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ cd "$(dirname "$0")"
3
+
4
+ DATA_PATH="/home/jinhua/ExplainableVQA/benchmarks/Medical_Multimodal_Evaluation_Data/medical_multimodel_evaluation_data.json"
5
+ MODEL_PATH="FreedomIntelligence/HuatuoGPT-Vision-7B"
6
+
7
+ SEED=42
8
+ MAX_NEW_TOKENS=256
9
+
10
+ accelerate launch eval.py \
11
+ --data_path "$DATA_PATH" \
12
+ --model_path "$MODEL_PATH" \
13
+ --seed "$SEED" \
14
+ --max_new_tokens "$MAX_NEW_TOKENS"
之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/HuatuoGPT-Vision/results_attnbias/HuatuoGPT-Vision-7B/sam_none/_snapshot/run_eval_attnbias_sam_both.sh ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ cd "$(dirname "$0")"
3
+
4
+ DATA_PATH="/home/jinhua/ExplainableVQA/benchmarks/Medical_Multimodal_Evaluation_Data/medical_multimodel_evaluation_data.json"
5
+ MODEL_PATH="FreedomIntelligence/HuatuoGPT-Vision-7B"
6
+ OUTPUT_PATH="results_attnbias/HuatuoGPT-Vision-7B/sam_both"
7
+
8
+ SEED=42
9
+ MAX_NEW_TOKENS=256
10
+
11
+ MEDSAM3_CONFIG="/home/jinhua/ExplainableVQA/HuatuoGPT-Vision/MedSAM3/configs/full_lora_config.yaml"
12
+ MEDSAM3_DIR="/home/jinhua/ExplainableVQA/HuatuoGPT-Vision/MedSAM3"
13
+
14
+ # both mode: amplify scispaCy keyword tokens + SAM-bbox patches via pre-softmax bias
15
+ INTERVENTION="both"
16
+ ATTN_LAYERS_TEXT="17"
17
+ ATTN_KEY_BIAS_TEXT=4.0
18
+ ATTN_NONKEY_BIAS_TEXT=-4.0
19
+ ATTN_LAYERS_VIS="17"
20
+ ATTN_KEY_BIAS_VIS=1.0
21
+ ATTN_NONKEY_BIAS_VIS=-1.0
22
+
23
+ MAX_SAMPLES=""
24
+
25
+ accelerate launch eval_attnbias_sam.py \
26
+ --data_path "$DATA_PATH" \
27
+ --model_path "$MODEL_PATH" \
28
+ --seed "$SEED" \
29
+ --max_new_tokens "$MAX_NEW_TOKENS" \
30
+ --output_path "$OUTPUT_PATH" \
31
+ --intervention "$INTERVENTION" \
32
+ --attn_layers_text "$ATTN_LAYERS_TEXT" \
33
+ --attn_key_bias_text "$ATTN_KEY_BIAS_TEXT" \
34
+ --attn_nonkey_bias_text "$ATTN_NONKEY_BIAS_TEXT" \
35
+ --attn_layers_vis "$ATTN_LAYERS_VIS" \
36
+ --attn_key_bias_vis "$ATTN_KEY_BIAS_VIS" \
37
+ --attn_nonkey_bias_vis "$ATTN_NONKEY_BIAS_VIS" \
38
+ --medsam3_config "$MEDSAM3_CONFIG" \
39
+ --medsam3_dir "$MEDSAM3_DIR" \
40
+ ${MAX_SAMPLES:-}
之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/HuatuoGPT-Vision/results_attnbias/HuatuoGPT-Vision-7B/sam_none/_snapshot/run_eval_attnbias_sam_none.sh ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ cd "$(dirname "$0")"
3
+
4
+ DATA_PATH="/home/jinhua/ExplainableVQA/benchmarks/Medical_Multimodal_Evaluation_Data/medical_multimodel_evaluation_data.json"
5
+ MODEL_PATH="FreedomIntelligence/HuatuoGPT-Vision-7B"
6
+ OUTPUT_PATH="results_attnbias/HuatuoGPT-Vision-7B/sam_none"
7
+
8
+ SEED=42
9
+ MAX_NEW_TOKENS=256
10
+
11
+ MEDSAM3_CONFIG="/home/jinhua/ExplainableVQA/HuatuoGPT-Vision/MedSAM3/configs/full_lora_config.yaml"
12
+ MEDSAM3_DIR="/home/jinhua/ExplainableVQA/HuatuoGPT-Vision/MedSAM3"
13
+
14
+ # none: no attention intervention (model_output reuses plain inference result)
15
+ INTERVENTION="none"
16
+ ATTN_LAYERS_TEXT="17"
17
+ ATTN_KEY_BIAS_TEXT=4.0
18
+ ATTN_NONKEY_BIAS_TEXT=-4.0
19
+ ATTN_LAYERS_VIS="17"
20
+ ATTN_KEY_BIAS_VIS=1.0
21
+ ATTN_NONKEY_BIAS_VIS=-1.0
22
+
23
+ MAX_SAMPLES=""
24
+
25
+ accelerate launch eval_attnbias_sam.py \
26
+ --data_path "$DATA_PATH" \
27
+ --model_path "$MODEL_PATH" \
28
+ --seed "$SEED" \
29
+ --max_new_tokens "$MAX_NEW_TOKENS" \
30
+ --output_path "$OUTPUT_PATH" \
31
+ --intervention "$INTERVENTION" \
32
+ --attn_layers_text "$ATTN_LAYERS_TEXT" \
33
+ --attn_key_bias_text "$ATTN_KEY_BIAS_TEXT" \
34
+ --attn_nonkey_bias_text "$ATTN_NONKEY_BIAS_TEXT" \
35
+ --attn_layers_vis "$ATTN_LAYERS_VIS" \
36
+ --attn_key_bias_vis "$ATTN_KEY_BIAS_VIS" \
37
+ --attn_nonkey_bias_vis "$ATTN_NONKEY_BIAS_VIS" \
38
+ --medsam3_config "$MEDSAM3_CONFIG" \
39
+ --medsam3_dir "$MEDSAM3_DIR" \
40
+ ${MAX_SAMPLES:-}
之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/HuatuoGPT-Vision/results_attnbias/HuatuoGPT-Vision-7B/sam_none/_snapshot/run_eval_attnbias_sam_text.sh ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ cd "$(dirname "$0")"
3
+
4
+ DATA_PATH="/home/jinhua/ExplainableVQA/benchmarks/Medical_Multimodal_Evaluation_Data/medical_multimodel_evaluation_data.json"
5
+ MODEL_PATH="FreedomIntelligence/HuatuoGPT-Vision-7B"
6
+ OUTPUT_PATH="results_attnbias/HuatuoGPT-Vision-7B/sam_text"
7
+
8
+ SEED=42
9
+ MAX_NEW_TOKENS=256
10
+
11
+ MEDSAM3_CONFIG="/home/jinhua/ExplainableVQA/HuatuoGPT-Vision/MedSAM3/configs/full_lora_config.yaml"
12
+ MEDSAM3_DIR="/home/jinhua/ExplainableVQA/HuatuoGPT-Vision/MedSAM3"
13
+
14
+ # text mode: amplify scispaCy keyword tokens only via pre-softmax bias
15
+ INTERVENTION="text"
16
+ ATTN_LAYERS_TEXT="17"
17
+ ATTN_KEY_BIAS_TEXT=4.0
18
+ ATTN_NONKEY_BIAS_TEXT=-4.0
19
+ ATTN_LAYERS_VIS="17"
20
+ ATTN_KEY_BIAS_VIS=1.0
21
+ ATTN_NONKEY_BIAS_VIS=-1.0
22
+
23
+ MAX_SAMPLES=""
24
+
25
+ accelerate launch eval_attnbias_sam.py \
26
+ --data_path "$DATA_PATH" \
27
+ --model_path "$MODEL_PATH" \
28
+ --seed "$SEED" \
29
+ --max_new_tokens "$MAX_NEW_TOKENS" \
30
+ --output_path "$OUTPUT_PATH" \
31
+ --intervention "$INTERVENTION" \
32
+ --attn_layers_text "$ATTN_LAYERS_TEXT" \
33
+ --attn_key_bias_text "$ATTN_KEY_BIAS_TEXT" \
34
+ --attn_nonkey_bias_text "$ATTN_NONKEY_BIAS_TEXT" \
35
+ --attn_layers_vis "$ATTN_LAYERS_VIS" \
36
+ --attn_key_bias_vis "$ATTN_KEY_BIAS_VIS" \
37
+ --attn_nonkey_bias_vis "$ATTN_NONKEY_BIAS_VIS" \
38
+ --medsam3_config "$MEDSAM3_CONFIG" \
39
+ --medsam3_dir "$MEDSAM3_DIR" \
40
+ ${MAX_SAMPLES:-}
之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/HuatuoGPT-Vision/results_attnbias/HuatuoGPT-Vision-7B/sam_none/_snapshot/run_eval_attnbias_sam_vis.sh ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ cd "$(dirname "$0")"
3
+
4
+ DATA_PATH="/home/jinhua/ExplainableVQA/benchmarks/Medical_Multimodal_Evaluation_Data/medical_multimodel_evaluation_data.json"
5
+ MODEL_PATH="FreedomIntelligence/HuatuoGPT-Vision-7B"
6
+ OUTPUT_PATH="results_attnbias/HuatuoGPT-Vision-7B/sam_vis"
7
+
8
+ SEED=42
9
+ MAX_NEW_TOKENS=256
10
+
11
+ MEDSAM3_CONFIG="/home/jinhua/ExplainableVQA/HuatuoGPT-Vision/MedSAM3/configs/full_lora_config.yaml"
12
+ MEDSAM3_DIR="/home/jinhua/ExplainableVQA/HuatuoGPT-Vision/MedSAM3"
13
+
14
+ # vis mode: amplify SAM-bbox patches only via pre-softmax bias
15
+ INTERVENTION="vis"
16
+ ATTN_LAYERS_TEXT="17"
17
+ ATTN_KEY_BIAS_TEXT=4.0
18
+ ATTN_NONKEY_BIAS_TEXT=-4.0
19
+ ATTN_LAYERS_VIS="17"
20
+ ATTN_KEY_BIAS_VIS=1.0
21
+ ATTN_NONKEY_BIAS_VIS=-1.0
22
+
23
+ MAX_SAMPLES=""
24
+
25
+ accelerate launch eval_attnbias_sam.py \
26
+ --data_path "$DATA_PATH" \
27
+ --model_path "$MODEL_PATH" \
28
+ --seed "$SEED" \
29
+ --max_new_tokens "$MAX_NEW_TOKENS" \
30
+ --output_path "$OUTPUT_PATH" \
31
+ --intervention "$INTERVENTION" \
32
+ --attn_layers_text "$ATTN_LAYERS_TEXT" \
33
+ --attn_key_bias_text "$ATTN_KEY_BIAS_TEXT" \
34
+ --attn_nonkey_bias_text "$ATTN_NONKEY_BIAS_TEXT" \
35
+ --attn_layers_vis "$ATTN_LAYERS_VIS" \
36
+ --attn_key_bias_vis "$ATTN_KEY_BIAS_VIS" \
37
+ --attn_nonkey_bias_vis "$ATTN_NONKEY_BIAS_VIS" \
38
+ --medsam3_config "$MEDSAM3_CONFIG" \
39
+ --medsam3_dir "$MEDSAM3_DIR" \
40
+ ${MAX_SAMPLES:-}
之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/HuatuoGPT-Vision/results_attnbias/HuatuoGPT-Vision-7B/sam_text/HuatuoGPT-Vision-7B_medical_multimodel_evaluation_data_text.json ADDED
The diff for this file is too large to render. See raw diff
 
之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/HuatuoGPT-Vision/results_attnbias/HuatuoGPT-Vision-7B/sam_text/HuatuoGPT-Vision-7B_medical_multimodel_evaluation_data_text_result.json ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "OmniMedVQA": 0.743797195253506,
3
+ "PMC-VQA_test": 0.55,
4
+ "PathVQA_test": 0.582093991671624,
5
+ "VQA-RAD_test": 0.6254980079681275,
6
+ "SLAKE_test": 0.7572115384615384,
7
+ "MMMU_Medical_Validation": 0.5379310344827586,
8
+ "The total score for multiple-choice questions": 0.686842409527113,
9
+ "OmniMedVQA_MR (Mag-netic Resonance Imaging)": 0.7282178217821782,
10
+ "OmniMedVQA_ultrasound": 0.7776957163958641,
11
+ "OmniMedVQA_OCT (Optical Coherence Tomography": 0.8631578947368421,
12
+ "OmniMedVQA_Dermoscopy": 0.7223618090452262,
13
+ "OmniMedVQA_X-Ray": 0.8086359175662414,
14
+ "OmniMedVQA_CT(Computed Tomography)": 0.6619789050728278,
15
+ "OmniMedVQA_Fundus Photography": 0.8162939297124601,
16
+ "OmniMedVQA_Microscopy Images": 0.7678571428571429,
17
+ "MMMU_Medical_Validation_validation_Public_Health": 0.5666666666666667,
18
+ "MMMU_Medical_Validation_validation_Pharmacy": 0.4444444444444444,
19
+ "MMMU_Medical_Validation_validation_Basic_Medical_Science": 0.5714285714285714,
20
+ "MMMU_Medical_Validation_validation_Clinical_Medicine": 0.6666666666666666,
21
+ "MMMU_Medical_Validation_validation_Diagnostics_and_Laboratory_Medicine": 0.43333333333333335
22
+ }
之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/HuatuoGPT-Vision/results_attnbias/HuatuoGPT-Vision-7B/sam_text/_snapshot/eval_attnbias_sam.py ADDED
@@ -0,0 +1,1192 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Code for finetune_huatuo"""
2
+
3
+ import os
4
+ import re
5
+ import copy
6
+ import json
7
+ import torch
8
+ import logging
9
+ import argparse
10
+ from transformers.generation.utils import LogitsProcessorList
11
+ from transformers.generation.logits_process import LogitsProcessor
12
+ import sys
13
+ import ast
14
+
15
+ from tqdm import tqdm
16
+ import torch.distributed as dist
17
+ from torch.utils.data import Dataset, DataLoader
18
+ from accelerate import Accelerator, DeepSpeedPlugin
19
+ from transformers import set_seed
20
+ import datasets
21
+ import shutil
22
+ import json
23
+ import random
24
+ from scorer import score_mix_llava
25
+ from cli import HuatuoChatbot
26
+
27
+
28
+ from transformers import AutoModelForCausalLM, AutoTokenizer, AutoModel, AutoModelWithLMHead
29
+ os.umask(0)
30
+
31
+
32
+ logger = logging.getLogger(__name__)
33
+ logging.basicConfig(level='INFO')
34
+
35
+ # Additional imports for attention intervention
36
+ import gc
37
+ import math
38
+ import types
39
+ import numpy as np
40
+ import torch.nn.functional as F
41
+ from PIL import Image
42
+
43
+ import matplotlib
44
+ matplotlib.use("Agg") # non-interactive backend: avoids X11 display / forwarding prompts on remote sessions
45
+
46
+
47
+ # ══════════════════════════════════════════════════════════════════════════════
48
+ # Constants
49
+ # ══════════════════════════════════════════════════════════════════════════════
50
+
51
+ HUATUO_NUM_IMG_TOKENS = 576
52
+ HUATUO_PATCHES = 24
53
+
54
+
55
+ _sci_nlp = None
56
+
57
+ def _get_sci_nlp():
58
+ global _sci_nlp
59
+ if _sci_nlp is None:
60
+ try:
61
+ import spacy
62
+ _sci_nlp = spacy.load("en_core_sci_sm")
63
+ print("[scispaCy] en_core_sci_sm loaded")
64
+ except Exception as e:
65
+ print(f"[scispaCy] load failed ({e}), falling back to rule filter.")
66
+ _sci_nlp = None
67
+ return _sci_nlp
68
+
69
+
70
+ _PAREN_RE = re.compile(r"\([^)]*\)")
71
+
72
+
73
+ def _strip_parens(text: str) -> str:
74
+ return re.sub(r"\s{2,}", " ", _PAREN_RE.sub("", text)).strip()
75
+
76
+
77
+ def _get_medical_entities(text: str) -> set:
78
+ nlp = _get_sci_nlp()
79
+ if nlp is None:
80
+ return set()
81
+ doc = nlp(text)
82
+ return {ent.text.lower().strip() for ent in doc.ents if len(ent.text.strip()) >= 2}
83
+
84
+
85
+ # ══════════════════════════════════════════════════════════════════════════════
86
+ # TestDataset
87
+
88
+ class TestDataset(torch.utils.data.Dataset):
89
+ def __init__(self, config, data_path):
90
+ self.config = config
91
+ self.dataset = {}
92
+ with open(data_path) as f:
93
+ self.dataset = json.load(f)
94
+ self.datas = []
95
+
96
+ test_id = 1
97
+ for da in self.dataset:
98
+ da['query'] = self.llava_prompt(da)
99
+ da['test_id'] = test_id
100
+ test_id += 1
101
+ self.datas.append(da)
102
+
103
+ def mmmu_prompt(self,da):
104
+ self.query_prompt = "Please answer the multiple-choice questions below.\n{}\n{}"
105
+ opt_title = ['A','B','C','D','E','F','G']
106
+ if isinstance(da['options'],str):
107
+ da['options'] = ast.literal_eval(da['options'])
108
+ option_str = '\n'.join(f'{opt}. {ops}' for opt,ops in zip(opt_title,da['options']))
109
+ return self.query_prompt.format(da['question'],option_str)
110
+
111
+ def OmniMedVQA_prompt(self,entity):
112
+ q_str = entity['question'] + f'Here are {len(entity["options"])} candidate answers:' + str(entity["options"])+' Only return what you think is the correct answer from the candidate answers, do not return any other irrelevant text!'
113
+ return q_str
114
+
115
+ def llava_prompt(self,da):
116
+ self.query_prompt = "{}\n{}\nAnswer with the option's letter from the given choices directly."
117
+ opt_title = ['A','B','C','D','E','F','G','H','I','J','K']
118
+ if isinstance(da['options'],str):
119
+ da['options'] = ast.literal_eval(da['options'])
120
+ option_str = '\n'.join(f'{opt}. {ops}' for opt,ops in zip(opt_title,da['options']))
121
+ return self.query_prompt.format(da['question'],option_str)
122
+
123
+ def __getitem__(self, index):
124
+ da = self.datas[index]
125
+ return {
126
+ 'data': da,
127
+ 'query': da['query'],
128
+ 'image': da['image']
129
+ }
130
+
131
+ def __len__(self):
132
+ return len(self.datas)
133
+
134
+ def collate_fn(self, batch):
135
+ out_batch = {}
136
+ out_batch['query'] = [x['query'] for x in batch]
137
+ out_batch['data'] = [x['data'] for x in batch]
138
+ out_batch['image'] = [x['image'] for x in batch]
139
+ return out_batch
140
+
141
+
142
+ def get_response(inputs,outputs,tokenizer,num_return):
143
+ responses_list=[]
144
+ batch_return=[]
145
+ for i, output in enumerate(outputs):
146
+ input_len = len(inputs[0])
147
+ generated_output = output[input_len:]
148
+ batch_return.append(tokenizer.decode(generated_output, skip_special_tokens=True))
149
+ if i%num_return==num_return-1:
150
+ responses_list.append(batch_return)
151
+ batch_return=[]
152
+ return responses_list
153
+
154
+ def table_to_csv_string(table):
155
+ rows = [",".join(table.columns)]
156
+ for row in table.data:
157
+ rows.append(",".join(map(str, row)))
158
+ return "\n".join(rows)
159
+
160
+
161
+ # ══════════════════════════════════════════════════════════════════════════════
162
+ # Top-K layer selection
163
+ # ══════════════════════════════════════════════════════════════════════════════
164
+
165
+ def _load_mean_div(pt_path):
166
+ data = torch.load(pt_path, map_location="cpu", weights_only=False)
167
+ if isinstance(data, torch.Tensor):
168
+ arr = data.float().numpy()
169
+ return arr if arr.ndim == 1 else arr.mean(axis=0)
170
+ stacked = np.stack([np.array(x) for x in data], axis=0)
171
+ return stacked.mean(axis=0)
172
+
173
+
174
+ def load_top_layers(pt_path, topk, pt_path_random=None):
175
+ mean = _load_mean_div(pt_path)
176
+ if pt_path_random is not None:
177
+ rand = _load_mean_div(pt_path_random)
178
+ diff = mean - rand
179
+ idx = np.argsort(diff)[::-1][:topk]
180
+ layers = [int(i) for i in idx]
181
+ print(f"[top-layers/diff] top-{topk}: {layers}")
182
+ return layers
183
+ idx = np.argsort(mean)[::-1][:topk]
184
+ layers = [int(i) for i in idx]
185
+ print(f"[top-layers] top-{topk}: {layers}")
186
+ return layers
187
+
188
+
189
+ def _parse_layer_list(s):
190
+ if s is None:
191
+ return None
192
+ if isinstance(s, int):
193
+ return [s]
194
+ return [int(x.strip()) for x in str(s).split(',') if x.strip()]
195
+
196
+
197
+ # ══════════════════════════════════════════════════════════════════════════════
198
+ # Attention forward utilities (manual RoPE + attention with pre-softmax key bias)
199
+ # ══════════════════════════════════════════════════════════════════════════════
200
+
201
+ def _rotate_half(x):
202
+ x1 = x[..., : x.shape[-1] // 2]
203
+ x2 = x[..., x.shape[-1] // 2 :]
204
+ return torch.cat((-x2, x1), dim=-1)
205
+
206
+
207
+ def _apply_rotary_pos_emb_local(q, k, cos, sin, unsqueeze_dim=1):
208
+ cos = cos.unsqueeze(unsqueeze_dim)
209
+ sin = sin.unsqueeze(unsqueeze_dim)
210
+ q_embed = (q * cos) + (_rotate_half(q) * sin)
211
+ k_embed = (k * cos) + (_rotate_half(k) * sin)
212
+ return q_embed, k_embed
213
+
214
+
215
+ def _repeat_kv_local(hidden_states, n_rep):
216
+ if n_rep == 1:
217
+ return hidden_states
218
+ bsz, n_kv_heads, slen, head_dim = hidden_states.shape
219
+ hidden_states = hidden_states[:, :, None, :, :].expand(
220
+ bsz, n_kv_heads, n_rep, slen, head_dim
221
+ )
222
+ return hidden_states.reshape(bsz, n_kv_heads * n_rep, slen, head_dim)
223
+
224
+
225
+ def _patch_attn_forward_with_key_bias(
226
+ attn_module, key_positions, tag: str = "",
227
+ bias_vec_fn=None):
228
+ key_positions = sorted({int(p) for p in key_positions if p is not None and int(p) >= 0})
229
+ old_forward = attn_module.forward
230
+
231
+ def _new_forward(self, hidden_states, attention_mask=None, position_ids=None,
232
+ past_key_value=None, output_attentions=False, use_cache=False,
233
+ cache_position=None, position_embeddings=None, **kwargs):
234
+ bsz, q_len, _ = hidden_states.size()
235
+
236
+ num_heads = getattr(self, "num_heads",
237
+ getattr(self.config, "num_attention_heads", None))
238
+ num_kv_heads = getattr(self, "num_key_value_heads",
239
+ getattr(self.config, "num_key_value_heads", num_heads))
240
+ head_dim = getattr(self, "head_dim",
241
+ hidden_states.shape[-1] // num_heads)
242
+ num_kv_groups = getattr(self, "num_key_value_groups",
243
+ num_heads // num_kv_heads)
244
+
245
+ query_states = self.q_proj(hidden_states)
246
+ key_states = self.k_proj(hidden_states)
247
+ value_states = self.v_proj(hidden_states)
248
+
249
+ query_states = query_states.view(bsz, q_len, num_heads, head_dim).transpose(1, 2)
250
+ key_states = key_states.view(bsz, q_len, num_kv_heads, head_dim).transpose(1, 2)
251
+ value_states = value_states.view(bsz, q_len, num_kv_heads, head_dim).transpose(1, 2)
252
+
253
+ if position_embeddings is None:
254
+ if not hasattr(self, "rotary_emb"):
255
+ return old_forward(hidden_states, attention_mask=attention_mask,
256
+ position_ids=position_ids, past_key_value=past_key_value,
257
+ output_attentions=output_attentions, use_cache=use_cache,
258
+ cache_position=cache_position, **kwargs)
259
+ kv_seq_len = key_states.shape[-2]
260
+ if past_key_value is not None:
261
+ try:
262
+ kv_seq_len += past_key_value.get_usable_length(
263
+ kv_seq_len, getattr(self, "layer_idx", 0))
264
+ except Exception:
265
+ try:
266
+ kv_seq_len += past_key_value.get_seq_length(
267
+ getattr(self, "layer_idx", 0))
268
+ except Exception:
269
+ pass
270
+ try:
271
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
272
+ except TypeError:
273
+ cos, sin = self.rotary_emb(value_states, position_ids)
274
+ else:
275
+ cos, sin = position_embeddings
276
+
277
+ try:
278
+ from transformers.models.qwen2.modeling_qwen2 import apply_rotary_pos_emb
279
+ try:
280
+ query_states, key_states = apply_rotary_pos_emb(
281
+ query_states, key_states, cos, sin, position_ids)
282
+ except TypeError:
283
+ query_states, key_states = apply_rotary_pos_emb(
284
+ query_states, key_states, cos, sin)
285
+ except Exception:
286
+ if position_ids is not None and getattr(cos, "dim", lambda: 0)() == 2:
287
+ cos_sel = cos[position_ids].to(dtype=query_states.dtype)
288
+ sin_sel = sin[position_ids].to(dtype=query_states.dtype)
289
+ query_states, key_states = _apply_rotary_pos_emb_local(
290
+ query_states, key_states, cos_sel, sin_sel)
291
+ else:
292
+ query_states, key_states = _apply_rotary_pos_emb_local(
293
+ query_states, key_states, cos, sin)
294
+
295
+ if past_key_value is not None:
296
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
297
+ key_states, value_states = past_key_value.update(
298
+ key_states, value_states, getattr(self, "layer_idx", 0), cache_kwargs)
299
+
300
+ key_states = _repeat_kv_local(key_states, num_kv_groups)
301
+ value_states = _repeat_kv_local(value_states, num_kv_groups)
302
+
303
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) \
304
+ / math.sqrt(head_dim)
305
+
306
+ if attention_mask is not None:
307
+ if attention_mask.dim() == 4:
308
+ causal_mask = attention_mask[:, :, :, :key_states.shape[-2]]
309
+ attn_weights = attn_weights + causal_mask
310
+ else:
311
+ attn_weights = attn_weights + attention_mask
312
+
313
+ kv_len = attn_weights.shape[-1]
314
+ valid_keys = [p for p in key_positions if p < kv_len]
315
+
316
+ # apply fine-grained bias before softmax if bias_vec_fn provided
317
+ if bias_vec_fn is not None:
318
+ bv = bias_vec_fn(valid_keys, kv_len).to(device=attn_weights.device, dtype=attn_weights.dtype)
319
+ if not getattr(self, f"_bias_printed_{tag}", False):
320
+ nonzero_pos = bv.nonzero(as_tuple=True)[0].tolist()
321
+ print(f"[AttnBias-{tag}] layer={getattr(self,'layer_idx','?')} "
322
+ f"kv_len={kv_len} nonzero={len(nonzero_pos)} positions: "
323
+ + ", ".join(f"{p}:{bv[p].item():.2f}" for p in nonzero_pos[:20])
324
+ + (" ..." if len(nonzero_pos) > 20 else ""))
325
+ setattr(self, f"_bias_printed_{tag}", True)
326
+ attn_weights[:, :, -1:, :] = attn_weights[:, :, -1:, :] + bv.view(1, 1, 1, kv_len)
327
+ # if not getattr(self, f"_bias_vec_printed_{tag}", False):
328
+ # print(f"[AttnBiasVec-{tag}] layer={getattr(self,'layer_idx','?')} kv_len={kv_len}")
329
+ # setattr(self, f"_bias_vec_printed_{tag}", True)
330
+
331
+ attn_weights = F.softmax(attn_weights, dim=-1,
332
+ dtype=torch.float32).to(query_states.dtype)
333
+
334
+ attn_weights = F.dropout(attn_weights,
335
+ p=getattr(self, "attention_dropout", 0.0),
336
+ training=self.training)
337
+ attn_output = torch.matmul(attn_weights, value_states)
338
+
339
+ if attn_output.size() != (bsz, num_heads, q_len, head_dim):
340
+ raise ValueError(
341
+ f"attn_output should be {(bsz, num_heads, q_len, head_dim)}, "
342
+ f"but is {attn_output.size()}"
343
+ )
344
+
345
+ attn_output = attn_output.transpose(1, 2).contiguous()
346
+ attn_output = attn_output.reshape(bsz, q_len, num_heads * head_dim)
347
+ attn_output = self.o_proj(attn_output)
348
+
349
+ if not output_attentions:
350
+ attn_weights = None
351
+ return attn_output, attn_weights, past_key_value
352
+
353
+ attn_module.forward = types.MethodType(_new_forward, attn_module)
354
+ return old_forward
355
+
356
+
357
+ def _get_attn_layers(bot):
358
+ try:
359
+ return [layer.self_attn for layer in bot.model.model.layers]
360
+ except AttributeError:
361
+ return [m for n, m in bot.model.named_modules()
362
+ if n.endswith(".self_attn") and hasattr(m, "q_proj")]
363
+
364
+
365
+ # ══════════════════════════════════════════════════════════════════════════════
366
+ # Step A: Extract key text token positions and option token positions
367
+ # ══════════════════════════════════════════════════════════════════════════════
368
+
369
+ def _get_attentions(output):
370
+ att = getattr(output, "attentions", None)
371
+ if att is None and isinstance(output, dict):
372
+ att = output.get("attentions")
373
+ if att is None:
374
+ raise RuntimeError("Model did not return attentions. Make sure eager attention is forced.")
375
+ return att
376
+
377
+
378
+ def _decode_token(tokenizer, token_id):
379
+ try:
380
+ return tokenizer.decode([int(token_id)], skip_special_tokens=True).strip().lower().lstrip("▁").strip()
381
+ except Exception:
382
+ return ""
383
+
384
+
385
+ def extract_key_positions(bot, prompt, image, question=None, attn_layer_indices=None, need_keywords=True):
386
+ """
387
+ Run one eager attention forward pass and return:
388
+ top_text_positions : [list[int]] — global positions of scispaCy keyword tokens (wrapped in a list)
389
+ all_text_positions : list[int] — all text token positions in the question segment
390
+ option_positions : list[int] — token positions of A./B./C./D. options
391
+ img_start : int
392
+ seq_len : int
393
+ attentions : tuple — all layer attentions, reused by Step B
394
+
395
+ need_keywords=False skips the scispaCy entity extraction below (img_start/seq_len/
396
+ option_positions are still computed — every intervention mode needs those), for use
397
+ by the "none" mode where keywords are never consumed.
398
+ """
399
+ text = bot.input_moderation(prompt)
400
+ text = bot.insert_image_placeholder(text, 1)
401
+ conv = bot.get_conv_without_history(text)
402
+ input_ids = bot.preprocess(conv, return_tensors="pt").unsqueeze(0).to(bot.device)
403
+ image_tensors = (torch.stack(bot.get_image_tensors([image]))
404
+ .to(dtype=torch.bfloat16).to(bot.device))
405
+
406
+ with torch.no_grad():
407
+ output = bot.model(input_ids, images=image_tensors,
408
+ output_attentions=True, output_hidden_states=False,
409
+ return_dict=True, use_cache=False)
410
+ attentions = _get_attentions(output)
411
+
412
+ ids_cpu = input_ids[0].cpu()
413
+ img_pos_list = torch.where(ids_cpu == -200)[0]
414
+ if img_pos_list.numel() == 0:
415
+ raise ValueError("Image placeholder token (-200) not found.")
416
+ img_start = int(img_pos_list[0].item())
417
+ seq_len = attentions[0].shape[-1]
418
+ vis_end = img_start + HUATUO_NUM_IMG_TOKENS
419
+
420
+ # expand single -200 placeholder to 576 tokens to align with actual sequence length
421
+ prefix = ids_cpu[:img_start]
422
+ img_fill = torch.full((HUATUO_NUM_IMG_TOKENS,), -200, dtype=ids_cpu.dtype)
423
+ suffix = ids_cpu[img_start + 1:]
424
+ ids_cpu = torch.cat([prefix, img_fill, suffix], dim=0)
425
+
426
+ # ── locate option token positions ────────────────────────────────────────
427
+ option_positions = []
428
+ first_option_pos = None
429
+ tokenizer = bot.tokenizer
430
+ text_ids = ids_cpu[vis_end:].tolist()
431
+ option_letters = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k'}
432
+ i = 0
433
+ while i < len(text_ids):
434
+ w = _decode_token(tokenizer, text_ids[i])
435
+ w_stripped = w.strip()
436
+ is_option = False
437
+
438
+ # must be preceded by a newline to avoid false positives inside words
439
+ # use raw decode (skip_special_tokens=False) to preserve \n
440
+ prev_raw = tokenizer.decode([text_ids[i - 1]], skip_special_tokens=False) if i > 0 else ""
441
+ cur_raw = tokenizer.decode([text_ids[i]], skip_special_tokens=False)
442
+ preceded_by_newline = '\n' in prev_raw or '\n' in cur_raw
443
+
444
+ # case 1: token is exactly a single letter e.g. "a", then next token contains "."
445
+ if preceded_by_newline and w_stripped.lower() in option_letters:
446
+ if i + 1 < len(text_ids) and '.' in _decode_token(tokenizer, text_ids[i + 1]):
447
+ is_option = True
448
+
449
+ # case 2: token is "a." or "A." (letter + dot, possibly with surrounding spaces)
450
+ if not is_option and preceded_by_newline and len(w_stripped) >= 2:
451
+ if w_stripped[0].lower() in option_letters and w_stripped[1] == '.':
452
+ is_option = True
453
+
454
+ if is_option:
455
+ if first_option_pos is None:
456
+ first_option_pos = vis_end + i
457
+ j = i
458
+ while j < len(text_ids):
459
+ option_positions.append(vis_end + j)
460
+ if '\n' in tokenizer.decode([text_ids[j]], skip_special_tokens=False):
461
+ break
462
+ j += 1
463
+ i += 1
464
+
465
+ text_end = first_option_pos if first_option_pos is not None else (seq_len - 1)
466
+ text_positions = list(range(vis_end, text_end))
467
+ if not text_positions:
468
+ text_positions = list(range(vis_end, seq_len - 1))
469
+
470
+ # print(f"[debug] first_option_pos={first_option_pos} text_positions count={len(list(range(vis_end, text_end if first_option_pos else seq_len-1)))}")
471
+ # for di in range(min(20, len(text_ids))):
472
+ # raw = tokenizer.decode([text_ids[di]], skip_special_tokens=False)
473
+ # print(f"[debug token] i={di} pos={vis_end+di} raw={repr(raw)}")
474
+ top_text_pos = []
475
+ sorted_ents = []
476
+ if need_keywords:
477
+ # ── scispaCy: extract medical entities from question, find their token positions ──
478
+ q_text = question if question else prompt
479
+ med_ents = _get_medical_entities(q_text)
480
+
481
+ pos_to_word = {}
482
+ for ti in text_positions:
483
+ if 0 <= ti < ids_cpu.shape[0]:
484
+ w = _decode_token(tokenizer, ids_cpu[ti].item())
485
+ if w:
486
+ pos_to_word[ti] = w
487
+
488
+ # build full text string with char-to-position mapping
489
+ # use raw decode (with ▁) to preserve word boundaries as spaces
490
+ full_text = ""
491
+ char_to_pos = []
492
+ for ti in text_positions:
493
+ if 0 <= ti < ids_cpu.shape[0]:
494
+ raw = tokenizer.decode([ids_cpu[ti].item()], skip_special_tokens=True)
495
+ # ▁ represents a space prefix in sentencepiece tokenizers
496
+ w = raw.replace("▁", " ").lower()
497
+ else:
498
+ w = ""
499
+ for _ in w:
500
+ char_to_pos.append(ti)
501
+ full_text += w
502
+ full_text_lower = full_text.lower()
503
+
504
+ def _find_entity_positions(ent):
505
+ ent_lower = ent.lower().strip()
506
+ idx = full_text_lower.find(ent_lower)
507
+ if idx == -1:
508
+ return []
509
+ end = idx + len(ent_lower)
510
+ # collect unique token positions covering this span
511
+ positions = []
512
+ seen_pos = set()
513
+ for ci in range(idx, min(end, len(char_to_pos))):
514
+ p = char_to_pos[ci]
515
+ if p not in seen_pos:
516
+ seen_pos.add(p)
517
+ positions.append(p)
518
+ return positions
519
+
520
+ # 每个实体词找到 token 位置,并用指定层注意力分数排序
521
+ ent_positions = {}
522
+ for ent in sorted(med_ents):
523
+ positions = _find_entity_positions(ent)
524
+ if positions:
525
+ ent_positions[ent] = positions
526
+
527
+ # 用 attn_layer_indices(调用方传入全部层)的注意力对实体词打分,取 top-k
528
+ if ent_positions and attn_layer_indices is not None and len(attn_layer_indices) > 0:
529
+ ent_scores = {}
530
+ for ent, positions in ent_positions.items():
531
+ valid_pos = [p for p in positions if p < seq_len]
532
+ if not valid_pos:
533
+ ent_scores[ent] = 0.0
534
+ continue
535
+ score_list = []
536
+ for layer in attn_layer_indices:
537
+ if layer < len(attentions):
538
+ # [1, heads, seq, seq] → 最后一个 query token 对这些位置的平均
539
+ att = attentions[layer][0, :, -1, valid_pos].float().mean().item()
540
+ score_list.append(att)
541
+ ent_scores[ent] = float(np.mean(score_list)) if score_list else 0.0
542
+ # 按分数降序,取 top-3
543
+ sorted_ents = sorted(ent_scores, key=lambda e: ent_scores[e], reverse=True)[:3]
544
+ print(f"[AttnRank] entity scores: { {e: f'{ent_scores[e]:.4f}' for e in sorted_ents} }")
545
+ else:
546
+ sorted_ents = list(ent_positions.keys())
547
+
548
+ for ent in sorted_ents:
549
+ top_text_pos.extend(ent_positions[ent])
550
+
551
+ # 确保疑问词 token 也被加入 key positions
552
+ wh_words = {'what', 'where', 'when', 'which', 'who', 'how'}
553
+ seen_pos = set(top_text_pos)
554
+ for ti in text_positions[:5]: # 只看问题前几个 token
555
+ if 0 <= ti < ids_cpu.shape[0]:
556
+ w = _decode_token(tokenizer, ids_cpu[ti].item())
557
+ if w.lower() in wh_words and ti not in seen_pos:
558
+ top_text_pos.append(ti)
559
+ seen_pos.add(ti)
560
+ print(f"[WH] added '{w}' at pos={ti}")
561
+ break
562
+
563
+ top_text_positions = [top_text_pos] if top_text_pos else [[]]
564
+ keywords = sorted_ents
565
+ return top_text_positions, text_positions, option_positions, img_start, seq_len, attentions, keywords
566
+
567
+
568
+ # ══════════════════════════════════════════════════════════════════════════════
569
+ # Step B: MedSAM3 visual localization
570
+ # ══════════════════════════════════════════════════════════════════════════════
571
+
572
+ def _bbox_to_patch_indices(bbox_xyxy, orig_size, img_pos, margin=2):
573
+ # cli.py's get_image_tensors() expand2square-pads the image to a square
574
+ # before resizing to the model's input grid, so bbox coords (in the
575
+ # original, unpadded image) must be shifted into the padded square's
576
+ # coordinate frame before converting to a patch fraction.
577
+ W, H = orig_size
578
+ side = max(W, H)
579
+ off_x = (side - W) // 2
580
+ off_y = (side - H) // 2
581
+ x1, y1, x2, y2 = bbox_xyxy
582
+ x1, x2 = x1 + off_x, x2 + off_x
583
+ y1, y2 = y1 + off_y, y2 + off_y
584
+ c1 = max(0, int(x1 / side * HUATUO_PATCHES) - margin)
585
+ r1 = max(0, int(y1 / side * HUATUO_PATCHES) - margin)
586
+ c2 = min(HUATUO_PATCHES - 1, int(x2 / side * HUATUO_PATCHES) + margin)
587
+ r2 = min(HUATUO_PATCHES - 1, int(y2 / side * HUATUO_PATCHES) + margin)
588
+ indices = []
589
+ for r in range(r1, r2 + 1):
590
+ for c in range(c1, c2 + 1):
591
+ indices.append(img_pos + r * HUATUO_PATCHES + c)
592
+ return indices
593
+
594
+
595
+ def _multi_bbox_to_patch_indices(bbox_list, orig_size, img_pos, margin=2):
596
+ seen, merged = set(), []
597
+ for bbox in bbox_list:
598
+ for idx in _bbox_to_patch_indices(bbox, orig_size, img_pos, margin):
599
+ if idx not in seen:
600
+ seen.add(idx)
601
+ merged.append(idx)
602
+ return merged
603
+
604
+
605
+ _vis_save_count = 0
606
+ _vis_save_dir = "vis_debug"
607
+
608
+
609
+ # ══════════════════════════════════════════════════════════════════════════════
610
+ # Step C: Attention intervention context manager
611
+ # ══════════════════════════════════════════════════════════════════════════════
612
+
613
+ class _AttnInterventionContext:
614
+ """
615
+ Within the with block, replaces attention forward of specified layers with a
616
+ pre-softmax key-bias intervention version.
617
+ both mode: key text tokens + option tokens + salient visual patches (union) get
618
+ a positive bias; all other positions get the non-key bias.
619
+ """
620
+ def __init__(self, bot, intervention,
621
+ top_text_positions=None,
622
+ all_text_positions=None,
623
+ option_positions=None,
624
+ attn_layer_indices_text=None,
625
+ key_bias_text=3.0, nonkey_bias_text=0.0,
626
+ img_pos=None, seq_len=None,
627
+ attn_layer_indices_vis=None,
628
+ key_bias_vis=3.0, nonkey_bias_vis=0.0,
629
+ vis_key_patches=None):
630
+ self._patched = []
631
+ self.intervention = intervention
632
+ self._img_pos = img_pos
633
+ self._option_positions = option_positions or []
634
+ all_layers = _get_attn_layers(bot)
635
+
636
+ # ── text-side keys: keyword tokens only (amplify, everything else unchanged) ─
637
+ seen, merged = set(), []
638
+ for ep in (top_text_positions or []):
639
+ for p in ep:
640
+ if p not in seen:
641
+ seen.add(p)
642
+ merged.append(p)
643
+ self._kw_positions = merged
644
+ self._all_text_positions = list(all_text_positions or [])
645
+ self._key_bias_text = float(key_bias_text)
646
+ self._nonkey_bias_text = float(nonkey_bias_text)
647
+ text_indices = [int(i) for i in (attn_layer_indices_text or []) if i is not None]
648
+ self._text_layers = [all_layers[i] for i in text_indices if 0 <= i < len(all_layers)]
649
+ self._text_layer_idx = [i for i in text_indices if 0 <= i < len(all_layers)]
650
+
651
+ # ── vis-side keys: SAM bbox patches only (amplify, everything else unchanged) ─
652
+ vis_seen, vis_merged = set(), []
653
+ for p in (vis_key_patches or []):
654
+ if p not in vis_seen:
655
+ vis_seen.add(p)
656
+ vis_merged.append(p)
657
+ self._vis_key_positions = vis_merged
658
+ self._key_bias_vis = float(key_bias_vis)
659
+ self._nonkey_bias_vis = float(nonkey_bias_vis)
660
+ vis_indices = [int(i) for i in (attn_layer_indices_vis or []) if i is not None]
661
+ self._vis_layers = [all_layers[i] for i in vis_indices if 0 <= i < len(all_layers)]
662
+ self._vis_layer_idx = [i for i in vis_indices if 0 <= i < len(all_layers)]
663
+
664
+ # ── both-mode keys: keyword tokens + SAM bbox patches (union) ────────
665
+ both_seen, both_merged = set(), []
666
+ for p in merged + vis_merged:
667
+ if p not in both_seen:
668
+ both_seen.add(p)
669
+ both_merged.append(p)
670
+ self._both_key_positions = both_merged
671
+
672
+ def __enter__(self):
673
+ if self.intervention == "none":
674
+ return self
675
+
676
+ img_pos = self._img_pos
677
+ img_set = set(range(img_pos, img_pos + HUATUO_NUM_IMG_TOKENS)) if img_pos is not None else set()
678
+ kw_set = set(self._kw_positions)
679
+ vis_set = set(self._vis_key_positions)
680
+ nonkey_img_set = img_set - vis_set
681
+
682
+ kbt = self._key_bias_text; nbt = self._nonkey_bias_text
683
+ kbv = self._key_bias_vis; nbv = self._nonkey_bias_vis
684
+
685
+ # precompute index tensors
686
+ all_text_set = set(self._all_text_positions)
687
+ nonkw_text_set = all_text_set - kw_set
688
+ kw_idx = torch.tensor(sorted(kw_set), dtype=torch.long) if kw_set else None
689
+ vis_idx = torch.tensor(sorted(vis_set), dtype=torch.long) if vis_set else None
690
+ nonkey_img_idx = torch.tensor(sorted(nonkey_img_set), dtype=torch.long) if nonkey_img_set else None
691
+ nonkw_text_idx = torch.tensor(sorted(nonkw_text_set), dtype=torch.long) if nonkw_text_set else None
692
+
693
+ if self.intervention == "text":
694
+ # default 0: prefix/suffix/prompt tokens untouched
695
+ # question non-keyword text: nbt, keyword text: kbt
696
+ def make_bias(key_positions, kv_len):
697
+ b = torch.zeros(kv_len)
698
+ if nonkw_text_idx is not None:
699
+ b[nonkw_text_idx[nonkw_text_idx < kv_len]] = nbt
700
+ if kw_idx is not None:
701
+ b[kw_idx[kw_idx < kv_len]] = kbt
702
+ return b
703
+ for layer in self._text_layers:
704
+ old_fwd = _patch_attn_forward_with_key_bias(
705
+ layer, self._kw_positions, tag="text",
706
+ bias_vec_fn=make_bias)
707
+ self._patched.append((layer, old_fwd))
708
+
709
+ elif self.intervention == "vis":
710
+ # key patches: +kbv, non-key patches: nbv, all text tokens: 0 (neutral)
711
+ def make_bias(key_positions, kv_len):
712
+ b = torch.zeros(kv_len)
713
+ if nonkey_img_idx is not None:
714
+ b[nonkey_img_idx[nonkey_img_idx < kv_len]] = nbv
715
+ if vis_idx is not None:
716
+ b[vis_idx[vis_idx < kv_len]] = kbv
717
+ return b
718
+ for layer in self._vis_layers:
719
+ old_fwd = _patch_attn_forward_with_key_bias(
720
+ layer, self._vis_key_positions, tag="vis",
721
+ bias_vec_fn=make_bias)
722
+ self._patched.append((layer, old_fwd))
723
+
724
+ elif self.intervention == "both":
725
+ # default 0: prefix/suffix/prompt/option tokens untouched
726
+ # question non-keyword text: nbt, keyword text: kbt
727
+ # non-key patches: nbv, key patches: kbv
728
+ def make_bias(key_positions, kv_len):
729
+ b = torch.zeros(kv_len)
730
+ if nonkw_text_idx is not None:
731
+ b[nonkw_text_idx[nonkw_text_idx < kv_len]] = nbt # non-keyword question text
732
+ if nonkey_img_idx is not None:
733
+ b[nonkey_img_idx[nonkey_img_idx < kv_len]] = nbv # non-key patches
734
+ if vis_idx is not None:
735
+ b[vis_idx[vis_idx < kv_len]] = kbv # key patches
736
+ if kw_idx is not None:
737
+ b[kw_idx[kw_idx < kv_len]] = kbt # keyword text
738
+ return b
739
+ all_tgt_layers = {id(l): l for l in set(self._text_layers + self._vis_layers)}
740
+ for _, layer in all_tgt_layers.items():
741
+ old_fwd = _patch_attn_forward_with_key_bias(
742
+ layer, self._both_key_positions, tag="both",
743
+ bias_vec_fn=make_bias)
744
+ self._patched.append((layer, old_fwd))
745
+
746
+ return self
747
+
748
+ def __exit__(self, *args):
749
+ for layer, old_fwd in self._patched:
750
+ layer.forward = old_fwd
751
+ for tag in ("text", "vis", "both"):
752
+ if hasattr(layer, f"_bias_printed_{tag}"):
753
+ delattr(layer, f"_bias_printed_{tag}")
754
+ self._patched = []
755
+
756
+
757
+ # ══════════════════════════════════════════════════════════════════════════════
758
+ # SAM bbox lookup helper
759
+ # ══════════════════════════════════════════════════════════════════════════════
760
+
761
+ def _set_attn_impl(model, impl):
762
+ for m in model.modules():
763
+ if hasattr(m, "_attn_implementation"):
764
+ m._attn_implementation = impl
765
+ if hasattr(m, "config") and hasattr(m.config, "_attn_implementation"):
766
+ m.config._attn_implementation = impl
767
+ model.config._attn_implementation = impl
768
+
769
+
770
+ def _get_sam_bbox_text(obj_name: str, pil_image, medsam3, max_bbox=1):
771
+ """Run SAM on a PIL image for obj_name, return at most max_bbox 'obj_name: [x1,y1,x2,y2]'
772
+ strings plus the combined segmentation mask (numpy array, or None if SAM produced no mask)."""
773
+ try:
774
+ bbox_list, mask, info = medsam3.predict_bbox(pil_image, obj_name)
775
+ if not bbox_list:
776
+ return [], None
777
+ lines = [f"{obj_name}: [{x1},{y1},{x2},{y2}]" for x1, y1, x2, y2 in bbox_list[:max_bbox]]
778
+ return lines, mask
779
+ except Exception as e:
780
+ print(f"[SAM] failed for '{obj_name}': {e}")
781
+ return [], None
782
+
783
+
784
+ def _build_objects_prompt(question: str, scispacy_keywords=None) -> str:
785
+ """Stage1 prompt: ask the model for SAM-segmentable objects only (no image caption).
786
+
787
+ scispacy_keywords are offered as candidates the model should prefer when they are
788
+ genuine segmentable structures; if none qualify (or more are needed), the model
789
+ fills the rest itself, up to 5 objects total.
790
+
791
+ Questions about the image's modality/scan type (e.g. "is this a CT or MRI?",
792
+ "what imaging technique was used?") have no segmentable target -- there is no
793
+ anatomical structure that "is" the modality. The prompt tells the model to reply
794
+ NONE for these instead of inventing organs/structures just to satisfy the format,
795
+ which would otherwise feed SAM a meaningless bbox.
796
+ """
797
+ exclusion_note = (
798
+ "A candidate only qualifies if SAM could draw a bounding box around it as a "
799
+ "distinct visual region -- a physical organ, bone, lesion, or anatomical "
800
+ "structure. Reject any candidate that is not itself a segmentable region: "
801
+ "directional/positional words (left, right, upper, lower, anterior, posterior, "
802
+ "proximal, distal, etc.), modifiers or descriptors (normal, abnormal, mild, "
803
+ "severe, etc.), symptoms, diagnoses, measurements, or image/modality properties "
804
+ "are NOT valid objects on their own, even if they appear in the question.\n"
805
+ )
806
+ if scispacy_keywords:
807
+ candidates_block = (
808
+ f"From the following candidate terms extracted from the question, "
809
+ f"select ONLY the ones that are themselves concrete anatomical structures "
810
+ f"or lesions visually present and segmentable in this image:\n"
811
+ f"Candidates: {', '.join(scispacy_keywords)}\n"
812
+ f"{exclusion_note}"
813
+ f"If none of the candidates qualify, or more relevant structures exist, "
814
+ f"you may add additional ones. List up to 5 total.\n"
815
+ )
816
+ else:
817
+ candidates_block = (
818
+ "Identify up to 5 anatomical structures or lesions most relevant to the "
819
+ "question that are visually present and physically segmentable in the image.\n"
820
+ f"{exclusion_note}"
821
+ )
822
+ return (
823
+ f"{candidates_block}"
824
+ f"Question: {question}\n"
825
+ "If the question is about the image's modality or scan type (e.g. CT vs MRI vs "
826
+ "X-ray vs ultrasound, or which imaging technique was used) rather than about a "
827
+ "specific anatomical structure or lesion, there is nothing to segment -- reply "
828
+ "with exactly: Objects: NONE\n"
829
+ "Otherwise reply with ONLY the object names, comma-separated, on a single line. "
830
+ "Use plain object names with no parentheses, no explanations, no extra text. "
831
+ "Format: Objects: <obj1>, <obj2>, ..."
832
+ )
833
+
834
+
835
+ def _parse_objects_response(response: str) -> list:
836
+ """Extract the object list from the Stage1 response, stripping any parenthetical asides.
837
+ Returns [] if the model replied NONE (e.g. modality/scan-type questions with no
838
+ segmentable target) -- the caller skips SAM entirely in that case."""
839
+ objects = []
840
+ for line in response.splitlines():
841
+ line = line.strip()
842
+ if line.lower().startswith("objects:"):
843
+ raw = line[len("objects:"):].strip()
844
+ if raw.strip().upper() == "NONE":
845
+ return []
846
+ objects = [_strip_parens(o) for o in raw.split(",") if _strip_parens(o)]
847
+ break
848
+ if not objects:
849
+ if response.strip().upper() == "NONE":
850
+ return []
851
+ objects = [o for o in (_strip_parens(o) for o in response.split(",")) if o]
852
+ return objects
853
+
854
+
855
+ # ══════════════════════════════════════════════════════════════════════════════
856
+ # test() — same structure as eval.py, only the inference call is replaced
857
+ # ══════════════════════════════════════════════════════════════════════════════
858
+
859
+ def test(args):
860
+ accelerator = Accelerator()
861
+ global _vis_save_dir
862
+ torch.cuda.set_device(accelerator.process_index)
863
+ accelerator.print(f'args:\n{args}')
864
+ _vis_save_dir = os.path.join(args.output_path, "vis_debug")
865
+
866
+ bot = HuatuoChatbot(args.model_path)
867
+ accelerator.print(f'load_finish')
868
+
869
+ bot.gen_kwargs['max_new_tokens'] = args.max_new_tokens
870
+
871
+ dataset = TestDataset(args, args.data_path)
872
+
873
+ if args.max_samples is not None:
874
+ dataset.datas = dataset.datas[:args.max_samples]
875
+
876
+ val_dataloader = DataLoader(dataset, batch_size=1, shuffle=False, drop_last=False, collate_fn=dataset.collate_fn)
877
+
878
+ val_dataloader = accelerator.prepare(val_dataloader)
879
+ accelerator.wait_for_everyone()
880
+
881
+ # Save code snapshot
882
+ if accelerator.is_main_process:
883
+ import shutil, glob as _glob
884
+ os.makedirs(args.output_path, exist_ok=True)
885
+ _snapshot_dir = os.path.join(args.output_path, '_snapshot')
886
+ os.makedirs(_snapshot_dir, exist_ok=True)
887
+ shutil.copy2(__file__, os.path.join(_snapshot_dir, os.path.basename(__file__)))
888
+ _sh_patterns = ('run_eval_attnbias_sam_*.sh', 'run_eval.sh', 'run_all_attnbias_sam.sh')
889
+ for _pattern in _sh_patterns:
890
+ for _sh in _glob.glob(os.path.join(os.path.dirname(__file__), _pattern)):
891
+ shutil.copy2(_sh, os.path.join(_snapshot_dir, os.path.basename(_sh)))
892
+ accelerator.print(f'[Snapshot] code snapshot saved to {_snapshot_dir}')
893
+
894
+ # Intervention layer selection
895
+ attn_layer_indices_text = _parse_layer_list(args.attn_layers_text)
896
+ if attn_layer_indices_text is None:
897
+ pt_path_text = args.pt_path_text or args.pt_path
898
+ if pt_path_text is None:
899
+ raise ValueError("Provide --attn_layers_text, or --pt_path/--pt_path_text to auto-select layers.")
900
+ attn_layer_indices_text = load_top_layers(
901
+ pt_path_text, args.attn_topk_text,
902
+ pt_path_random=args.pt_path_text_random or args.pt_path_random)
903
+
904
+ attn_layer_indices_vis = _parse_layer_list(args.attn_layers_vis)
905
+ if attn_layer_indices_vis is None:
906
+ if args.pt_path is None:
907
+ raise ValueError("Provide --attn_layers_vis, or --pt_path to auto-select layers.")
908
+ attn_layer_indices_vis = load_top_layers(
909
+ args.pt_path, args.attn_topk_vis, pt_path_random=args.pt_path_random)
910
+
911
+ accelerator.print(f'[layers] text={attn_layer_indices_text} vis={attn_layer_indices_vis}')
912
+
913
+ # entity scoring (extract_key_positions) always ranks over all layers,
914
+ # independent of the top-k layers selected above for the actual intervention
915
+ num_total_layers = len(_get_attn_layers(bot))
916
+ attn_layer_indices_score = list(range(num_total_layers))
917
+
918
+ # MedSAM3 initialization (only needed when SAM-based vis_patches actually feed the intervention)
919
+ _needs_sam = args.intervention in ("vis", "both")
920
+ medsam3 = None
921
+ if _needs_sam and args.medsam3_config:
922
+ try:
923
+ from medsam3_wrapper import MedSAM3Wrapper
924
+ except ImportError:
925
+ accelerator.print(
926
+ "[AttnBias] medsam3_wrapper.MedSAM3Wrapper not found; "
927
+ "continuing with medsam3=None (SAM bbox lookup degrades to the "
928
+ "full-image fallback in Stage2 below)."
929
+ )
930
+ MedSAM3Wrapper = None
931
+ if MedSAM3Wrapper is not None:
932
+ medsam3 = MedSAM3Wrapper(
933
+ config_path=args.medsam3_config,
934
+ device=args.medsam3_device or f"cuda:{accelerator.process_index}",
935
+ threshold=args.medsam3_threshold,
936
+ nms_iou=args.medsam3_nms_iou,
937
+ medsam3_dir=args.medsam3_dir,
938
+ )
939
+
940
+ # ── Pass 0: keyword extraction + Stage1 objects + SAM bbox for all samples (no VQA inference) ──
941
+ # Cache per-sample context: vis_patches, img_start, seq_len, orig_size
942
+ sample_list = []
943
+ with torch.no_grad():
944
+ dataloader_iterator = tqdm(val_dataloader, total=len(val_dataloader), desc="Stage1+SAM") if accelerator.is_main_process else val_dataloader
945
+ for batch in dataloader_iterator:
946
+ for da, query, image in zip(batch["data"], batch['query'], batch['image']):
947
+ image_paths = [os.path.join(os.path.dirname(args.data_path), x) for x in image]
948
+ for img in image_paths:
949
+ assert os.path.exists(img), f'{img} not exists'
950
+ img_path = image_paths[0] if image_paths else None
951
+ pil_img = Image.open(img_path).convert("RGB") if img_path else None
952
+
953
+ # extract img_start + keyword positions (eager forward; also needed for text/both)
954
+ orig_impl = bot.model.config._attn_implementation
955
+ _set_attn_impl(bot.model, "eager")
956
+ top_text_pos, all_text_pos, option_pos = [[]], [], []
957
+ keywords = []
958
+ img_start, seq_len = None, None
959
+ try:
960
+ top_text_pos, all_text_pos, option_pos, img_start, seq_len, _, keywords = \
961
+ extract_key_positions(bot, query, img_path, question=da.get('question', ''),
962
+ attn_layer_indices=attn_layer_indices_score,
963
+ need_keywords=(args.intervention != "none"))
964
+ except Exception as e:
965
+ print(f"[AttnBias] img_start extraction failed: {e}, using full-image fallback")
966
+ finally:
967
+ _set_attn_impl(bot.model, orig_impl)
968
+
969
+ print(f"[scispaCy] keywords: {keywords}")
970
+
971
+ # Stage1: ask the model for SAM-segmentable objects (scispaCy keywords as hint, no caption)
972
+ objects = []
973
+ if _needs_sam and medsam3 is not None and pil_img is not None:
974
+ _orig_max_new_tokens = bot.gen_kwargs.get("max_new_tokens", 32)
975
+ bot.gen_kwargs["max_new_tokens"] = 32
976
+ stage1_response = bot.inference(
977
+ _build_objects_prompt(da.get('question', '') or query, scispacy_keywords=keywords),
978
+ image_paths)
979
+ bot.gen_kwargs["max_new_tokens"] = _orig_max_new_tokens
980
+ stage1_text = stage1_response[0] if stage1_response else ""
981
+ objects = _parse_objects_response(stage1_text)
982
+ print(f"[Stage1] objects: {objects}")
983
+
984
+ # Stage2: SAM bbox + segmentation mask from Stage1 objects
985
+ all_bboxes = []
986
+ obj_masks = [] # [(obj_name, mask_ndarray), ...] -- one combined mask per object
987
+ if _needs_sam and medsam3 is not None and pil_img is not None:
988
+ for obj in objects[:10]:
989
+ lines, mask = _get_sam_bbox_text(obj, pil_img, medsam3, max_bbox=2)
990
+ for line in lines:
991
+ try:
992
+ coords = [int(v) for v in line.split("[")[1].rstrip("]").split(",")]
993
+ all_bboxes.append((obj, *coords))
994
+ except Exception:
995
+ pass
996
+ if mask is not None:
997
+ obj_masks.append((obj, mask))
998
+
999
+ # Visualization + mask persistence (only meaningful when SAM actually ran;
1000
+ # otherwise all_bboxes/obj_masks are always empty)
1001
+ global _vis_save_count
1002
+ if _needs_sam and pil_img is not None and _vis_save_count < 30:
1003
+ import matplotlib.pyplot as plt
1004
+ import matplotlib.patches as mpatches
1005
+ import matplotlib.colors as mcolors
1006
+ os.makedirs(_vis_save_dir, exist_ok=True)
1007
+
1008
+ # save each object's raw mask array, plus a combined mask across all objects
1009
+ for obj_name, mask in obj_masks:
1010
+ safe_name = re.sub(r"[^a-zA-Z0-9_-]+", "_", obj_name)[:40]
1011
+ np.save(os.path.join(_vis_save_dir,
1012
+ f"sam_{_vis_save_count:03d}_mask_{safe_name}.npy"), mask)
1013
+ if obj_masks:
1014
+ combined = obj_masks[0][1].astype(np.float32)
1015
+ for _, m in obj_masks[1:]:
1016
+ combined = np.maximum(combined, m.astype(np.float32))
1017
+ np.save(os.path.join(_vis_save_dir,
1018
+ f"sam_{_vis_save_count:03d}_mask_combined.npy"), combined)
1019
+
1020
+ fig, ax = plt.subplots(1, 1, figsize=(7, 7))
1021
+ ax.imshow(np.array(pil_img))
1022
+ colors = ["red", "lime", "cyan", "yellow", "magenta", "orange", "white", "blue"]
1023
+ # overlay each object's mask (semi-transparent) before drawing bbox/label
1024
+ for ci, (obj_name, mask) in enumerate(obj_masks):
1025
+ color = colors[ci % len(colors)]
1026
+ rgba = np.zeros((*mask.shape, 4))
1027
+ rgb = mcolors.to_rgb(color)
1028
+ rgba[..., :3] = rgb
1029
+ rgba[..., 3] = (mask > 0).astype(np.float32) * 0.45
1030
+ ax.imshow(rgba)
1031
+ for ci, entry in enumerate(all_bboxes):
1032
+ obj_name, x1, y1, x2, y2 = entry
1033
+ color = colors[ci % len(colors)]
1034
+ ax.add_patch(mpatches.Rectangle((x1, y1), x2-x1, y2-y1, linewidth=2, edgecolor=color, facecolor="none"))
1035
+ ax.text(x1, y1-4, obj_name, color=color, fontsize=7, bbox=dict(facecolor="black", alpha=0.4, pad=1))
1036
+ ax.set_title(f"objects: {objects}", fontsize=7, wrap=True)
1037
+ ax.axis("off")
1038
+ fig.savefig(os.path.join(_vis_save_dir, f"sam_{_vis_save_count:03d}.png"), dpi=120, bbox_inches="tight")
1039
+ plt.close(fig)
1040
+ _vis_save_count += 1
1041
+
1042
+ orig_size = pil_img.size if pil_img is not None else (1, 1)
1043
+ raw_bboxes = [[x1, y1, x2, y2] for (_, x1, y1, x2, y2) in all_bboxes]
1044
+ if not raw_bboxes and pil_img is not None:
1045
+ # No SAM result (e.g. SAM found nothing, or the question was a modality
1046
+ # question with no segmentable target -- see _build_objects_prompt).
1047
+ # Fall back to the bounding box of the non-zero (actual image content)
1048
+ # pixels rather than the full canvas, so black letterbox/background
1049
+ # padding common in medical scans isn't treated as "key region".
1050
+ W, H = orig_size
1051
+ img_arr = np.array(pil_img.convert("L"))
1052
+ ys, xs = np.where(img_arr > 0)
1053
+ if len(xs) > 0:
1054
+ raw_bboxes = [[int(xs.min()), int(ys.min()), int(xs.max()) + 1, int(ys.max()) + 1]]
1055
+ else:
1056
+ raw_bboxes = [[0, 0, W, H]]
1057
+ vis_patches = _multi_bbox_to_patch_indices(raw_bboxes, orig_size, img_start, margin=2) if img_start is not None else []
1058
+ print(f"[AttnBias] vis_patches={len(vis_patches)} from {len(raw_bboxes)} bboxes")
1059
+
1060
+ sample_list.append(dict(
1061
+ da=da, query=query, image_paths=image_paths, img_path=img_path,
1062
+ img_start=img_start, seq_len=seq_len,
1063
+ vis_patches=vis_patches, orig_size=orig_size,
1064
+ top_text_pos=top_text_pos, all_text_pos=all_text_pos,
1065
+ option_pos=option_pos, keywords=keywords, objects=objects,
1066
+ ))
1067
+
1068
+ # ── Helper: build intervention context (mode follows args.intervention; SAM vis_patches kept) ──
1069
+ def _make_attn_ctx(img_start, seq_len, vis_patches, top_text_pos=None, all_text_pos=None, option_pos=None):
1070
+ return _AttnInterventionContext(
1071
+ bot, args.intervention,
1072
+ top_text_positions=top_text_pos or [[]],
1073
+ all_text_positions=all_text_pos or [],
1074
+ option_positions=option_pos or [],
1075
+ attn_layer_indices_text=attn_layer_indices_text,
1076
+ key_bias_text=args.attn_key_bias_text,
1077
+ nonkey_bias_text=args.attn_nonkey_bias_text,
1078
+ img_pos=img_start, seq_len=seq_len,
1079
+ attn_layer_indices_vis=attn_layer_indices_vis,
1080
+ key_bias_vis=args.attn_key_bias_vis,
1081
+ nonkey_bias_vis=args.attn_nonkey_bias_vis,
1082
+ vis_key_patches=vis_patches,
1083
+ )
1084
+
1085
+ def _make_inputs(q, img_path):
1086
+ t = bot.input_moderation(q)
1087
+ t = bot.insert_image_placeholder(t, 1)
1088
+ cv = bot.get_conv_without_history(t)
1089
+ ids = bot.preprocess(cv, return_tensors="pt").unsqueeze(0).to(bot.device)
1090
+ imgs = (torch.stack(bot.get_image_tensors([img_path]))
1091
+ .to(dtype=torch.bfloat16).to(bot.device))
1092
+ return ids, imgs
1093
+
1094
+ orig_impl = bot.model.config._attn_implementation
1095
+
1096
+ # ── Pass 1+3: plain inference is only ever needed for "none" mode, or as a
1097
+ # fallback when img_start extraction failed for a sample -- for text/vis/both
1098
+ # with a successful extraction, the intervention pass below fully overwrites
1099
+ # it, so running it unconditionally for every sample would be wasted compute. ──
1100
+ set_seed(args.seed)
1101
+ with torch.no_grad():
1102
+ for s in tqdm(sample_list, desc="generate") if accelerator.is_main_process else sample_list:
1103
+ if args.intervention == "none" or s['img_start'] is None:
1104
+ s['da']['model_output'] = bot.inference(s['query'], s['image_paths'])[0]
1105
+ continue
1106
+ aug_ids, aug_imgs = _make_inputs(s['query'], s['img_path'])
1107
+ _set_attn_impl(bot.model, "eager")
1108
+ try:
1109
+ with torch.inference_mode():
1110
+ with _make_attn_ctx(s['img_start'], s['seq_len'], s['vis_patches'],
1111
+ top_text_pos=s['top_text_pos'], all_text_pos=s['all_text_pos'],
1112
+ option_pos=s['option_pos']):
1113
+ out_ids = bot.model.generate(aug_ids, images=aug_imgs, use_cache=True, **bot.gen_kwargs)
1114
+ finally:
1115
+ _set_attn_impl(bot.model, orig_impl)
1116
+ s['da']['model_output'] = bot.tokenizer.decode(out_ids[0], skip_special_tokens=True).strip()
1117
+
1118
+ torch.cuda.empty_cache()
1119
+ accelerator.wait_for_everyone()
1120
+
1121
+ cache_data = [s['da'] for s in sample_list]
1122
+ all_data = [None] * dist.get_world_size()
1123
+ dist.all_gather_object(all_data, cache_data)
1124
+ all_data = [item for sublist in all_data for item in sublist]
1125
+
1126
+ ress = all_data
1127
+
1128
+ if accelerator.is_main_process:
1129
+ import copy
1130
+ task_name = os.path.basename(args.model_path) + f'_{os.path.split(args.data_path)[-1].replace(".json","")}'+ f'_{args.intervention}'
1131
+
1132
+ def _save_and_score(ress_input, key, suffix):
1133
+ ress_copy = []
1134
+ for d in ress_input:
1135
+ dc = copy.deepcopy(d)
1136
+ dc['model_output'] = d.get(key, d['model_output'])
1137
+ ress_copy.append(dc)
1138
+ out_f = os.path.join(args.output_path, f'{task_name}{suffix}.json')
1139
+ with open(out_f, 'w') as fw:
1140
+ json.dump(ress_copy, fw, ensure_ascii=False, indent=2)
1141
+ val = score_mix_llava(ress_copy)
1142
+ accelerator.print(f'[{suffix}] {json.dumps(val, ensure_ascii=False, indent=2)}')
1143
+ with open(os.path.join(args.output_path, f'{task_name}{suffix}_result.json'), 'w') as fw:
1144
+ json.dump(val, fw, ensure_ascii=False, indent=2)
1145
+ print(f'{suffix} results: {out_f}')
1146
+
1147
+ print(f'question num: {len(ress)}')
1148
+ _save_and_score(ress, 'model_output', '')
1149
+
1150
+
1151
+ # ══════════════════════════════════════════════════════════════════════════════
1152
+ # Arguments — original eval.py args unchanged, intervention args added
1153
+ # ══════════════════════════════════════════════════════════════════════════════
1154
+
1155
+ if __name__ == '__main__':
1156
+ parser = argparse.ArgumentParser(description='Args of sft')
1157
+
1158
+ # Model Args
1159
+ parser.add_argument('--data_path', default='medical_multimodel_evaluation_data.json', type=str)
1160
+ parser.add_argument('--model_path', default='HuatuoGPT-Vision-7B', type=str)
1161
+ parser.add_argument('--max_new_tokens', default=256, type=int)
1162
+ parser.add_argument('--batch_size', default=2, type=int)
1163
+
1164
+ # Other Args
1165
+ parser.add_argument('--seed', default=42, type=int)
1166
+
1167
+ # Attention intervention Args
1168
+ parser.add_argument('--pt_path', type=str, default=None)
1169
+ parser.add_argument('--pt_path_random', type=str, default=None)
1170
+ parser.add_argument('--pt_path_text', type=str, default=None)
1171
+ parser.add_argument('--pt_path_text_random', type=str, default=None)
1172
+ parser.add_argument('--attn_layers_text', type=str, default=17)
1173
+ parser.add_argument('--attn_topk_text', type=int, default=1)
1174
+ parser.add_argument('--attn_layers_vis', type=str, default=17)
1175
+ parser.add_argument('--attn_topk_vis', type=int, default=1)
1176
+ parser.add_argument('--attn_key_bias_text', type=float, default=3.0)
1177
+ parser.add_argument('--attn_nonkey_bias_text', type=float, default=-3.0)
1178
+ parser.add_argument('--attn_key_bias_vis', type=float, default=3.0)
1179
+ parser.add_argument('--attn_nonkey_bias_vis', type=float, default=-3.0)
1180
+ parser.add_argument('--intervention', type=str, default='both', choices=['text', 'vis', 'both', 'none'])
1181
+ parser.add_argument('--medsam3_config', type=str, default=None)
1182
+ parser.add_argument('--medsam3_dir', type=str, default=None)
1183
+ parser.add_argument('--medsam3_device', type=str, default=None)
1184
+ parser.add_argument('--medsam3_threshold', type=float, default=0.3)
1185
+ parser.add_argument('--medsam3_nms_iou', type=float, default=0.5)
1186
+ parser.add_argument('--output_path', type=str, default='results_attnbias')
1187
+ parser.add_argument('--max_samples', type=int, default=None)
1188
+
1189
+ args = parser.parse_args()
1190
+
1191
+ set_seed(args.seed)
1192
+ test(args)
之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/HuatuoGPT-Vision/results_attnbias/HuatuoGPT-Vision-7B/sam_text/_snapshot/run_all_attnbias_sam.sh ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ cd "$(dirname "$0")"
3
+
4
+ # 先跑 baseline(无干预的 eval.py),再依次跑完 none / text / vis / both 四种干预模式
5
+ # 任意一个失败就停止,避免在错误的环境下继续浪费时间
6
+ set -e
7
+
8
+ # 默认使用 huatuovision conda 环境,不依赖调用者当前激活的环境
9
+ source "$(conda info --base)/etc/profile.d/conda.sh"
10
+ conda activate huatuovision
11
+
12
+ SCRIPTS=(
13
+ "run_eval.sh"
14
+ "run_eval_attnbias_sam_none.sh"
15
+ "run_eval_attnbias_sam_text.sh"
16
+ "run_eval_attnbias_sam_vis.sh"
17
+ "run_eval_attnbias_sam_both.sh"
18
+ )
19
+
20
+ for script in "${SCRIPTS[@]}"; do
21
+ echo "=================================================="
22
+ echo "[run_all] 开始运行 $script"
23
+ echo "=================================================="
24
+ bash "$script"
25
+ echo "[run_all] $script 运行完成"
26
+ done
27
+
28
+ echo "[run_all] 全部干预模式运行完成"
之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/HuatuoGPT-Vision/results_attnbias/HuatuoGPT-Vision-7B/sam_text/_snapshot/run_eval.sh ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ cd "$(dirname "$0")"
3
+
4
+ DATA_PATH="/home/jinhua/ExplainableVQA/benchmarks/Medical_Multimodal_Evaluation_Data/medical_multimodel_evaluation_data.json"
5
+ MODEL_PATH="FreedomIntelligence/HuatuoGPT-Vision-7B"
6
+
7
+ SEED=42
8
+ MAX_NEW_TOKENS=256
9
+
10
+ accelerate launch eval.py \
11
+ --data_path "$DATA_PATH" \
12
+ --model_path "$MODEL_PATH" \
13
+ --seed "$SEED" \
14
+ --max_new_tokens "$MAX_NEW_TOKENS"
之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/HuatuoGPT-Vision/results_attnbias/HuatuoGPT-Vision-7B/sam_text/_snapshot/run_eval_attnbias_sam_both.sh ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ cd "$(dirname "$0")"
3
+
4
+ DATA_PATH="/home/jinhua/ExplainableVQA/benchmarks/Medical_Multimodal_Evaluation_Data/medical_multimodel_evaluation_data.json"
5
+ MODEL_PATH="FreedomIntelligence/HuatuoGPT-Vision-7B"
6
+ OUTPUT_PATH="results_attnbias/HuatuoGPT-Vision-7B/sam_both"
7
+
8
+ SEED=42
9
+ MAX_NEW_TOKENS=256
10
+
11
+ MEDSAM3_CONFIG="/home/jinhua/ExplainableVQA/HuatuoGPT-Vision/MedSAM3/configs/full_lora_config.yaml"
12
+ MEDSAM3_DIR="/home/jinhua/ExplainableVQA/HuatuoGPT-Vision/MedSAM3"
13
+
14
+ # both mode: amplify scispaCy keyword tokens + SAM-bbox patches via pre-softmax bias
15
+ INTERVENTION="both"
16
+ ATTN_LAYERS_TEXT="17"
17
+ ATTN_KEY_BIAS_TEXT=4.0
18
+ ATTN_NONKEY_BIAS_TEXT=-4.0
19
+ ATTN_LAYERS_VIS="17"
20
+ ATTN_KEY_BIAS_VIS=1.0
21
+ ATTN_NONKEY_BIAS_VIS=-1.0
22
+
23
+ MAX_SAMPLES=""
24
+
25
+ accelerate launch eval_attnbias_sam.py \
26
+ --data_path "$DATA_PATH" \
27
+ --model_path "$MODEL_PATH" \
28
+ --seed "$SEED" \
29
+ --max_new_tokens "$MAX_NEW_TOKENS" \
30
+ --output_path "$OUTPUT_PATH" \
31
+ --intervention "$INTERVENTION" \
32
+ --attn_layers_text "$ATTN_LAYERS_TEXT" \
33
+ --attn_key_bias_text "$ATTN_KEY_BIAS_TEXT" \
34
+ --attn_nonkey_bias_text "$ATTN_NONKEY_BIAS_TEXT" \
35
+ --attn_layers_vis "$ATTN_LAYERS_VIS" \
36
+ --attn_key_bias_vis "$ATTN_KEY_BIAS_VIS" \
37
+ --attn_nonkey_bias_vis "$ATTN_NONKEY_BIAS_VIS" \
38
+ --medsam3_config "$MEDSAM3_CONFIG" \
39
+ --medsam3_dir "$MEDSAM3_DIR" \
40
+ ${MAX_SAMPLES:-}
之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/HuatuoGPT-Vision/results_attnbias/HuatuoGPT-Vision-7B/sam_text/_snapshot/run_eval_attnbias_sam_none.sh ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ cd "$(dirname "$0")"
3
+
4
+ DATA_PATH="/home/jinhua/ExplainableVQA/benchmarks/Medical_Multimodal_Evaluation_Data/medical_multimodel_evaluation_data.json"
5
+ MODEL_PATH="FreedomIntelligence/HuatuoGPT-Vision-7B"
6
+ OUTPUT_PATH="results_attnbias/HuatuoGPT-Vision-7B/sam_none"
7
+
8
+ SEED=42
9
+ MAX_NEW_TOKENS=256
10
+
11
+ MEDSAM3_CONFIG="/home/jinhua/ExplainableVQA/HuatuoGPT-Vision/MedSAM3/configs/full_lora_config.yaml"
12
+ MEDSAM3_DIR="/home/jinhua/ExplainableVQA/HuatuoGPT-Vision/MedSAM3"
13
+
14
+ # none: no attention intervention (model_output reuses plain inference result)
15
+ INTERVENTION="none"
16
+ ATTN_LAYERS_TEXT="17"
17
+ ATTN_KEY_BIAS_TEXT=4.0
18
+ ATTN_NONKEY_BIAS_TEXT=-4.0
19
+ ATTN_LAYERS_VIS="17"
20
+ ATTN_KEY_BIAS_VIS=1.0
21
+ ATTN_NONKEY_BIAS_VIS=-1.0
22
+
23
+ MAX_SAMPLES=""
24
+
25
+ accelerate launch eval_attnbias_sam.py \
26
+ --data_path "$DATA_PATH" \
27
+ --model_path "$MODEL_PATH" \
28
+ --seed "$SEED" \
29
+ --max_new_tokens "$MAX_NEW_TOKENS" \
30
+ --output_path "$OUTPUT_PATH" \
31
+ --intervention "$INTERVENTION" \
32
+ --attn_layers_text "$ATTN_LAYERS_TEXT" \
33
+ --attn_key_bias_text "$ATTN_KEY_BIAS_TEXT" \
34
+ --attn_nonkey_bias_text "$ATTN_NONKEY_BIAS_TEXT" \
35
+ --attn_layers_vis "$ATTN_LAYERS_VIS" \
36
+ --attn_key_bias_vis "$ATTN_KEY_BIAS_VIS" \
37
+ --attn_nonkey_bias_vis "$ATTN_NONKEY_BIAS_VIS" \
38
+ --medsam3_config "$MEDSAM3_CONFIG" \
39
+ --medsam3_dir "$MEDSAM3_DIR" \
40
+ ${MAX_SAMPLES:-}
之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/HuatuoGPT-Vision/results_attnbias/HuatuoGPT-Vision-7B/sam_text/_snapshot/run_eval_attnbias_sam_text.sh ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ cd "$(dirname "$0")"
3
+
4
+ DATA_PATH="/home/jinhua/ExplainableVQA/benchmarks/Medical_Multimodal_Evaluation_Data/medical_multimodel_evaluation_data.json"
5
+ MODEL_PATH="FreedomIntelligence/HuatuoGPT-Vision-7B"
6
+ OUTPUT_PATH="results_attnbias/HuatuoGPT-Vision-7B/sam_text"
7
+
8
+ SEED=42
9
+ MAX_NEW_TOKENS=256
10
+
11
+ MEDSAM3_CONFIG="/home/jinhua/ExplainableVQA/HuatuoGPT-Vision/MedSAM3/configs/full_lora_config.yaml"
12
+ MEDSAM3_DIR="/home/jinhua/ExplainableVQA/HuatuoGPT-Vision/MedSAM3"
13
+
14
+ # text mode: amplify scispaCy keyword tokens only via pre-softmax bias
15
+ INTERVENTION="text"
16
+ ATTN_LAYERS_TEXT="17"
17
+ ATTN_KEY_BIAS_TEXT=4.0
18
+ ATTN_NONKEY_BIAS_TEXT=-4.0
19
+ ATTN_LAYERS_VIS="17"
20
+ ATTN_KEY_BIAS_VIS=1.0
21
+ ATTN_NONKEY_BIAS_VIS=-1.0
22
+
23
+ MAX_SAMPLES=""
24
+
25
+ accelerate launch eval_attnbias_sam.py \
26
+ --data_path "$DATA_PATH" \
27
+ --model_path "$MODEL_PATH" \
28
+ --seed "$SEED" \
29
+ --max_new_tokens "$MAX_NEW_TOKENS" \
30
+ --output_path "$OUTPUT_PATH" \
31
+ --intervention "$INTERVENTION" \
32
+ --attn_layers_text "$ATTN_LAYERS_TEXT" \
33
+ --attn_key_bias_text "$ATTN_KEY_BIAS_TEXT" \
34
+ --attn_nonkey_bias_text "$ATTN_NONKEY_BIAS_TEXT" \
35
+ --attn_layers_vis "$ATTN_LAYERS_VIS" \
36
+ --attn_key_bias_vis "$ATTN_KEY_BIAS_VIS" \
37
+ --attn_nonkey_bias_vis "$ATTN_NONKEY_BIAS_VIS" \
38
+ --medsam3_config "$MEDSAM3_CONFIG" \
39
+ --medsam3_dir "$MEDSAM3_DIR" \
40
+ ${MAX_SAMPLES:-}
之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/HuatuoGPT-Vision/results_attnbias/HuatuoGPT-Vision-7B/sam_text/_snapshot/run_eval_attnbias_sam_vis.sh ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ cd "$(dirname "$0")"
3
+
4
+ DATA_PATH="/home/jinhua/ExplainableVQA/benchmarks/Medical_Multimodal_Evaluation_Data/medical_multimodel_evaluation_data.json"
5
+ MODEL_PATH="FreedomIntelligence/HuatuoGPT-Vision-7B"
6
+ OUTPUT_PATH="results_attnbias/HuatuoGPT-Vision-7B/sam_vis"
7
+
8
+ SEED=42
9
+ MAX_NEW_TOKENS=256
10
+
11
+ MEDSAM3_CONFIG="/home/jinhua/ExplainableVQA/HuatuoGPT-Vision/MedSAM3/configs/full_lora_config.yaml"
12
+ MEDSAM3_DIR="/home/jinhua/ExplainableVQA/HuatuoGPT-Vision/MedSAM3"
13
+
14
+ # vis mode: amplify SAM-bbox patches only via pre-softmax bias
15
+ INTERVENTION="vis"
16
+ ATTN_LAYERS_TEXT="17"
17
+ ATTN_KEY_BIAS_TEXT=4.0
18
+ ATTN_NONKEY_BIAS_TEXT=-4.0
19
+ ATTN_LAYERS_VIS="17"
20
+ ATTN_KEY_BIAS_VIS=1.0
21
+ ATTN_NONKEY_BIAS_VIS=-1.0
22
+
23
+ MAX_SAMPLES=""
24
+
25
+ accelerate launch eval_attnbias_sam.py \
26
+ --data_path "$DATA_PATH" \
27
+ --model_path "$MODEL_PATH" \
28
+ --seed "$SEED" \
29
+ --max_new_tokens "$MAX_NEW_TOKENS" \
30
+ --output_path "$OUTPUT_PATH" \
31
+ --intervention "$INTERVENTION" \
32
+ --attn_layers_text "$ATTN_LAYERS_TEXT" \
33
+ --attn_key_bias_text "$ATTN_KEY_BIAS_TEXT" \
34
+ --attn_nonkey_bias_text "$ATTN_NONKEY_BIAS_TEXT" \
35
+ --attn_layers_vis "$ATTN_LAYERS_VIS" \
36
+ --attn_key_bias_vis "$ATTN_KEY_BIAS_VIS" \
37
+ --attn_nonkey_bias_vis "$ATTN_NONKEY_BIAS_VIS" \
38
+ --medsam3_config "$MEDSAM3_CONFIG" \
39
+ --medsam3_dir "$MEDSAM3_DIR" \
40
+ ${MAX_SAMPLES:-}
之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/HuatuoGPT-Vision/results_attnbias/HuatuoGPT-Vision-7B/sam_vis/_snapshot/run_eval_attnbias_sam_none.sh ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ cd "$(dirname "$0")"
3
+
4
+ DATA_PATH="/home/jinhua/ExplainableVQA/benchmarks/Medical_Multimodal_Evaluation_Data/medical_multimodel_evaluation_data.json"
5
+ MODEL_PATH="FreedomIntelligence/HuatuoGPT-Vision-7B"
6
+ OUTPUT_PATH="results_attnbias/HuatuoGPT-Vision-7B/sam_none"
7
+
8
+ SEED=42
9
+ MAX_NEW_TOKENS=256
10
+
11
+ MEDSAM3_CONFIG="/home/jinhua/ExplainableVQA/HuatuoGPT-Vision/MedSAM3/configs/full_lora_config.yaml"
12
+ MEDSAM3_DIR="/home/jinhua/ExplainableVQA/HuatuoGPT-Vision/MedSAM3"
13
+
14
+ # none: no attention intervention (model_output reuses plain inference result)
15
+ INTERVENTION="none"
16
+ ATTN_LAYERS_TEXT="17"
17
+ ATTN_KEY_BIAS_TEXT=4.0
18
+ ATTN_NONKEY_BIAS_TEXT=-4.0
19
+ ATTN_LAYERS_VIS="17"
20
+ ATTN_KEY_BIAS_VIS=1.0
21
+ ATTN_NONKEY_BIAS_VIS=-1.0
22
+
23
+ MAX_SAMPLES=""
24
+
25
+ accelerate launch eval_attnbias_sam.py \
26
+ --data_path "$DATA_PATH" \
27
+ --model_path "$MODEL_PATH" \
28
+ --seed "$SEED" \
29
+ --max_new_tokens "$MAX_NEW_TOKENS" \
30
+ --output_path "$OUTPUT_PATH" \
31
+ --intervention "$INTERVENTION" \
32
+ --attn_layers_text "$ATTN_LAYERS_TEXT" \
33
+ --attn_key_bias_text "$ATTN_KEY_BIAS_TEXT" \
34
+ --attn_nonkey_bias_text "$ATTN_NONKEY_BIAS_TEXT" \
35
+ --attn_layers_vis "$ATTN_LAYERS_VIS" \
36
+ --attn_key_bias_vis "$ATTN_KEY_BIAS_VIS" \
37
+ --attn_nonkey_bias_vis "$ATTN_NONKEY_BIAS_VIS" \
38
+ --medsam3_config "$MEDSAM3_CONFIG" \
39
+ --medsam3_dir "$MEDSAM3_DIR" \
40
+ ${MAX_SAMPLES:-}