Master-Shi commited on
Commit
a7465ce
·
verified ·
1 Parent(s): 411cdef

Add files using upload-large-folder tool

Browse files
Files changed (20) hide show
  1. HuatuoGPT-Vision-Abla-New/llava/__pycache__/constants.cpython-310.pyc +0 -0
  2. HuatuoGPT-Vision-Abla-New/llava/model/__pycache__/llava_arch.cpython-310.pyc +0 -0
  3. HuatuoGPT-Vision-Abla-New/llava/model/language_model/__pycache__/llava_qwen2.cpython-310.pyc +0 -0
  4. HuatuoGPT-Vision-Abla-New/llava/model/language_model/llava_llama.py +170 -0
  5. HuatuoGPT-Vision-Abla-New/llava/model/language_model/llava_qwen2.py +168 -0
  6. HuatuoGPT-Vision-Abla-New/llava/model/multimodal_encoder/__pycache__/builder.cpython-310.pyc +0 -0
  7. HuatuoGPT-Vision-Abla-New/llava/model/multimodal_encoder/__pycache__/clip_encoder.cpython-310.pyc +0 -0
  8. HuatuoGPT-Vision-Abla-New/llava/model/multimodal_encoder/builder.py +15 -0
  9. HuatuoGPT-Vision-Abla-New/llava/model/multimodal_encoder/clip_encoder.py +92 -0
  10. HuatuoGPT-Vision-Abla-New/llava/model/multimodal_encoder/clip_encoder_larger_input.py +230 -0
  11. HuatuoGPT-Vision-Abla-New/llava/model/multimodal_projector/__pycache__/builder.cpython-310.pyc +0 -0
  12. HuatuoGPT-Vision-Abla-New/llava/model/multimodal_projector/builder.py +51 -0
  13. HuatuoGPT-Vision-Abla-New/results_attnbias/HuatuoGPT-Vision-7B/sam_both/HuatuoGPT-Vision-7B_medical_multimodel_evaluation_data_both_Lt17_kt5.0_nt0.0_Lv17_kv1.0_nv0.0.json +0 -0
  14. HuatuoGPT-Vision-Abla-New/results_attnbias/HuatuoGPT-Vision-7B/sam_both/HuatuoGPT-Vision-7B_medical_multimodel_evaluation_data_both_Lt17_kt5.0_nt0.0_Lv17_kv1.0_nv0.0_result.json +22 -0
  15. HuatuoGPT-Vision-Abla-New/results_attnbias/HuatuoGPT-Vision-7B/sam_both/_snapshot/run_ablation_grid_layer.sh +120 -0
  16. HuatuoGPT-Vision-Abla-New/results_attnbias/HuatuoGPT-Vision-7B/sam_both/_snapshot/run_ablation_grid_layer_worker.sh +144 -0
  17. HuatuoGPT-Vision-Abla-New/results_attnbias/HuatuoGPT-Vision-7B/sam_both/_snapshot/run_ablation_grid_pick.sh +68 -0
  18. HuatuoGPT-Vision-Abla-New/results_attnbias/HuatuoGPT-Vision-7B/sam_both/_snapshot/run_all_attnbias_sam.sh +35 -0
  19. HuatuoGPT-Vision-Abla-New/results_attnbias/HuatuoGPT-Vision-7B/sam_both/_snapshot/run_eval_attnbias_sam_both.sh +48 -0
  20. HuatuoGPT-Vision-Abla-New/results_attnbias/HuatuoGPT-Vision-7B/sam_both/_snapshot/run_eval_attnbias_sam_text.sh +41 -0
HuatuoGPT-Vision-Abla-New/llava/__pycache__/constants.cpython-310.pyc ADDED
Binary file (514 Bytes). View file
 
HuatuoGPT-Vision-Abla-New/llava/model/__pycache__/llava_arch.cpython-310.pyc ADDED
Binary file (13.9 kB). View file
 
HuatuoGPT-Vision-Abla-New/llava/model/language_model/__pycache__/llava_qwen2.cpython-310.pyc ADDED
Binary file (3.95 kB). View file
 
HuatuoGPT-Vision-Abla-New/llava/model/language_model/llava_llama.py ADDED
@@ -0,0 +1,170 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 Haotian Liu
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ # import sys
16
+ # sys.path.insert(0, '/opt/conda/lib/python3.10')
17
+ # print(sys.path)
18
+ from typing import List, Optional, Tuple, Union
19
+
20
+ import torch
21
+ import torch.nn as nn
22
+
23
+ from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer, \
24
+ LlamaConfig, LlamaModel, LlamaForCausalLM
25
+
26
+
27
+ from transformers.modeling_outputs import CausalLMOutputWithPast
28
+
29
+ from ..llava_arch import LlavaMetaModel, LlavaMetaForCausalLM
30
+
31
+
32
+ class LlavaConfig(LlamaConfig):
33
+ model_type = "llava_llama"
34
+
35
+
36
+ class LlavaLlamaModel(LlavaMetaModel, LlamaModel):
37
+ config_class = LlavaConfig
38
+
39
+ def __init__(self, config: LlamaConfig):
40
+ super(LlavaLlamaModel, self).__init__(config)
41
+
42
+
43
+ class LlavaLlamaForCausalLM(LlamaForCausalLM, LlavaMetaForCausalLM):
44
+ config_class = LlavaConfig
45
+
46
+ def __init__(self, config, init_vision_encoder_from_ckpt=False):
47
+ config._attn_implementation = "flash_attention_2"
48
+ config._flash_attn_2_enabled = True
49
+ super(LlamaForCausalLM, self).__init__(config)
50
+ self.model = LlavaLlamaModel(config)
51
+ # assert self.model._use_flash_attention_2 == True
52
+ self.tokenizer = AutoTokenizer.from_pretrained(config._name_or_path,padding_side="left")
53
+ self.pretraining_tp = config.pretraining_tp
54
+ self.vocab_size = config.vocab_size
55
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
56
+
57
+ # if getattr(config, 'init_vision_encoder_from_ckpt', True):
58
+ if init_vision_encoder_from_ckpt:
59
+ vision_tower = self.get_vision_tower()
60
+ print(f'loading from CLIP first. This should only be used at inference!!!')
61
+ vision_tower.load_model() #
62
+
63
+ # Initialize weights and apply final processing
64
+ self.post_init()
65
+
66
+ def get_model(self):
67
+ return self.model
68
+
69
+ def get_tokenizer(self):
70
+ return self.tokenizer
71
+
72
+ def forward(
73
+ self,
74
+ input_ids: torch.LongTensor = None,
75
+ attention_mask: Optional[torch.Tensor] = None,
76
+ position_ids: Optional[torch.LongTensor] = None,
77
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
78
+ inputs_embeds: Optional[torch.FloatTensor] = None,
79
+ labels: Optional[torch.LongTensor] = None,
80
+ use_cache: Optional[bool] = None,
81
+ output_attentions: Optional[bool] = None,
82
+ output_hidden_states: Optional[bool] = None,
83
+ images: Optional[torch.FloatTensor] = None,
84
+ return_dict: Optional[bool] = None,
85
+ cache_position = None
86
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
87
+
88
+ if inputs_embeds is None:
89
+ (
90
+ input_ids,
91
+ position_ids,
92
+ attention_mask,
93
+ past_key_values,
94
+ inputs_embeds,
95
+ labels
96
+ # ) = self.prepare_inputs_labels_for_multimodal(
97
+ ) = self.prepare_inputs_labels_for_multimodal_new(
98
+ input_ids,
99
+ position_ids,
100
+ attention_mask,
101
+ past_key_values,
102
+ labels,
103
+ images
104
+ )
105
+
106
+ return super().forward(
107
+ input_ids=input_ids,
108
+ attention_mask=attention_mask,
109
+ position_ids=position_ids,
110
+ past_key_values=past_key_values,
111
+ inputs_embeds=inputs_embeds,
112
+ labels=labels,
113
+ use_cache=use_cache,
114
+ output_attentions=output_attentions,
115
+ output_hidden_states=output_hidden_states,
116
+ return_dict=return_dict,
117
+ cache_position = cache_position
118
+ )
119
+
120
+ @torch.no_grad()
121
+ def generate(
122
+ self,
123
+ inputs: Optional[torch.Tensor] = None,
124
+ images: Optional[torch.Tensor] = None,
125
+ **kwargs,
126
+ ) :
127
+ position_ids = kwargs.pop("position_ids", None)
128
+ attention_mask = kwargs.pop("attention_mask", None)
129
+ if "inputs_embeds" in kwargs:
130
+ raise NotImplementedError("`inputs_embeds` is not supported")
131
+
132
+ if images is not None:
133
+ (
134
+ inputs,
135
+ position_ids,
136
+ attention_mask,
137
+ _,
138
+ inputs_embeds,
139
+ _
140
+ ) = self.prepare_inputs_labels_for_multimodal_new(
141
+ inputs,
142
+ position_ids,
143
+ attention_mask,
144
+ None,
145
+ None,
146
+ images
147
+ )
148
+ else:
149
+ inputs_embeds = self.get_model().embed_tokens(inputs)
150
+
151
+ # print(inputs_embeds.shape)
152
+ return super().generate(
153
+ position_ids=None,
154
+ attention_mask=None,
155
+ inputs_embeds=inputs_embeds,
156
+ **kwargs
157
+ )
158
+
159
+ def prepare_inputs_for_generation(self, input_ids, past_key_values=None, inputs_embeds=None, **kwargs):
160
+ images = kwargs.pop("images", None)
161
+ _inputs = super().prepare_inputs_for_generation(
162
+ input_ids, past_key_values=past_key_values, inputs_embeds=inputs_embeds, **kwargs
163
+ )
164
+ if images is not None:
165
+ _inputs['images'] = images
166
+ return _inputs
167
+
168
+ # AutoConfig.register("llava", LlavaConfig)
169
+ AutoConfig.register("llava_llama", LlavaConfig)
170
+ AutoModelForCausalLM.register(LlavaConfig, LlavaLlamaForCausalLM)
HuatuoGPT-Vision-Abla-New/llava/model/language_model/llava_qwen2.py ADDED
@@ -0,0 +1,168 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 Haotian Liu
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ # import sys
16
+ # sys.path.insert(0, '/opt/conda/lib/python3.10')
17
+ # print(sys.path)
18
+ from typing import List, Optional, Tuple, Union
19
+
20
+ import torch
21
+ import torch.nn as nn
22
+
23
+ from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer, \
24
+ Qwen2ForCausalLM, Qwen2Config, Qwen2Model \
25
+
26
+ from transformers.modeling_outputs import CausalLMOutputWithPast
27
+
28
+ from ..llava_arch import LlavaMetaModel, LlavaMetaForCausalLM
29
+
30
+
31
+ class LlavaQwenConfig(Qwen2Config):
32
+ model_type = "llava_qwen2"
33
+
34
+
35
+ class LlavaQwen2Model(LlavaMetaModel, Qwen2Model):
36
+ config_class = LlavaQwenConfig
37
+
38
+ def __init__(self, config: Qwen2Config):
39
+ super(LlavaQwen2Model, self).__init__(config)
40
+
41
+
42
+ class LlavaQwen2ForCausalLM(Qwen2ForCausalLM, LlavaMetaForCausalLM):
43
+ config_class = LlavaQwenConfig
44
+
45
+ def __init__(self, config, init_vision_encoder_from_ckpt=False):
46
+ # config._attn_implementation = "flash_attention_2"
47
+ # config._flash_attn_2_enabled = True
48
+ super(Qwen2ForCausalLM, self).__init__(config)
49
+ self.model = LlavaQwen2Model(config)
50
+ # assert self.model._use_flash_attention_2 == True
51
+ # self.tokenizer = AutoTokenizer.from_pretrained(config._name_or_path,padding_side="left")
52
+ self.tokenizer = None
53
+ # self.pretraining_tp = config.pretraining_tp
54
+ self.vocab_size = config.vocab_size
55
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
56
+
57
+ # if getattr(config, 'init_vision_encoder_from_ckpt', True):
58
+ if init_vision_encoder_from_ckpt:
59
+ vision_tower = self.get_vision_tower()
60
+ print(f'loading from CLIP first. This should only be used at inference!!!')
61
+ vision_tower.load_model() #
62
+
63
+ # Initialize weights and apply final processing
64
+ self.post_init()
65
+
66
+ def get_model(self):
67
+ return self.model
68
+
69
+ def get_tokenizer(self):
70
+ return self.tokenizer
71
+
72
+ def forward(
73
+ self,
74
+ input_ids: torch.LongTensor = None,
75
+ attention_mask: Optional[torch.Tensor] = None,
76
+ position_ids: Optional[torch.LongTensor] = None,
77
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
78
+ inputs_embeds: Optional[torch.FloatTensor] = None,
79
+ labels: Optional[torch.LongTensor] = None,
80
+ use_cache: Optional[bool] = None,
81
+ output_attentions: Optional[bool] = None,
82
+ output_hidden_states: Optional[bool] = None,
83
+ images: Optional[torch.FloatTensor] = None,
84
+ return_dict: Optional[bool] = None,
85
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
86
+
87
+ if inputs_embeds is None:
88
+ (
89
+ input_ids,
90
+ position_ids,
91
+ attention_mask,
92
+ past_key_values,
93
+ inputs_embeds,
94
+ labels
95
+ # ) = self.prepare_inputs_labels_for_multimodal(
96
+ ) = self.prepare_inputs_labels_for_multimodal_new(
97
+ input_ids,
98
+ position_ids,
99
+ attention_mask,
100
+ past_key_values,
101
+ labels,
102
+ images
103
+ )
104
+
105
+ return super().forward(
106
+ input_ids=input_ids,
107
+ attention_mask=attention_mask,
108
+ position_ids=position_ids,
109
+ past_key_values=past_key_values,
110
+ inputs_embeds=inputs_embeds,
111
+ labels=labels,
112
+ use_cache=use_cache,
113
+ output_attentions=output_attentions,
114
+ output_hidden_states=output_hidden_states,
115
+ return_dict=return_dict
116
+ )
117
+
118
+ @torch.no_grad()
119
+ def generate(
120
+ self,
121
+ inputs: Optional[torch.Tensor] = None,
122
+ images: Optional[torch.Tensor] = None,
123
+ **kwargs,
124
+ ) :
125
+ position_ids = kwargs.pop("position_ids", None)
126
+ attention_mask = kwargs.pop("attention_mask", None)
127
+ if "inputs_embeds" in kwargs:
128
+ raise NotImplementedError("`inputs_embeds` is not supported")
129
+
130
+ if images is not None:
131
+ (
132
+ inputs,
133
+ position_ids,
134
+ attention_mask,
135
+ _,
136
+ inputs_embeds,
137
+ _
138
+ ) = self.prepare_inputs_labels_for_multimodal_new(
139
+ inputs,
140
+ position_ids,
141
+ attention_mask,
142
+ None,
143
+ None,
144
+ images
145
+ )
146
+ else:
147
+ inputs_embeds = self.get_model().embed_tokens(inputs)
148
+
149
+ # print(inputs_embeds.shape)
150
+ return super().generate(
151
+ position_ids=None,
152
+ attention_mask=None,
153
+ inputs_embeds=inputs_embeds,
154
+ **kwargs
155
+ )
156
+
157
+ def prepare_inputs_for_generation(self, input_ids, past_key_values=None, inputs_embeds=None, **kwargs):
158
+ images = kwargs.pop("images", None)
159
+ _inputs = super().prepare_inputs_for_generation(
160
+ input_ids, past_key_values=past_key_values, inputs_embeds=inputs_embeds, **kwargs
161
+ )
162
+ if images is not None:
163
+ _inputs['images'] = images
164
+ return _inputs
165
+
166
+ # AutoConfig.register("llava", LlavaQwenConfig)
167
+ AutoConfig.register("llava_qwen2", LlavaQwenConfig)
168
+ AutoModelForCausalLM.register(LlavaQwenConfig, LlavaQwen2ForCausalLM)
HuatuoGPT-Vision-Abla-New/llava/model/multimodal_encoder/__pycache__/builder.cpython-310.pyc ADDED
Binary file (738 Bytes). View file
 
HuatuoGPT-Vision-Abla-New/llava/model/multimodal_encoder/__pycache__/clip_encoder.cpython-310.pyc ADDED
Binary file (3.41 kB). View file
 
HuatuoGPT-Vision-Abla-New/llava/model/multimodal_encoder/builder.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from .clip_encoder import CLIPVisionTower
3
+
4
+
5
+ def build_vision_tower(vision_tower_cfg, **kwargs):
6
+ vision_tower = getattr(vision_tower_cfg, 'mm_vision_tower', getattr(vision_tower_cfg, 'vision_tower', None))
7
+ is_absolute_path_exists = os.path.exists(vision_tower)
8
+ if not is_absolute_path_exists and vision_tower:
9
+ vision_tower = os.path.join(getattr(vision_tower_cfg, '_name_or_path', None),vision_tower)
10
+ is_absolute_path_exists = os.path.exists(vision_tower)
11
+ if is_absolute_path_exists or vision_tower.startswith("openai"):
12
+ return CLIPVisionTower(vision_tower, args=vision_tower_cfg, **kwargs)
13
+ else:
14
+ return CLIPVisionTower('openai/clip-vit-large-patch14-336', args=vision_tower_cfg, **kwargs)
15
+ raise ValueError(f'Unknown vision tower: {vision_tower}')
HuatuoGPT-Vision-Abla-New/llava/model/multimodal_encoder/clip_encoder.py ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+
4
+ from transformers import CLIPVisionModel, CLIPImageProcessor, CLIPVisionConfig, AutoModel
5
+ import math
6
+
7
+ class CLIPVisionTower(nn.Module):
8
+ def __init__(self, vision_tower, args, delay_load=False):
9
+ super().__init__()
10
+
11
+ self.is_loaded = False
12
+
13
+ self.vision_tower_name = vision_tower
14
+ # self.select_layer = args.mm_vision_select_layer
15
+ self.select_layer = getattr(args, 'mm_vision_select_layer', -2)
16
+ self.select_feature = getattr(args, 'mm_vision_select_feature', 'patch')
17
+
18
+ if not delay_load:
19
+ self.load_model()
20
+ else:
21
+ self.cfg_only = CLIPVisionConfig.from_pretrained(self.vision_tower_name)
22
+
23
+ def load_model(self):
24
+ print(f'loading vision model from {self.vision_tower_name}')
25
+ self.image_processor = CLIPImageProcessor.from_pretrained(self.vision_tower_name)
26
+ if 'clip' in self.vision_tower_name.lower():
27
+ self.vision_tower = CLIPVisionModel.from_pretrained(self.vision_tower_name)
28
+
29
+
30
+ elif 'internvit' in self.vision_tower_name.lower():
31
+ self.vision_tower = AutoModel.from_pretrained(self.vision_tower_name, trust_remote_code=True)
32
+ else:
33
+ raise ValueError(f'Please implement the loading of vision encoder here')
34
+
35
+ self.vision_tower.requires_grad_(False)
36
+
37
+ self.is_loaded = True
38
+
39
+ def feature_select(self, image_forward_outs):
40
+ image_features = image_forward_outs.hidden_states[self.select_layer]
41
+ if self.select_feature == 'patch':
42
+ image_features = image_features[:, 1:]
43
+ elif self.select_feature == 'cls_patch':
44
+ image_features = image_features
45
+ else:
46
+ raise ValueError(f'Unexpected select feature: {self.select_feature}')
47
+ return image_features
48
+
49
+ @torch.no_grad()
50
+ def forward(self, images):
51
+ if type(images) is list:
52
+ image_features = []
53
+ for image in images:
54
+ image_forward_out = self.vision_tower(image.to(device=self.device, dtype=self.dtype).unsqueeze(0), output_hidden_states=True)
55
+ image_feature = self.feature_select(image_forward_out).to(image.dtype)
56
+ image_features.append(image_feature)
57
+ else:
58
+ image_forward_outs = self.vision_tower(images.to(device=self.device, dtype=self.dtype), output_hidden_states=True)
59
+ image_features = self.feature_select(image_forward_outs).to(images.dtype)
60
+
61
+ return image_features
62
+
63
+ @property
64
+ def dummy_feature(self):
65
+ return torch.zeros(1, self.hidden_size, device=self.device, dtype=self.dtype)
66
+
67
+ @property
68
+ def dtype(self):
69
+ return self.vision_tower.dtype
70
+
71
+ @property
72
+ def device(self):
73
+ return self.vision_tower.device
74
+
75
+ @property
76
+ def config(self):
77
+ if self.is_loaded:
78
+ return self.vision_tower.config
79
+ else:
80
+ return self.cfg_only
81
+
82
+ @property
83
+ def hidden_size(self):
84
+ return self.config.hidden_size
85
+
86
+ @property
87
+ def num_patches(self):
88
+ return (self.config.image_size // self.config.patch_size) ** 2
89
+
90
+ @property
91
+ def num_patches_per_side(self):
92
+ return self.config.image_size // self.config.patch_size
HuatuoGPT-Vision-Abla-New/llava/model/multimodal_encoder/clip_encoder_larger_input.py ADDED
@@ -0,0 +1,230 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+
4
+ from transformers import CLIPVisionModel, CLIPImageProcessor, CLIPVisionConfig, AutoModel
5
+
6
+ from transformers import CLIPPreTrainedModel
7
+ import math
8
+
9
+
10
+ class CLIPVisionEmbeddingsLargerInput(nn.Module):
11
+ def __init__(self, config: CLIPVisionConfig):
12
+ super().__init__()
13
+ self.config = config
14
+ self.embed_dim = config.hidden_size
15
+ self.image_size = config.image_size
16
+ self.patch_size = config.patch_size
17
+
18
+ self.class_embedding = nn.Parameter(torch.randn(self.embed_dim))
19
+
20
+ self.patch_embedding = nn.Conv2d(
21
+ in_channels=config.num_channels,
22
+ out_channels=self.embed_dim,
23
+ kernel_size=self.patch_size,
24
+ stride=self.patch_size,
25
+ bias=False,
26
+ )
27
+
28
+ self.num_patches = (self.image_size // self.patch_size) ** 2
29
+ self.num_positions = self.num_patches + 1
30
+ self.position_embedding = nn.Embedding(self.num_positions, self.embed_dim)
31
+ self.register_buffer("position_ids", torch.arange(self.num_positions).expand((1, -1)), persistent=False)
32
+
33
+ # def forward(self, pixel_values: torch.FloatTensor) -> torch.Tensor:
34
+ # batch_size = pixel_values.shape[0]
35
+ # target_dtype = self.patch_embedding.weight.dtype
36
+ # patch_embeds = self.patch_embedding(pixel_values.to(dtype=target_dtype)) # shape = [*, width, grid, grid]
37
+ # patch_embeds = patch_embeds.flatten(2).transpose(1, 2)
38
+
39
+ # class_embeds = self.class_embedding.expand(batch_size, 1, -1)
40
+ # embeddings = torch.cat([class_embeds, patch_embeds], dim=1)
41
+ # embeddings = embeddings + self.position_embedding(self.position_ids)
42
+ # return embeddings
43
+
44
+ def forward(self, pixel_values: torch.FloatTensor) -> torch.Tensor:
45
+ batch_size = pixel_values.shape[0] # (bs, 3, h=336, w=336)
46
+ target_dtype = self.patch_embedding.weight.dtype
47
+ # pachify by using conv2D
48
+ patch_embeds = self.patch_embedding(pixel_values.to(dtype=target_dtype)) # shape = [*, width, grid, grid]
49
+ patch_embeds = patch_embeds.flatten(2).transpose(1, 2) # (bsz, emb_dim, p_size=24, p_size=24) -> (bsz, emb_dim, 24*24=576) -> (bsz, 576, emb_dim)
50
+
51
+ class_embeds = self.class_embedding.expand(batch_size, 1, -1) # (bsz, 1, emb_dim=1024)
52
+ embeddings = torch.cat([class_embeds, patch_embeds], dim=1)
53
+
54
+
55
+
56
+ embeddings = embeddings + self.interpolate_pos_encoding(embeddings, pixel_values.shape[2], pixel_values.shape[3])
57
+ # use interpolation
58
+
59
+
60
+ return embeddings # (bs, seqlen, dim)
61
+
62
+
63
+ def interpolate_pos_encoding(self, embeddings: torch.Tensor, height: int, width: int) -> torch.Tensor:
64
+ """
65
+ embeddings: (bsz, seqlen, dim)
66
+ This method allows to interpolate the pre-trained position encodings, to be able to use the model on higher
67
+ resolution images.
68
+ Source:
69
+ https://github.com/facebookresearch/dino/blob/de9ee3df6cf39fac952ab558447af1fa1365362a/vision_transformer.py#L174
70
+ """
71
+ # make this in init
72
+ bsz = embeddings.shape[0]
73
+ positional_embedding = self.position_embedding(self.position_ids)
74
+ # positional_embedding: (seqlen, dim)
75
+
76
+
77
+ num_patches = embeddings.shape[1] - 1
78
+
79
+ # pos_embedding = positional_embedding.unsqueeze(0)
80
+ num_positions = positional_embedding.shape[1] - 1 # number of positions of inputs
81
+
82
+
83
+ if num_patches == num_positions and height == width: # if it matches
84
+ return positional_embedding
85
+
86
+ assert num_positions < num_patches, f'there must be an increased number of positions, got {num_positions} > {num_patches}'
87
+
88
+
89
+ class_pos_embed = positional_embedding[:, [0]] # (bsz, 1)
90
+ patch_pos_embed = positional_embedding[:, 1:]
91
+ dim = embeddings.shape[-1]
92
+ h0 = height // self.patch_size
93
+ w0 = width // self.patch_size
94
+ # we add a small number to avoid floating point error in the interpolation
95
+ # see discussion at https://github.com/facebookresearch/dino/issues/8
96
+ h0, w0 = h0 + 0.1, w0 + 0.1
97
+ patch_pos_embed = patch_pos_embed.reshape(1, int(math.sqrt(num_positions)), int(math.sqrt(num_positions)), dim)
98
+ patch_pos_embed = patch_pos_embed.permute(0, 3, 1, 2)
99
+ patch_pos_embed = nn.functional.interpolate(
100
+ patch_pos_embed,
101
+ scale_factor=(h0 / math.sqrt(num_positions), w0 / math.sqrt(num_positions)),
102
+ mode="bicubic",
103
+ align_corners=False,
104
+ )
105
+ assert int(h0) == patch_pos_embed.shape[-2] and int(w0) == patch_pos_embed.shape[-1]
106
+ # patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim)
107
+ patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).view(bsz, -1, dim) # (bsz, dim, h, w) -> (bsz, h, w, dim) -> (bsz, seqlen=h*w, dim)
108
+ output = torch.cat((class_pos_embed, patch_pos_embed), dim=1)
109
+
110
+ return output
111
+
112
+
113
+ '''
114
+ overwrite:
115
+ CLIPVisionEmbeddings
116
+ embeddings = CLIPVisionEmbeddingsLargerInput()
117
+ CLIPVisionModel.vision_model.embeddings = embeddings
118
+ '''
119
+
120
+ class CLIPVisionTower(nn.Module):
121
+ def __init__(self, vision_tower, args, delay_load=False):
122
+ super().__init__()
123
+
124
+ self.is_loaded = False
125
+
126
+ self.vision_tower_name = vision_tower
127
+ # self.select_layer = args.mm_vision_select_layer
128
+ self.select_layer = getattr(args, 'mm_vision_select_layer', -2)
129
+ self.select_feature = getattr(args, 'mm_vision_select_feature', 'patch')
130
+
131
+ if not delay_load:
132
+ self.load_model()
133
+ else:
134
+ self.cfg_only = CLIPVisionConfig.from_pretrained(self.vision_tower_name)
135
+
136
+ def load_model(self):
137
+ print(f'loading vision model from {self.vision_tower_name}')
138
+ self.image_processor = CLIPImageProcessor.from_pretrained(self.vision_tower_name)
139
+ if 'clip' in self.vision_tower_name.lower():
140
+ self.vision_tower = CLIPVisionModel.from_pretrained(self.vision_tower_name)
141
+ self.vision_tower.vision_model.embeddings = CLIPVisionEmbeddingsLargerInput(self.vision_tower.config)
142
+
143
+ elif 'internvit' in self.vision_tower_name.lower():
144
+ self.vision_tower = AutoModel.from_pretrained(self.vision_tower_name, trust_remote_code=True)
145
+ else:
146
+ raise ValueError(f'Please implement the loading of vision encoder here')
147
+
148
+ self.vision_tower.requires_grad_(False)
149
+
150
+ self.is_loaded = True
151
+
152
+ def feature_select(self, image_forward_outs):
153
+ image_features = image_forward_outs.hidden_states[self.select_layer]
154
+ if self.select_feature == 'patch': # default excluding cls_patch
155
+ image_features = image_features[:, 1:]
156
+ elif self.select_feature == 'cls_patch':
157
+ image_features = image_features
158
+ else:
159
+ raise ValueError(f'Unexpected select feature: {self.select_feature}')
160
+ return image_features
161
+
162
+ @torch.no_grad()
163
+ def forward(self, images):
164
+ if type(images) is list:
165
+ image_features = []
166
+ for image in images:
167
+ image_forward_out = self.vision_tower(image.to(device=self.device, dtype=self.dtype).unsqueeze(0), output_hidden_states=True)
168
+ image_feature = self.feature_select(image_forward_out).to(image.dtype)
169
+ image_features.append(image_feature)
170
+ else:
171
+ image_forward_outs = self.vision_tower(images.to(device=self.device, dtype=self.dtype), output_hidden_states=True)
172
+ image_features = self.feature_select(image_forward_outs).to(images.dtype)
173
+
174
+ return image_features
175
+
176
+ @property
177
+ def dummy_feature(self):
178
+ return torch.zeros(1, self.hidden_size, device=self.device, dtype=self.dtype)
179
+
180
+ @property
181
+ def dtype(self):
182
+ return self.vision_tower.dtype
183
+
184
+ @property
185
+ def device(self):
186
+ return self.vision_tower.device
187
+
188
+ @property
189
+ def config(self):
190
+ if self.is_loaded:
191
+ return self.vision_tower.config
192
+ else:
193
+ return self.cfg_only
194
+
195
+ @property
196
+ def hidden_size(self):
197
+ return self.config.hidden_size
198
+
199
+ @property
200
+ def num_patches(self):
201
+ return (self.config.image_size // self.config.patch_size) ** 2
202
+
203
+
204
+
205
+ if __name__ == '__main__':
206
+ vision_tower = CLIPVisionTower('/wangbenyou/guimingchen/models/clip_vit_large_patch14_336', None)
207
+ from PIL import Image
208
+ import pdb
209
+
210
+ # vision_tower.load_model()
211
+ processor = vision_tower.image_processor
212
+
213
+ def expand2square(pil_img, background_color):
214
+ width, height = pil_img.size
215
+ if width == height:
216
+ return pil_img
217
+ elif width > height:
218
+ result = Image.new(pil_img.mode, (width, width), background_color)
219
+ result.paste(pil_img, (0, (width - height) // 2))
220
+ return result
221
+ else:
222
+ result = Image.new(pil_img.mode, (height, height), background_color)
223
+ result.paste(pil_img, ((height - width) // 2, 0))
224
+ return result
225
+ image = Image.open('/wangbenyou/guimingchen/workspaces/vllm/data/images_miniset/openai_wewb_screenshot.png').convert('RGB')
226
+
227
+ image = expand2square(image, tuple(int(x*255) for x in processor.image_mean))
228
+ image = processor.preprocess(image, return_tensors='pt')['pixel_values'] # (1, 3, 336, 336)
229
+
230
+ vision_tower(image)
HuatuoGPT-Vision-Abla-New/llava/model/multimodal_projector/__pycache__/builder.cpython-310.pyc ADDED
Binary file (2.04 kB). View file
 
HuatuoGPT-Vision-Abla-New/llava/model/multimodal_projector/builder.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import re
4
+
5
+
6
+ class IdentityMap(nn.Module):
7
+ def __init__(self):
8
+ super().__init__()
9
+
10
+ def forward(self, x, *args, **kwargs):
11
+ return x
12
+
13
+ @property
14
+ def config(self):
15
+ return {"mm_projector_type": 'identity'}
16
+
17
+
18
+ class SimpleResBlock(nn.Module):
19
+ def __init__(self, channels):
20
+ super().__init__()
21
+ self.pre_norm = nn.LayerNorm(channels)
22
+
23
+ self.proj = nn.Sequential(
24
+ nn.Linear(channels, channels),
25
+ nn.GELU(),
26
+ nn.Linear(channels, channels)
27
+ )
28
+ def forward(self, x):
29
+ x = self.pre_norm(x)
30
+ return x + self.proj(x)
31
+
32
+
33
+ def build_vision_projector(config, delay_load=False, **kwargs):
34
+ projector_type = getattr(config, 'mm_projector_type', 'linear')
35
+
36
+ if projector_type == 'linear':
37
+ return nn.Linear(config.mm_hidden_size, config.hidden_size)
38
+
39
+ mlp_gelu_match = re.match(r'^mlp(\d+)x_gelu$', projector_type)
40
+ if mlp_gelu_match:
41
+ mlp_depth = int(mlp_gelu_match.group(1))
42
+ modules = [nn.Linear(config.mm_hidden_size, config.hidden_size)]
43
+ for _ in range(1, mlp_depth):
44
+ modules.append(nn.GELU())
45
+ modules.append(nn.Linear(config.hidden_size, config.hidden_size))
46
+ return nn.Sequential(*modules)
47
+
48
+ if projector_type == 'identity':
49
+ return IdentityMap()
50
+
51
+ raise ValueError(f'Unknown projector type: {projector_type}')
HuatuoGPT-Vision-Abla-New/results_attnbias/HuatuoGPT-Vision-7B/sam_both/HuatuoGPT-Vision-7B_medical_multimodel_evaluation_data_both_Lt17_kt5.0_nt0.0_Lv17_kv1.0_nv0.0.json ADDED
The diff for this file is too large to render. See raw diff
 
HuatuoGPT-Vision-Abla-New/results_attnbias/HuatuoGPT-Vision-7B/sam_both/HuatuoGPT-Vision-7B_medical_multimodel_evaluation_data_both_Lt17_kt5.0_nt0.0_Lv17_kv1.0_nv0.0_result.json ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "OmniMedVQA": 0.7478425026968716,
3
+ "PMC-VQA_test": 0.5515,
4
+ "PathVQA_test": 0.5978584176085663,
5
+ "SLAKE_test": 0.7740384615384616,
6
+ "VQA-RAD_test": 0.6334661354581673,
7
+ "MMMU_Medical_Validation": 0.5310344827586206,
8
+ "The total score for multiple-choice questions": 0.693143716036536,
9
+ "OmniMedVQA_MR (Mag-netic Resonance Imaging)": 0.7299504950495049,
10
+ "OmniMedVQA_ultrasound": 0.7806499261447563,
11
+ "OmniMedVQA_OCT (Optical Coherence Tomography": 0.8666666666666667,
12
+ "OmniMedVQA_Dermoscopy": 0.7261306532663316,
13
+ "OmniMedVQA_CT(Computed Tomography)": 0.6715218483174284,
14
+ "OmniMedVQA_X-Ray": 0.8056918547595682,
15
+ "OmniMedVQA_Microscopy Images": 0.7747252747252747,
16
+ "OmniMedVQA_Fundus Photography": 0.829073482428115,
17
+ "MMMU_Medical_Validation_validation_Public_Health": 0.5,
18
+ "MMMU_Medical_Validation_validation_Diagnostics_and_Laboratory_Medicine": 0.43333333333333335,
19
+ "MMMU_Medical_Validation_validation_Pharmacy": 0.4444444444444444,
20
+ "MMMU_Medical_Validation_validation_Basic_Medical_Science": 0.6071428571428571,
21
+ "MMMU_Medical_Validation_validation_Clinical_Medicine": 0.6666666666666666
22
+ }
HuatuoGPT-Vision-Abla-New/results_attnbias/HuatuoGPT-Vision-7B/sam_both/_snapshot/run_ablation_grid_layer.sh ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ cd "$(dirname "$0")"
3
+
4
+ # Stage 2 of the two-stage greedy ablation search: run_ablation_grid.sh (+
5
+ # optionally run_ablation_grid_pick.sh) already found the best (s_text, s_vis)
6
+ # with the bias layer fixed at 17, and a first pass already tested
7
+ # LAYERS=(3 10 17 24 27) serially. This script covers the remaining 23 layers
8
+ # (the model has 28 total, indices 0-27, confirmed via
9
+ # PretrainedConfig.get_config_dict(...)['num_hidden_layers'] == 28) by
10
+ # splitting them across GPU 0 and GPU 2 via run_ablation_grid_layer_worker.sh
11
+ # (GPU 1/3 are occupied by other people's jobs on this workstation, so 0/2 are
12
+ # used instead of the usual 0/1), running concurrently -- no cache-warmup step first (see
13
+ # run_ablation_grid_layer_worker.sh's header for why that's safe here: the
14
+ # Pass0 cache should already be fully warm from every prior run in this repo
15
+ # sharing the same data_path/model_path/seed).
16
+ #
17
+ # After both workers finish, this script picks the best layer across ALL 28
18
+ # (the original 5 + these 23), fixed at the same winning (s_text, s_vis), and
19
+ # syncs the final (layer, s_text, s_vis) into every run_eval_attnbias_sam_*.sh.
20
+ #
21
+ # FINAL METHOD = run_eval_attnbias_sam_both.sh: nonkey_bias is
22
+ # pinned at 0 (amplify_only) and the auction mechanism is OFF for this whole
23
+ # search, matching run_ablation_grid_worker.sh/run_ablation_grid_layer_worker.sh.
24
+ set -e
25
+
26
+ TOTAL=23 # len(LAYERS_REMAINING), see run_ablation_grid_layer_worker.sh
27
+ SPLIT=12 # indices [0, SPLIT) -> GPU 0, indices [SPLIT, TOTAL) -> GPU 2
28
+
29
+ echo "[ablation-grid-layer] launching GPU 0 on layer-indices [0, $SPLIT) and GPU 2 on [$SPLIT, $TOTAL) in parallel (no warmup)"
30
+
31
+ ./run_ablation_grid_layer_worker.sh 0 0 "$SPLIT" > ablation_grid_layer_gpu0.log 2>&1 &
32
+ PID0=$!
33
+ ./run_ablation_grid_layer_worker.sh 2 "$SPLIT" $((TOTAL - SPLIT)) > ablation_grid_layer_gpu2.log 2>&1 &
34
+ PID1=$!
35
+
36
+ echo "[ablation-grid-layer] gpu0 worker pid=$PID0 (log: ablation_grid_layer_gpu0.log), gpu2 worker pid=$PID1 (log: ablation_grid_layer_gpu2.log)"
37
+
38
+ wait "$PID0"
39
+ STATUS0=$?
40
+ wait "$PID1"
41
+ STATUS1=$?
42
+
43
+ if [ "$STATUS0" -ne 0 ] || [ "$STATUS1" -ne 0 ]; then
44
+ echo "[ablation-grid-layer] a worker failed (gpu0 exit=$STATUS0, gpu2 exit=$STATUS1) -- check ablation_grid_layer_gpu{0,2}.log" >&2
45
+ exit 1
46
+ fi
47
+
48
+ echo "[ablation-grid-layer] both workers finished, all $TOTAL remaining layers done"
49
+
50
+ source /home/jinhua/miniconda3/etc/profile.d/conda.sh
51
+ conda activate huatuovision
52
+
53
+ STAGE1_LAYER=17
54
+ STRENGTHS_TEXT=(1.0 2.0 3.0 4.0 5.0)
55
+ STRENGTHS_VIS=(1.0 2.0 3.0 4.0 5.0)
56
+ # every layer the model has been tested at: the original 5-point sweep plus
57
+ # the 23 "remaining" layers this script just ran.
58
+ LAYERS_ALL=(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27)
59
+
60
+ # ── re-derive the winning (s_text, s_vis) directly from the strength grid's
61
+ # result files, same scan-and-compare as run_ablation_grid_pick.sh.
62
+ echo "[ablation-grid-layer] re-scanning the strength grid's results to find the winning (s_text, s_vis)..."
63
+ S_TEXT=""
64
+ S_VIS=""
65
+ STAGE1_BEST_SCORE=""
66
+ for ST in "${STRENGTHS_TEXT[@]}"; do
67
+ for SV in "${STRENGTHS_VIS[@]}"; do
68
+ STAGE1_OUTPUT_PATH="results_attnbias_ablation/HuatuoGPT-Vision-7B/sam_both_amplify_noauction_layer${STAGE1_LAYER}_stext${ST}_svis${SV}"
69
+ STAGE1_RESULT_F=$(ls "$STAGE1_OUTPUT_PATH"/*_result.json 2>/dev/null | head -n1)
70
+ if [ -z "$STAGE1_RESULT_F" ]; then
71
+ echo "[ablation-grid-layer] missing *_result.json under $STAGE1_OUTPUT_PATH -- has the strength grid finished?" >&2
72
+ exit 1
73
+ fi
74
+ STAGE1_SCORE=$(python -c "
75
+ import json
76
+ with open('$STAGE1_RESULT_F') as f:
77
+ d = json.load(f)
78
+ print(d['The total score for multiple-choice questions'])
79
+ ")
80
+ if [ -z "$STAGE1_BEST_SCORE" ] || python -c "exit(0 if $STAGE1_SCORE > $STAGE1_BEST_SCORE else 1)"; then
81
+ STAGE1_BEST_SCORE="$STAGE1_SCORE"
82
+ S_TEXT="$ST"
83
+ S_VIS="$SV"
84
+ fi
85
+ done
86
+ done
87
+ echo "[ablation-grid-layer] strength winner: s_text=$S_TEXT s_vis=$S_VIS (score=$STAGE1_BEST_SCORE)"
88
+
89
+ # ── pick the best layer across all 28, strength fixed at (S_TEXT, S_VIS).
90
+ BEST_LAYER=""
91
+ BEST_SCORE=""
92
+ for LAYER in "${LAYERS_ALL[@]}"; do
93
+ OUTPUT_PATH="results_attnbias_ablation/HuatuoGPT-Vision-7B/sam_both_amplify_noauction_layer${LAYER}_stext${S_TEXT}_svis${S_VIS}"
94
+ RESULT_F=$(ls "$OUTPUT_PATH"/*_result.json 2>/dev/null | head -n1)
95
+ if [ -z "$RESULT_F" ]; then
96
+ echo "[ablation-grid-layer] missing *_result.json under $OUTPUT_PATH -- cannot pick best layer (layer=$LAYER not yet run)" >&2
97
+ exit 1
98
+ fi
99
+ SCORE=$(python -c "
100
+ import json
101
+ with open('$RESULT_F') as f:
102
+ d = json.load(f)
103
+ print(d['The total score for multiple-choice questions'])
104
+ ")
105
+ echo "[ablation-grid-layer] layer=$LAYER score=$SCORE"
106
+ if [ -z "$BEST_SCORE" ] || python -c "exit(0 if $SCORE > $BEST_SCORE else 1)"; then
107
+ BEST_SCORE="$SCORE"
108
+ BEST_LAYER="$LAYER"
109
+ fi
110
+ done
111
+
112
+ echo "[ablation-grid-layer] best overall across all 28 layers: layer=$BEST_LAYER s_text=$S_TEXT s_vis=$S_VIS (score=$BEST_SCORE)"
113
+ echo "[ablation-grid-layer] syncing into every run_eval_attnbias_sam_*.sh via sync_attn_params.py"
114
+
115
+ python sync_attn_params.py \
116
+ --layers_text "$BEST_LAYER" --key_bias_text "$S_TEXT" --nonkey_bias_text "0" \
117
+ --layers_vis "$BEST_LAYER" --key_bias_vis "$S_VIS" --nonkey_bias_vis "0"
118
+
119
+ echo "[ablation-grid-layer] done. All run_eval_attnbias_sam_*.sh now use the ablation-selected layer/strength (nonkey_bias=0, amplify_only style)"
120
+ echo "[ablation-grid-layer] (amplify_only keeps its pinned-zero side; text.sh/vis.sh keep their single-modality side -- see sync_attn_params.py)."
HuatuoGPT-Vision-Abla-New/results_attnbias/HuatuoGPT-Vision-7B/sam_both/_snapshot/run_ablation_grid_layer_worker.sh ADDED
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ cd "$(dirname "$0")"
3
+
4
+ # Runs a contiguous slice of the "remaining layers" sweep (the 23 layers NOT
5
+ # already covered by the original LAYERS=(3 10 17 24 27) test) on a single
6
+ # GPU, so the full sweep can be split across GPU 0 and GPU 2 and run
7
+ # concurrently (GPU 1/3 are occupied by other jobs on this workstation) --
8
+ # same pattern as run_ablation_grid_worker.sh for the strength grid, but for
9
+ # layers.
10
+ #
11
+ # NO cache-warmup step here (unlike run_ablation_grid.sh's stage 1): by the
12
+ # time this runs, the Pass0 cache (keyed on data_path/model_path/seed, shared
13
+ # across every combo/script in this repo) has already been fully populated by
14
+ # the earlier strength grid + original 5-layer sweep + run_all_attnbias_sam.sh
15
+ # runs, so both GPU workers should hit pure cache reads with nothing new to
16
+ # write -- eliminating the write-race risk without needing a serialized
17
+ # warmup run first. This assumption only breaks if the cache is somehow still
18
+ # incomplete (e.g. an earlier run was interrupted before finishing Pass 0);
19
+ # if you're not confident the cache is fully warm, warm it manually first
20
+ # (run any single combo alone) before launching this in parallel.
21
+ #
22
+ # S_TEXT/S_VIS are re-derived from the strength grid's results (same as
23
+ # run_ablation_grid_layer.sh), not hand-filled.
24
+ #
25
+ # FINAL METHOD = run_eval_attnbias_sam_both.sh: nonkey_bias_text/vis
26
+ # are pinned at 0 (amplify_only) AND the auction mechanism is OFF, matching
27
+ # run_ablation_grid_worker.sh's strength grid exactly. Output dirs use the
28
+ # "sam_both_amplify_noauction_..." tag to match.
29
+ #
30
+ # Usage:
31
+ # ./run_ablation_grid_layer_worker.sh <gpu_id> <start_index> <count>
32
+ # Example (23 combos split 12/11 across 2 GPUs):
33
+ # ./run_ablation_grid_layer_worker.sh 0 0 12 &
34
+ # ./run_ablation_grid_layer_worker.sh 2 12 11 &
35
+ # wait
36
+ set -e
37
+
38
+ GPU_ID="$1"
39
+ START="$2"
40
+ COUNT="$3"
41
+ if [ -z "$GPU_ID" ] || [ -z "$START" ] || [ -z "$COUNT" ]; then
42
+ echo "usage: $0 <gpu_id> <start_index> <count>" >&2
43
+ exit 1
44
+ fi
45
+ export CUDA_VISIBLE_DEVICES="$GPU_ID"
46
+
47
+ source /home/jinhua/miniconda3/etc/profile.d/conda.sh
48
+ conda activate huatuovision
49
+
50
+ DATA_PATH="/home/jinhua/ExplainableVQA/benchmarks/Medical_Multimodal_Evaluation_Data/medical_multimodel_evaluation_data.json"
51
+ MODEL_PATH="FreedomIntelligence/HuatuoGPT-Vision-7B"
52
+
53
+ SEED=42
54
+ MAX_NEW_TOKENS=256
55
+
56
+ MEDSAM3_CONFIG="/home/jinhua/ExplainableVQA/HuatuoGPT-Vision-Abla/MedSAM3/configs/full_lora_config.yaml"
57
+ MEDSAM3_DIR="/home/jinhua/ExplainableVQA/HuatuoGPT-Vision-Abla/MedSAM3"
58
+
59
+ INTERVENTION="both"
60
+ # the 23 layers NOT in the original LAYERS=(3 10 17 24 27) test -- model has
61
+ # 28 layers total (indices 0-27), confirmed via
62
+ # PretrainedConfig.get_config_dict('FreedomIntelligence/HuatuoGPT-Vision-7B')['num_hidden_layers'] == 28.
63
+ # run_ablation_grid_layer.sh (the driver) does NOT keep its own copy of this
64
+ # array -- it only needs the total count (TOTAL=23) to split indices across
65
+ # GPU 0/1, plus a separate LAYERS_ALL (all 28) for the final "pick best
66
+ # layer" scan. If you change this array's length, update TOTAL/SPLIT in
67
+ # run_ablation_grid_layer.sh to match.
68
+ LAYERS_REMAINING=(0 1 2 4 5 6 7 8 9 11 12 13 14 15 16 18 19 20 21 22 23 25 26)
69
+ STAGE1_LAYER=17
70
+ STRENGTHS_TEXT=(1.0 2.0 3.0 4.0 5.0)
71
+ STRENGTHS_VIS=(1.0 2.0 3.0 4.0 5.0)
72
+
73
+ MAX_SAMPLES=""
74
+
75
+ # ── re-derive stage 1's winning (s_text, s_vis) directly from the strength
76
+ # grid's result files -- same scan-and-compare as run_ablation_grid_pick.sh.
77
+ echo "[ablation-grid-layer-worker gpu=$GPU_ID] re-scanning stage 1's results to find the winning (s_text, s_vis)..."
78
+ S_TEXT=""
79
+ S_VIS=""
80
+ STAGE1_BEST_SCORE=""
81
+ for ST in "${STRENGTHS_TEXT[@]}"; do
82
+ for SV in "${STRENGTHS_VIS[@]}"; do
83
+ STAGE1_OUTPUT_PATH="results_attnbias_ablation/HuatuoGPT-Vision-7B/sam_both_amplify_noauction_layer${STAGE1_LAYER}_stext${ST}_svis${SV}"
84
+ STAGE1_RESULT_F=$(ls "$STAGE1_OUTPUT_PATH"/*_result.json 2>/dev/null | head -n1)
85
+ if [ -z "$STAGE1_RESULT_F" ]; then
86
+ echo "[ablation-grid-layer-worker gpu=$GPU_ID] missing *_result.json under $STAGE1_OUTPUT_PATH -- has the strength grid finished?" >&2
87
+ exit 1
88
+ fi
89
+ STAGE1_SCORE=$(python -c "
90
+ import json
91
+ with open('$STAGE1_RESULT_F') as f:
92
+ d = json.load(f)
93
+ print(d['The total score for multiple-choice questions'])
94
+ ")
95
+ if [ -z "$STAGE1_BEST_SCORE" ] || python -c "exit(0 if $STAGE1_SCORE > $STAGE1_BEST_SCORE else 1)"; then
96
+ STAGE1_BEST_SCORE="$STAGE1_SCORE"
97
+ S_TEXT="$ST"
98
+ S_VIS="$SV"
99
+ fi
100
+ done
101
+ done
102
+ echo "[ablation-grid-layer-worker gpu=$GPU_ID] strength winner: s_text=$S_TEXT s_vis=$S_VIS (score=$STAGE1_BEST_SCORE) -- fixing strength at this combo for the layer sweep"
103
+
104
+ TOTAL=${#LAYERS_REMAINING[@]}
105
+ END=$((START + COUNT))
106
+ if [ "$END" -gt "$TOTAL" ]; then
107
+ END="$TOTAL"
108
+ fi
109
+
110
+ echo "[ablation-grid-layer-worker gpu=$GPU_ID] running layers [$START, $END) of $TOTAL total"
111
+
112
+ for ((i = START; i < END; i++)); do
113
+ LAYER="${LAYERS_REMAINING[$i]}"
114
+ OUTPUT_PATH="results_attnbias_ablation/HuatuoGPT-Vision-7B/sam_both_amplify_noauction_layer${LAYER}_stext${S_TEXT}_svis${S_VIS}"
115
+ if [ -d "$OUTPUT_PATH" ]; then
116
+ echo "[ablation-grid-layer-worker gpu=$GPU_ID] $OUTPUT_PATH already exists, skipping layer=$LAYER (delete the dir manually to re-run)"
117
+ continue
118
+ fi
119
+
120
+ echo "=================================================="
121
+ echo "[ablation-grid-layer-worker gpu=$GPU_ID] idx=$i layer=$LAYER s_text=$S_TEXT s_vis=$S_VIS -> $OUTPUT_PATH"
122
+ echo "=================================================="
123
+
124
+ accelerate launch --num_processes=1 eval_attnbias_sam.py \
125
+ --data_path "$DATA_PATH" \
126
+ --model_path "$MODEL_PATH" \
127
+ --seed "$SEED" \
128
+ --max_new_tokens "$MAX_NEW_TOKENS" \
129
+ --output_path "$OUTPUT_PATH" \
130
+ --intervention "$INTERVENTION" \
131
+ --attn_layers_text "$LAYER" \
132
+ --attn_key_bias_text "$S_TEXT" \
133
+ --attn_nonkey_bias_text "0" \
134
+ --attn_layers_vis "$LAYER" \
135
+ --attn_key_bias_vis "$S_VIS" \
136
+ --attn_nonkey_bias_vis "0" \
137
+ --medsam3_config "$MEDSAM3_CONFIG" \
138
+ --medsam3_dir "$MEDSAM3_DIR" \
139
+ ${MAX_SAMPLES:+--max_samples "$MAX_SAMPLES"}
140
+
141
+ echo "[ablation-grid-layer-worker gpu=$GPU_ID] idx=$i layer=$LAYER finished"
142
+ done
143
+
144
+ echo "[ablation-grid-layer-worker gpu=$GPU_ID] done with layers [$START, $END)"
HuatuoGPT-Vision-Abla-New/results_attnbias/HuatuoGPT-Vision-7B/sam_both/_snapshot/run_ablation_grid_pick.sh ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ cd "$(dirname "$0")"
3
+
4
+ # Picks the best (strength_text, strength_vis) across the full grid and syncs
5
+ # it into every run_eval_attnbias_sam_*.sh via sync_attn_params.py. Run this
6
+ # ONCE, by hand, after every run_ablation_grid_worker.sh slice (on every GPU
7
+ # you split the grid across) has finished -- it requires *all* combos'
8
+ # *_result.json to be present, since the "best" choice isn't meaningful until
9
+ # the whole grid has been scored.
10
+ #
11
+ # FINAL METHOD = run_eval_attnbias_sam_both.sh: nonkey_bias is
12
+ # pinned at 0 (amplify_only -- boost key regions only, no suppression) AND the
13
+ # grid was searched with the auction mechanism OFF (see
14
+ # run_ablation_grid_worker.sh), matching the final method exactly.
15
+ # run_eval_attnbias_sam_both_suppress_only.sh has been dropped from
16
+ # run_all_attnbias_sam.sh's comparison set (no longer a live ablation arm), so
17
+ # there's no risk of this sync corrupting it.
18
+ set -e
19
+
20
+ source /home/jinhua/miniconda3/etc/profile.d/conda.sh
21
+ conda activate huatuovision
22
+
23
+ LAYER=17
24
+ # must stay identical to run_ablation_grid_worker.sh's copy of these arrays.
25
+ STRENGTHS_TEXT=(1.0 2.0 3.0 4.0 5.0)
26
+ STRENGTHS_VIS=(1.0 2.0 3.0 4.0 5.0)
27
+
28
+ # ── pick the best (s_text, s_vis) across the full grid, layer fixed at 17.
29
+ # Each combo's output dir holds exactly one *_result.json (eval_attnbias_sam.py's hparam_tag
30
+ # already makes the filename unique per layer/strength/auction config, so
31
+ # no risk of stale files from a previous combo lingering in the same dir),
32
+ # so glob for it directly instead of hand-reconstructing the filename --
33
+ # that reconstruction is what broke last time hparam_tag's format changed.
34
+ BEST_S_TEXT=""
35
+ BEST_S_VIS=""
36
+ BEST_SCORE=""
37
+ for S_TEXT in "${STRENGTHS_TEXT[@]}"; do
38
+ for S_VIS in "${STRENGTHS_VIS[@]}"; do
39
+ OUTPUT_PATH="results_attnbias_ablation/HuatuoGPT-Vision-7B/sam_both_amplify_noauction_layer${LAYER}_stext${S_TEXT}_svis${S_VIS}"
40
+ RESULT_F=$(ls "$OUTPUT_PATH"/*_result.json 2>/dev/null | head -n1)
41
+ if [ -z "$RESULT_F" ]; then
42
+ echo "[ablation-grid-pick] missing *_result.json under $OUTPUT_PATH -- cannot pick best (s_text, s_vis). Did every run_ablation_grid_worker.sh slice finish?" >&2
43
+ exit 1
44
+ fi
45
+ SCORE=$(python -c "
46
+ import json
47
+ with open('$RESULT_F') as f:
48
+ d = json.load(f)
49
+ print(d['The total score for multiple-choice questions'])
50
+ ")
51
+ echo "[ablation-grid-pick] s_text=$S_TEXT s_vis=$S_VIS score=$SCORE"
52
+ if [ -z "$BEST_SCORE" ] || python -c "exit(0 if $SCORE > $BEST_SCORE else 1)"; then
53
+ BEST_SCORE="$SCORE"
54
+ BEST_S_TEXT="$S_TEXT"
55
+ BEST_S_VIS="$S_VIS"
56
+ fi
57
+ done
58
+ done
59
+
60
+ echo "[ablation-grid-pick] best overall: layer=$LAYER s_text=$BEST_S_TEXT s_vis=$BEST_S_VIS (score=$BEST_SCORE)"
61
+ echo "[ablation-grid-pick] syncing into every run_eval_attnbias_sam_*.sh via sync_attn_params.py"
62
+
63
+ python sync_attn_params.py \
64
+ --layers_text "$LAYER" --key_bias_text "$BEST_S_TEXT" --nonkey_bias_text "0" \
65
+ --layers_vis "$LAYER" --key_bias_vis "$BEST_S_VIS" --nonkey_bias_vis "0"
66
+
67
+ echo "[ablation-grid-pick] done. All run_eval_attnbias_sam_*.sh now use the ablation-selected layer/strength (nonkey_bias=0, amplify_only style)"
68
+ echo "[ablation-grid-pick] (amplify_only keeps its pinned-zero side; text.sh/vis.sh keep their single-modality side -- see sync_attn_params.py)."
HuatuoGPT-Vision-Abla-New/results_attnbias/HuatuoGPT-Vision-7B/sam_both/_snapshot/run_all_attnbias_sam.sh ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ cd "$(dirname "$0")"
3
+
4
+ # 先跑 baseline(无干预的 eval.py),再依次跑完对比组:
5
+ # none(无attention干预)/ both(正式配置:全量放大关键区域,不开拍卖)/
6
+ # text / vis(单模态消融)
7
+ # run_eval_attnbias_sam_both_noauction.sh 内容跟正式配置both.sh完全一样(both.sh
8
+ # 本身已经改成不开拍卖了),文件保留但不再放进这个清单,避免重复跑同一件事。
9
+ # 任意一个失败就停止,避免在错误的环境下继续浪费时间
10
+ set -e
11
+
12
+ # 默认使用 huatuovision conda 环境,不依赖调用者当前激活的环境。
13
+ # source profile.d/conda.sh是必须的:非交互式shell(setsid/nohup这类后台
14
+ # 启动方式)不会自动加载~/.bashrc,conda activate这个shell函数不会被定义,
15
+ # 必须显式source这个脚本才能在当前shell里用conda activate。
16
+ source /home/jinhua/miniconda3/etc/profile.d/conda.sh
17
+ conda activate huatuovision
18
+
19
+ SCRIPTS=(
20
+ "run_eval.sh"
21
+ "run_eval_attnbias_sam_none.sh"
22
+ "run_eval_attnbias_sam_both.sh"
23
+ "run_eval_attnbias_sam_text.sh"
24
+ "run_eval_attnbias_sam_vis.sh"
25
+ )
26
+
27
+ for script in "${SCRIPTS[@]}"; do
28
+ echo "=================================================="
29
+ echo "[run_all] 开始运行 $script"
30
+ echo "=================================================="
31
+ bash "$script"
32
+ echo "[run_all] $script 运行完成"
33
+ done
34
+
35
+ echo "[run_all] 全部干预模式运行完成"
HuatuoGPT-Vision-Abla-New/results_attnbias/HuatuoGPT-Vision-7B/sam_both/_snapshot/run_eval_attnbias_sam_both.sh ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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-Abla/MedSAM3/configs/full_lora_config.yaml"
12
+ MEDSAM3_DIR="/home/jinhua/ExplainableVQA/HuatuoGPT-Vision-Abla/MedSAM3"
13
+
14
+ # FINAL METHOD: both mode, amplify-only (nonkey_bias pinned at 0 -- boost key
15
+ # regions, don't suppress anything else) and auction OFF -- every Stage1/SAM-
16
+ # detected key position gets boosted directly, not just an auction-selected
17
+ # subset (ablation found the auction mechanism doesn't help over this simpler
18
+ # design; see run_eval_attnbias_sam_both_noauction.sh, kept around for
19
+ # reference but no longer part of the active comparison set).
20
+ INTERVENTION="both"
21
+ ATTN_LAYERS_TEXT=17
22
+ ATTN_KEY_BIAS_TEXT=5.0
23
+ ATTN_NONKEY_BIAS_TEXT=0
24
+ ATTN_LAYERS_VIS=17
25
+ ATTN_KEY_BIAS_VIS=1.0
26
+ ATTN_NONKEY_BIAS_VIS=0
27
+
28
+ MAX_SAMPLES=""
29
+
30
+ # 单卡跑,跟run_eval.sh一样显式锁定卡2。
31
+ export CUDA_VISIBLE_DEVICES=2
32
+
33
+ accelerate launch --num_processes=1 eval_attnbias_sam.py \
34
+ --data_path "$DATA_PATH" \
35
+ --model_path "$MODEL_PATH" \
36
+ --seed "$SEED" \
37
+ --max_new_tokens "$MAX_NEW_TOKENS" \
38
+ --output_path "$OUTPUT_PATH" \
39
+ --intervention "$INTERVENTION" \
40
+ --attn_layers_text "$ATTN_LAYERS_TEXT" \
41
+ --attn_key_bias_text "$ATTN_KEY_BIAS_TEXT" \
42
+ --attn_nonkey_bias_text "$ATTN_NONKEY_BIAS_TEXT" \
43
+ --attn_layers_vis "$ATTN_LAYERS_VIS" \
44
+ --attn_key_bias_vis "$ATTN_KEY_BIAS_VIS" \
45
+ --attn_nonkey_bias_vis "$ATTN_NONKEY_BIAS_VIS" \
46
+ --medsam3_config "$MEDSAM3_CONFIG" \
47
+ --medsam3_dir "$MEDSAM3_DIR" \
48
+ ${MAX_SAMPLES:+--max_samples "$MAX_SAMPLES"}
HuatuoGPT-Vision-Abla-New/results_attnbias/HuatuoGPT-Vision-7B/sam_both/_snapshot/run_eval_attnbias_sam_text.sh ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # Modality ablation: text-only. Only the scispaCy keyword text positions get
12
+ # biased (key_bias_text / nonkey_bias_text); the vis side is forced to 0 bias
13
+ # inside _make_attn_ctx regardless of what's passed here. SAM/MedSAM3 is
14
+ # skipped entirely (_needs_sam is False for "text"), so no medsam3_* args.
15
+ # Matches run_eval_attnbias_sam_both.sh's mechanism (amplify-only, auction
16
+ # OFF) so this differs from the final method by exactly one factor (modality
17
+ # restricted to text); compare against run_eval_attnbias_sam_vis.sh and
18
+ # run_eval_attnbias_sam_both.sh.
19
+ INTERVENTION="text"
20
+ ATTN_LAYERS_TEXT=17
21
+ ATTN_KEY_BIAS_TEXT=5.0
22
+ ATTN_NONKEY_BIAS_TEXT=0
23
+ ATTN_LAYERS_VIS="17"
24
+
25
+ MAX_SAMPLES=""
26
+
27
+ # 单卡跑,跟run_eval.sh一样显式锁定卡2。
28
+ export CUDA_VISIBLE_DEVICES=2
29
+
30
+ accelerate launch --num_processes=1 eval_attnbias_sam.py \
31
+ --data_path "$DATA_PATH" \
32
+ --model_path "$MODEL_PATH" \
33
+ --seed "$SEED" \
34
+ --max_new_tokens "$MAX_NEW_TOKENS" \
35
+ --output_path "$OUTPUT_PATH" \
36
+ --intervention "$INTERVENTION" \
37
+ --attn_layers_text "$ATTN_LAYERS_TEXT" \
38
+ --attn_key_bias_text "$ATTN_KEY_BIAS_TEXT" \
39
+ --attn_nonkey_bias_text "$ATTN_NONKEY_BIAS_TEXT" \
40
+ --attn_layers_vis "$ATTN_LAYERS_VIS" \
41
+ ${MAX_SAMPLES:+--max_samples "$MAX_SAMPLES"}