Master-Shi commited on
Commit
4f7b897
·
verified ·
1 Parent(s): 330d051

Add files using upload-large-folder tool

Browse files
HuatuoGPT-Vision-Abla/README.md ADDED
@@ -0,0 +1,198 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # HuatuoGPT-Vision, Towards Injecting Medical Visual Knowledge into Multimodal LLMs at Scale
2
+
3
+
4
+ <div align="center">
5
+ <h5>
6
+ 📃 <a href="https://arxiv.org/abs/2406.19280" target="_blank">Paper</a> • 🖥️ <a href="https://vision.huatuogpt.cn/#/" target="_blank">Demo</a>
7
+ </h5>
8
+ </div>
9
+
10
+ <div align="center">
11
+ <h4>
12
+ 📚 <a href="https://huggingface.co/datasets/FreedomIntelligence/PubMedVision" target="_blank">PubMedVision</a>
13
+ </h4>
14
+ </div>
15
+
16
+ <div align="center">
17
+ <h4>
18
+ 🤗 <a href="https://huggingface.co/FreedomIntelligence/HuatuoGPT-Vision-34B" target="_blank">HuatuoGPT-Vision-34B</a> • 🤗 <a href="https://huggingface.co/FreedomIntelligence/HuatuoGPT-Vision-7B">HuatuoGPT-Vision-7B</a>
19
+ </h4>
20
+ </div>
21
+
22
+ ## ✨ Updates
23
+ - [04/23/2025]: We release the training code based on the Qwen2.5-VL framework.
24
+ - [01/09/2025]: We released the evaluation code (including evaluation data). Additionally, we added instructions on how to train your medical multimodal LLM.
25
+ - [06/28/2024]: We released our medical MLLMs, including [HuatuoGPT-Vision-34B](https://huggingface.co/FreedomIntelligence/HuatuoGPT-Vision-34B) and [HuatuoGPT-Vision-7B](https://huggingface.co/FreedomIntelligence/HuatuoGPT-Vision-7B).
26
+ - [06/26/2024]: We released [PubMedVision](https://huggingface.co/datasets/FreedomIntelligence/PubMedVision), a **1.3M** high-quality medical VQA dataset for injecting medical visual knowledge.
27
+
28
+ ## 🩻 PubMedVision
29
+ - **PubMedVision** is a large-scale, high-quality medical VQA dataset, constructed from the image-text pairs from PubMed and reformatted using GPT-4V.
30
+
31
+ | | # Data | Download |
32
+ | ------------------ | ---------- | ------------- |
33
+ | **PubMedVision Dataset** | **1,294,062** | [HF Link](https://huggingface.co/datasets/FreedomIntelligence/PubMedVision) |
34
+
35
+ - **PubMedVision** could significantly improve the medical multimodal capabilities of MLLMs such as LLaVA-v1.5.
36
+
37
+ | | **VQA-RAD** | **SLAKE** | **PathVQA** | **PMC-VQA** |
38
+ | --------------------------------------- | ----------- | --------- | ----------- | ----------- |
39
+ | LLaVA-v1.6-34B | 58.6 | 67.3 | 59.1 | 44.4 |
40
+ | LLaVA-v1.5-LLaMA3-8B | 54.2 | 59.4 | 54.1 | 36.4 |
41
+ | LLaVA-v1.5-LLaMA3-8B + **PubMedVision** | **63.8** | **74.5** | **59.9** | **52.7** |
42
+
43
+ | | **OmniMedVQA** | **MMMU Health & Medicine (Test Set)** |
44
+ | ----------------------------------- | ------------ | -------------------------- |
45
+ | LLaVA-v1.6-34B | 61.4 | 48.8 |
46
+ | LLaVA-v1.5-LLaMA3-8B | 48.8 | 38.2 |
47
+ | LLaVA-v1.5-LLaMA3-8B + **PubMedVision** | **75.1** | **49.1** |
48
+
49
+ ## 👨‍⚕️ HuatuoGPT-Vision
50
+ HuatuoGPT-Vision is our medical multimodal LLMs, built on **PubMedVision**.
51
+
52
+ ### Model Access
53
+ Our model is available on Huggingface in two versions:
54
+ | | Backbone | Checkpoint |
55
+ |----------------------|--------------------|---------------------------------------------------------------------------------------|
56
+ | **HuatuoGPT-Vision-7B** | Qwen2-7B | [HF Link](https://huggingface.co/FreedomIntelligence/HuatuoGPT-Vision-7B) |
57
+ | **HuatuoGPT-Vision-34B** | Yi-1.5-34B | [HF Link](https://huggingface.co/FreedomIntelligence/HuatuoGPT-Vision-34B) |
58
+
59
+ ### Model Usage
60
+
61
+ - **Command Line Interface**
62
+
63
+ Chat via the command line:
64
+ ```bash
65
+ python cli.py --model_dir path-to-huatuogpt-vision-model
66
+ ```
67
+
68
+ - **Model Inference**
69
+
70
+ Inference using our ChatBot:
71
+ ```python
72
+ query = 'What does the picture show?'
73
+ image_paths = ['image_path1']
74
+
75
+ from cli import HuatuoChatbot
76
+ bot = HuatuoChatbot(path-to-huatuogpt-vision-model)
77
+ output = bot.inference(query, image_paths)
78
+ print(output) # Prints the output of the model
79
+ ```
80
+
81
+ ### Performance of Medical Multimodal
82
+ | | **VQA-RAD** | **SLAKE** | **PathVQA** | **PMC-VQA** |
83
+ |-----------------------------|-------------|-----------|-------------|-------------|
84
+ | LLaVA-Med-7B | 51.4 | 48.6 | 56.8 | 24.7 |
85
+ | LLaVA-v1.6-34B | 58.6 | 67.3 | 59.1 | 44.4 |
86
+ | **HuatuoGPT-Vision-7B** | 63.7 | 76.2 | 57.9 | 54.3 |
87
+ | **HuatuoGPT-Vision-34B** | **68.1** | **76.9** | **63.5** | **58.2** |
88
+
89
+ | | **OmniMedVQA** | **MMMU Health & Medicine (Test Set)** |
90
+ |---------------------------|-----------------|---------------------------------------|
91
+ | LLaVA-Med-7B | 44.5 | 36.9 |
92
+ | LLaVA-v1.6-34B | 61.4 | 48.8 |
93
+ | **HuatuoGPT-Vision-7B** | 74.0 | 50.6 |
94
+ | **HuatuoGPT-Vision-34B** | **76.9** | **54.4** |
95
+
96
+ ## 📏 Evaluation
97
+ 1. For evaluation, you need to download the medical evaluation dataset. We have organized multiple evaluation datasets, which can be downloaded directly via the following link:
98
+
99
+ | Dataset | Link |
100
+ | --- | --- |
101
+ | Medical_Multimodal_Evaluation_Data | [link](https://huggingface.co/datasets/FreedomIntelligence/Medical_Multimodal_Evaluation_Data) |
102
+
103
+ We have bundled multiple evaluation datasets together. Simply download the data and extract the `images.zip` file.
104
+
105
+ 2. Then, you can evaluate using the following command:
106
+ ```bash
107
+ accelerate launch eval.py --data_path Medical_Multimodal_Evaluation_Data/medical_multimodel_evaluation_data.json --model_path HuatuoGPT-Vision-7B
108
+ ```
109
+
110
+ 3. Once executed, you will directly obtain the results of the medical multimodal evaluation, including datasets like `VQA-RAD`, `SLAKE`, `PathVQA`, `PMC-VQA`, `OmniMedVQA`, and `MMMU-Medical-Tracks`.
111
+
112
+
113
+ ## 🏋 Training
114
+ This project uses LLaVA's code for training, and it is recommended to use LLaVA's code for training. The code is available at [LLaVA](https://github.com/haotian-liu/LLaVA).
115
+ > To reproduce our results, please train the model using a combination of the PubMedVision dataset and LLaVA's dataset.
116
+
117
+ > **Update (April 23, 2025):**
118
+ > We release our training process using an newer architecture. Given that the original LLaVA codebase are relatively outdated, we’ve transitioned to a cleaner and more efficient training framework based on [Qwen2.5-VL](https://github.com/QwenLM/Qwen2.5-VL).
119
+ > The Qwen2.5-VL architecture is more compatible with Huggingface Transformers, making both training and deployment easier, and it offers better support for image processing. **We strongly recommend using Qwen2.5-VL.** (Note: Use the latest Transformers library for Qwen2.5-VL compatibility.)
120
+
121
+ - **Step 1: Initialize Qwen2.5-VL with LLMs**
122
+
123
+ Initialize Qwen2.5-VL with LLMs (Qwen2.5-LLM). This step initializes a Qwen2.5-VL with an LLM so that we can train an MLLM from scratch.
124
+
125
+ ```bash
126
+ python convert_llm_to_vl.py \
127
+ --vl_model_path Qwen/Qwen2.5-VL-7B-Instruct \
128
+ --llm_model_path Qwen/Qwen2.5-7B-Instruct \
129
+ --save_path ./Qwen2.5-VL-7B-Base
130
+ ```
131
+
132
+ - **Step 2: Vision Alignment (Caption Dataset Pretraining)**
133
+
134
+ ```bash
135
+ accelerate launch --config_file ./config/ds.yaml \
136
+ --num_processes 8 \
137
+ --num_machines 1 \
138
+ --machine_rank 0 \
139
+ --main_process_port 29502 \
140
+ --deepspeed_multinode_launcher standard train_vl.py \
141
+ --experiment_name huatuogpt_vision_alignment \
142
+ --run_name huatuogpt_vision \
143
+ --model_path ./Qwen2.5-VL-7B-Base \
144
+ --max_ckpts 1 \
145
+ --gradient_accumulation_steps 8 \
146
+ --data_path Vision_Alignment_Data.json \
147
+ --output_dir ./huatuogpt_vision_alignment_checkpoint \
148
+ --n_epochs 1 \
149
+ --warmup_rates 0.05 \
150
+ --train_bsz_per_gpu 2 \
151
+ --learning_rate 5e-6 \
152
+ --gradient_checkpointing
153
+ ```
154
+
155
+ - **Step 3: Vision Instruction Fine-tuning**
156
+
157
+ ```bash
158
+ accelerate launch --config_file ./config/ds.yaml \
159
+ --num_processes 8 \
160
+ --num_machines 1 \
161
+ --machine_rank 0 \
162
+ --main_process_port 29502 \
163
+ --deepspeed_multinode_launcher standard train_vl.py \
164
+ --experiment_name huatuogpt_vision_sft \
165
+ --run_name huatuogpt_vision \
166
+ --model_path huatuogpt_vision_alignment_model \
167
+ --max_ckpts 1 \
168
+ --gradient_accumulation_steps 8 \
169
+ --data_path Vision_SFT_Data.json \
170
+ --n_epochs 1 \
171
+ --warmup_rates 0.05 \
172
+ --train_bsz_per_gpu 2 \
173
+ --learning_rate 5e-6 \
174
+ --gradient_checkpointing
175
+ ```
176
+
177
+
178
+
179
+ ## 🩺 HuatuoGPT Series
180
+
181
+ Explore our HuatuoGPT series:
182
+ - [**HuatuoGPT**](https://github.com/FreedomIntelligence/HuatuoGPT): Taming Language Models to Be a Doctor
183
+ - [**HuatuoGPT-II**](https://github.com/FreedomIntelligence/HuatuoGPT-II): One-stage Training for Medical Adaptation of LLMs
184
+ - [**HuatuoGPT-Vision**](https://github.com/FreedomIntelligence/HuatuoGPT-Vision): Injecting Medical Visual Knowledge into Multimodal LLMs at Scale
185
+
186
+
187
+ ## Citation
188
+ ```
189
+ @misc{chen2024huatuogptvisioninjectingmedicalvisual,
190
+ title={HuatuoGPT-Vision, Towards Injecting Medical Visual Knowledge into Multimodal LLMs at Scale},
191
+ author={Junying Chen and Ruyi Ouyang and Anningzhe Gao and Shunian Chen and Guiming Hardy Chen and Xidong Wang and Ruifei Zhang and Zhenyang Cai and Ke Ji and Guangjun Yu and Xiang Wan and Benyou Wang},
192
+ year={2024},
193
+ eprint={2406.19280},
194
+ archivePrefix={arXiv},
195
+ primaryClass={cs.CV},
196
+ url={https://arxiv.org/abs/2406.19280},
197
+ }
198
+ ```
HuatuoGPT-Vision-Abla/llava/constants.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ CONTROLLER_HEART_BEAT_EXPIRATION = 30
2
+ WORKER_HEART_BEAT_INTERVAL = 15
3
+
4
+ LOGDIR = "."
5
+
6
+ # Model Constants
7
+ IGNORE_INDEX = -100
8
+ IMAGE_TOKEN_INDEX = -200
9
+ DEFAULT_IMAGE_TOKEN = "<image>"
10
+ DEFAULT_IMAGE_PATCH_TOKEN = "<im_patch>"
11
+ DEFAULT_IM_START_TOKEN = "<im_start>"
12
+ DEFAULT_IM_END_TOKEN = "<im_end>"
13
+ IMAGE_PLACEHOLDER = "<image-placeholder>"
HuatuoGPT-Vision-Abla/llava/model/apply_delta.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Usage:
3
+ python3 -m fastchat.model.apply_delta --base ~/model_weights/llama-7b --target ~/model_weights/vicuna-7b --delta lmsys/vicuna-7b-delta
4
+ """
5
+ import argparse
6
+
7
+ import torch
8
+ from tqdm import tqdm
9
+ from transformers import AutoTokenizer, AutoModelForCausalLM
10
+ from llava import LlavaLlamaForCausalLM
11
+
12
+
13
+ def apply_delta(base_model_path, target_model_path, delta_path):
14
+ print("Loading base model")
15
+ base = AutoModelForCausalLM.from_pretrained(
16
+ base_model_path, torch_dtype=torch.float16, low_cpu_mem_usage=True)
17
+
18
+ print("Loading delta")
19
+ delta = LlavaLlamaForCausalLM.from_pretrained(delta_path, torch_dtype=torch.float16, low_cpu_mem_usage=True)
20
+ delta_tokenizer = AutoTokenizer.from_pretrained(delta_path)
21
+
22
+ print("Applying delta")
23
+ for name, param in tqdm(delta.state_dict().items(), desc="Applying delta"):
24
+ if name not in base.state_dict():
25
+ assert name in ['model.mm_projector.weight', 'model.mm_projector.bias'], f'{name} not in base model'
26
+ continue
27
+ if param.data.shape == base.state_dict()[name].shape:
28
+ param.data += base.state_dict()[name]
29
+ else:
30
+ assert name in ['model.embed_tokens.weight', 'lm_head.weight'], \
31
+ f'{name} dimension mismatch: {param.data.shape} vs {base.state_dict()[name].shape}'
32
+ bparam = base.state_dict()[name]
33
+ param.data[:bparam.shape[0], :bparam.shape[1]] += bparam
34
+
35
+ print("Saving target model")
36
+ delta.save_pretrained(target_model_path)
37
+ delta_tokenizer.save_pretrained(target_model_path)
38
+
39
+
40
+ if __name__ == "__main__":
41
+ parser = argparse.ArgumentParser()
42
+ parser.add_argument("--base-model-path", type=str, required=True)
43
+ parser.add_argument("--target-model-path", type=str, required=True)
44
+ parser.add_argument("--delta-path", type=str, required=True)
45
+
46
+ args = parser.parse_args()
47
+
48
+ apply_delta(args.base_model_path, args.target_model_path, args.delta_path)
HuatuoGPT-Vision-Abla/llava/model/builder.py ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
16
+ import os
17
+ import warnings
18
+ import shutil
19
+
20
+ from transformers import AutoTokenizer, AutoModelForCausalLM, AutoConfig, BitsAndBytesConfig
21
+ import torch
22
+ from llava.model import *
23
+ from llava.constants import DEFAULT_IMAGE_PATCH_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN
24
+ import pdb
25
+
26
+ def load_pretrained_model(model_path, model_base, model_name, load_8bit=False, load_4bit=False, device_map="auto", device="cuda", **kwargs):
27
+ kwargs = {"device_map": device_map, **kwargs}
28
+
29
+ if device != "cuda":
30
+ kwargs['device_map'] = {"": device}
31
+
32
+ if load_8bit:
33
+ kwargs['load_in_8bit'] = True
34
+ elif load_4bit:
35
+ kwargs['load_in_4bit'] = True
36
+ kwargs['quantization_config'] = BitsAndBytesConfig(
37
+ load_in_4bit=True,
38
+ bnb_4bit_compute_dtype=torch.float16,
39
+ bnb_4bit_use_double_quant=True,
40
+ bnb_4bit_quant_type='nf4'
41
+ )
42
+ else:
43
+ kwargs['torch_dtype'] = torch.float16
44
+ if 'llava' in model_name.lower():
45
+ # Load LLaVA model
46
+ if 'lora' in model_name.lower() and model_base is None:
47
+ warnings.warn('There is `lora` in model name but no `model_base` is provided. If you are loading a LoRA model, please provide the `model_base` argument. Detailed instruction: https://github.com/haotian-liu/LLaVA#launch-a-model-worker-lora-weights-unmerged.')
48
+ if 'lora' in model_name.lower() and model_base is not None:
49
+ lora_cfg_pretrained = AutoConfig.from_pretrained(model_path)
50
+ tokenizer = AutoTokenizer.from_pretrained(model_base, use_fast=False)
51
+ print('Loading LLaVA from base model...')
52
+ model = LlavaLlamaForCausalLM.from_pretrained(model_base, low_cpu_mem_usage=True, config=lora_cfg_pretrained, **kwargs)
53
+ token_num, tokem_dim = model.lm_head.out_features, model.lm_head.in_features
54
+ if model.lm_head.weight.shape[0] != token_num:
55
+ model.lm_head.weight = torch.nn.Parameter(torch.empty(token_num, tokem_dim, device=model.device, dtype=model.dtype))
56
+ model.model.embed_tokens.weight = torch.nn.Parameter(torch.empty(token_num, tokem_dim, device=model.device, dtype=model.dtype))
57
+
58
+ print('Loading additional LLaVA weights...')
59
+ if os.path.exists(os.path.join(model_path, 'non_lora_trainables.bin')):
60
+ non_lora_trainables = torch.load(os.path.join(model_path, 'non_lora_trainables.bin'), map_location='cpu')
61
+ else:
62
+ # this is probably from HF Hub
63
+ from huggingface_hub import hf_hub_download
64
+ def load_from_hf(repo_id, filename, subfolder=None):
65
+ cache_file = hf_hub_download(
66
+ repo_id=repo_id,
67
+ filename=filename,
68
+ subfolder=subfolder)
69
+ return torch.load(cache_file, map_location='cpu')
70
+ non_lora_trainables = load_from_hf(model_path, 'non_lora_trainables.bin')
71
+ non_lora_trainables = {(k[11:] if k.startswith('base_model.') else k): v for k, v in non_lora_trainables.items()}
72
+ if any(k.startswith('model.model.') for k in non_lora_trainables):
73
+ non_lora_trainables = {(k[6:] if k.startswith('model.') else k): v for k, v in non_lora_trainables.items()}
74
+ model.load_state_dict(non_lora_trainables, strict=False)
75
+
76
+ from peft import PeftModel
77
+ print('Loading LoRA weights...')
78
+ model = PeftModel.from_pretrained(model, model_path)
79
+ print('Merging LoRA weights...')
80
+ model = model.merge_and_unload()
81
+ print('Model is loaded...')
82
+ elif model_base is not None:
83
+ # this may be mm projector only
84
+ print('Loading LLaVA from base model...')
85
+ if 'mpt' in model_name.lower():
86
+ if not os.path.isfile(os.path.join(model_path, 'configuration_mpt.py')):
87
+ shutil.copyfile(os.path.join(model_base, 'configuration_mpt.py'), os.path.join(model_path, 'configuration_mpt.py'))
88
+ tokenizer = AutoTokenizer.from_pretrained(model_base, use_fast=True)
89
+ cfg_pretrained = AutoConfig.from_pretrained(model_path, trust_remote_code=True)
90
+ model = LlavaMPTForCausalLM.from_pretrained(model_base, low_cpu_mem_usage=True, config=cfg_pretrained, **kwargs)
91
+ else:
92
+ tokenizer = AutoTokenizer.from_pretrained(model_base, use_fast=False)
93
+ cfg_pretrained = AutoConfig.from_pretrained(model_path)
94
+ model = LlavaLlamaForCausalLM.from_pretrained(model_base, low_cpu_mem_usage=True, config=cfg_pretrained, **kwargs)
95
+
96
+ mm_projector_weights = torch.load(os.path.join(model_path, 'mm_projector.bin'), map_location='cpu')
97
+ mm_projector_weights = {k: v.to(torch.float16) for k, v in mm_projector_weights.items()}
98
+ model.load_state_dict(mm_projector_weights, strict=False)
99
+ else:
100
+ if 'mpt' in model_name.lower():
101
+ tokenizer = AutoTokenizer.from_pretrained(model_path, use_fast=True)
102
+ model = LlavaMPTForCausalLM.from_pretrained(model_path, low_cpu_mem_usage=True, **kwargs)
103
+ else:
104
+ try:
105
+ tokenizer = AutoTokenizer.from_pretrained(model_path, use_fast=False)
106
+ except:
107
+ tokenizer = AutoTokenizer.from_pretrained(model_path, use_fast=True)
108
+ model = LlavaLlamaForCausalLM.from_pretrained(model_path, low_cpu_mem_usage=True, **kwargs)
109
+ else:
110
+ # Load language model
111
+ if model_base is not None:
112
+ # PEFT model
113
+ from peft import PeftModel
114
+ tokenizer = AutoTokenizer.from_pretrained(model_base, use_fast=False)
115
+ model = AutoModelForCausalLM.from_pretrained(model_base, low_cpu_mem_usage=True, **kwargs)
116
+ print(f"Loading LoRA weights from {model_path}")
117
+ model = PeftModel.from_pretrained(model, model_path)
118
+ print(f"Merging weights")
119
+ model = model.merge_and_unload()
120
+ print('Convert to FP16...')
121
+ model.to(torch.float16)
122
+ else:
123
+ use_fast = False
124
+ if 'mpt' in model_name.lower():
125
+ tokenizer = AutoTokenizer.from_pretrained(model_path, use_fast=True)
126
+ model = AutoModelForCausalLM.from_pretrained(model_path, low_cpu_mem_usage=True, trust_remote_code=True, **kwargs)
127
+ else:
128
+ try:
129
+ tokenizer = AutoTokenizer.from_pretrained(model_path, use_fast=False)
130
+ except:
131
+ tokenizer = AutoTokenizer.from_pretrained(model_path, use_fast=True)
132
+ model = AutoModelForCausalLM.from_pretrained(model_path, low_cpu_mem_usage=True, **kwargs)
133
+
134
+ image_processor = None
135
+
136
+ if 'llava' in model_name.lower():
137
+ mm_use_im_start_end = getattr(model.config, "mm_use_im_start_end", False)
138
+ mm_use_im_patch_token = getattr(model.config, "mm_use_im_patch_token", True)
139
+ if mm_use_im_patch_token:
140
+ tokenizer.add_tokens([DEFAULT_IMAGE_PATCH_TOKEN], special_tokens=True)
141
+ if mm_use_im_start_end:
142
+ tokenizer.add_tokens([DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN], special_tokens=True)
143
+ model.resize_token_embeddings(len(tokenizer))
144
+
145
+ vision_tower = model.get_vision_tower()
146
+ if not vision_tower.is_loaded:
147
+ vision_tower.load_model()
148
+ vision_tower.to(device=device, dtype=torch.float16)
149
+ image_processor = vision_tower.image_processor
150
+
151
+ if hasattr(model.config, "max_sequence_length"):
152
+ context_len = model.config.max_sequence_length
153
+ else:
154
+ context_len = 2048
155
+
156
+ return tokenizer, model, image_processor, context_len
HuatuoGPT-Vision-Abla/llava/model/consolidate.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Usage:
3
+ python3 -m llava.model.consolidate --src ~/model_weights/llava-7b --dst ~/model_weights/llava-7b_consolidate
4
+ """
5
+ import argparse
6
+
7
+ import torch
8
+ from transformers import AutoTokenizer, AutoModelForCausalLM
9
+ from llava.model import *
10
+ from llava.model.utils import auto_upgrade
11
+
12
+
13
+ def consolidate_ckpt(src_path, dst_path):
14
+ print("Loading model")
15
+ auto_upgrade(src_path)
16
+ src_model = AutoModelForCausalLM.from_pretrained(src_path, torch_dtype=torch.float16, low_cpu_mem_usage=True)
17
+ src_tokenizer = AutoTokenizer.from_pretrained(src_path, use_fast=False)
18
+ src_model.save_pretrained(dst_path)
19
+ src_tokenizer.save_pretrained(dst_path)
20
+
21
+
22
+ if __name__ == "__main__":
23
+ parser = argparse.ArgumentParser()
24
+ parser.add_argument("--src", type=str, required=True)
25
+ parser.add_argument("--dst", type=str, required=True)
26
+
27
+ args = parser.parse_args()
28
+
29
+ consolidate_ckpt(args.src, args.dst)
HuatuoGPT-Vision-Abla/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/llava/model/llava_arch.py ADDED
@@ -0,0 +1,526 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
16
+ from abc import ABC, abstractmethod
17
+
18
+ import torch
19
+ import torch.nn as nn
20
+
21
+ from .multimodal_encoder.builder import build_vision_tower
22
+ from .multimodal_projector.builder import build_vision_projector
23
+
24
+ from llava.constants import IGNORE_INDEX, IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_PATCH_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN
25
+ import pdb
26
+
27
+ class LlavaMetaModel:
28
+
29
+ def __init__(self, config):
30
+ super(LlavaMetaModel, self).__init__(config)
31
+
32
+ if hasattr(config, "mm_vision_tower"):
33
+ self.vision_tower = build_vision_tower(config, delay_load=True)
34
+ self.mm_projector = build_vision_projector(config)
35
+
36
+ def get_vision_tower(self):
37
+ vision_tower = getattr(self, 'vision_tower', None)
38
+ if type(vision_tower) is list:
39
+ vision_tower = vision_tower[0]
40
+ return vision_tower
41
+
42
+ def initialize_vision_modules(self, model_args, fsdp=None):
43
+ vision_tower = model_args.vision_tower
44
+ mm_vision_select_layer = model_args.mm_vision_select_layer
45
+ mm_vision_select_feature = model_args.mm_vision_select_feature
46
+ pretrain_mm_mlp_adapter = model_args.pretrain_mm_mlp_adapter
47
+
48
+ self.config.mm_vision_tower = vision_tower
49
+
50
+ if self.get_vision_tower() is None:
51
+ vision_tower = build_vision_tower(model_args)
52
+
53
+ if fsdp is not None and len(fsdp) > 0:
54
+ self.vision_tower = [vision_tower]
55
+ else:
56
+ self.vision_tower = vision_tower
57
+ else:
58
+ if fsdp is not None and len(fsdp) > 0:
59
+ vision_tower = self.vision_tower[0]
60
+ else:
61
+ vision_tower = self.vision_tower
62
+ vision_tower.load_model()
63
+
64
+ self.config.use_mm_proj = True
65
+ self.config.mm_projector_type = getattr(model_args, 'mm_projector_type', 'linear')
66
+ self.config.mm_hidden_size = vision_tower.hidden_size
67
+ self.config.mm_vision_select_layer = mm_vision_select_layer
68
+ self.config.mm_vision_select_feature = mm_vision_select_feature
69
+
70
+ if getattr(self, 'mm_projector', None) is None:
71
+ self.mm_projector = build_vision_projector(self.config)
72
+ else:
73
+ # In case it is frozen by LoRA
74
+ for p in self.mm_projector.parameters():
75
+ p.requires_grad = True
76
+
77
+ if pretrain_mm_mlp_adapter is not None:
78
+ mm_projector_weights = torch.load(pretrain_mm_mlp_adapter, map_location='cpu')
79
+ def get_w(weights, keyword):
80
+ return {k.split(keyword + '.')[1]: v for k, v in weights.items() if keyword in k}
81
+
82
+ self.mm_projector.load_state_dict(get_w(mm_projector_weights, 'mm_projector'))
83
+
84
+
85
+ class LlavaMetaForCausalLM(ABC):
86
+
87
+ @abstractmethod
88
+ def get_model(self):
89
+ pass
90
+
91
+ @abstractmethod
92
+ def get_tokenizer(self):
93
+ pass
94
+
95
+ def get_vision_tower(self):
96
+ return self.get_model().get_vision_tower()
97
+
98
+ def encode_images(self, images):
99
+ image_features = self.get_model().get_vision_tower()(images)
100
+ image_features = self.get_model().mm_projector(image_features)
101
+ return image_features
102
+
103
+ def prepare_inputs_labels_for_multimodal(
104
+ self, input_ids, position_ids, attention_mask, past_key_values, labels, images
105
+ ):
106
+ vision_tower = self.get_vision_tower()
107
+ if vision_tower is None or images is None or input_ids.shape[1] == 1:
108
+ if past_key_values is not None and vision_tower is not None and images is not None and input_ids.shape[1] == 1:
109
+ target_shape = past_key_values[-1][-1].shape[-2] + 1
110
+ attention_mask = torch.cat((attention_mask, torch.ones(
111
+ (attention_mask.shape[0], target_shape - attention_mask.shape[1]),
112
+ dtype=attention_mask.dtype,
113
+ device=attention_mask.device
114
+ )), dim=1)
115
+ position_ids = torch.sum(attention_mask, dim=1).unsqueeze(-1) - 1
116
+ return input_ids, position_ids, attention_mask, past_key_values, None, labels
117
+
118
+ if type(images) is list or images.ndim == 5:
119
+ concat_images = torch.cat([image for image in images], dim=0)
120
+ image_features = self.encode_images(concat_images)
121
+ split_sizes = [image.shape[0] for image in images]
122
+ image_features = torch.split(image_features, split_sizes, dim=0)
123
+ image_features = [x.flatten(0, 1).to(self.device) for x in image_features]
124
+ else:
125
+ image_features = self.encode_images(images).to(self.device)
126
+
127
+ # TODO: image start / end is not implemented here to support pretraining.
128
+ if getattr(self.config, 'tune_mm_mlp_adapter', False) and getattr(self.config, 'mm_use_im_start_end', False):
129
+ raise NotImplementedError
130
+
131
+ # Let's just add dummy tensors if they do not exist,
132
+ # it is a headache to deal with None all the time.
133
+ # But it is not ideal, and if you have a better idea,
134
+ # please open an issue / submit a PR, thanks.
135
+ _labels = labels
136
+ _position_ids = position_ids
137
+ _attention_mask = attention_mask
138
+ if attention_mask is None:
139
+ attention_mask = torch.ones_like(input_ids, dtype=torch.bool)
140
+ else:
141
+ attention_mask = attention_mask.bool()
142
+ if position_ids is None:
143
+ position_ids = torch.arange(0, input_ids.shape[1], dtype=torch.long, device=input_ids.device)
144
+ if labels is None:
145
+ labels = torch.full_like(input_ids, IGNORE_INDEX)
146
+
147
+ # remove the padding using attention_mask -- TODO: double check
148
+ input_ids = [cur_input_ids[cur_attention_mask] for cur_input_ids, cur_attention_mask in zip(input_ids, attention_mask)]
149
+ labels = [cur_labels[cur_attention_mask] for cur_labels, cur_attention_mask in zip(labels, attention_mask)]
150
+
151
+ new_input_embeds = []
152
+ new_labels = []
153
+ cur_image_idx = 0
154
+ for batch_idx, cur_input_ids in enumerate(input_ids):
155
+ num_images = (cur_input_ids == IMAGE_TOKEN_INDEX).sum()
156
+ if num_images == 0:
157
+ cur_image_features = image_features[cur_image_idx]
158
+ cur_input_embeds_1 = self.get_model().embed_tokens(cur_input_ids)
159
+ cur_input_embeds = torch.cat([cur_input_embeds_1, cur_image_features[0:0]], dim=0)
160
+ new_input_embeds.append(cur_input_embeds)
161
+ new_labels.append(labels[batch_idx])
162
+ cur_image_idx += 1
163
+ continue
164
+
165
+ image_token_indices = [-1] + torch.where(cur_input_ids == IMAGE_TOKEN_INDEX)[0].tolist() + [cur_input_ids.shape[0]]
166
+ cur_input_ids_noim = []
167
+ cur_labels = labels[batch_idx]
168
+ cur_labels_noim = []
169
+ for i in range(len(image_token_indices) - 1):
170
+ cur_input_ids_noim.append(cur_input_ids[image_token_indices[i]+1:image_token_indices[i+1]])
171
+ cur_labels_noim.append(cur_labels[image_token_indices[i]+1:image_token_indices[i+1]])
172
+ split_sizes = [x.shape[0] for x in cur_labels_noim]
173
+ cur_input_embeds = self.get_model().embed_tokens(torch.cat(cur_input_ids_noim))
174
+ cur_input_embeds_no_im = torch.split(cur_input_embeds, split_sizes, dim=0)
175
+ cur_new_input_embeds = []
176
+ cur_new_labels = []
177
+
178
+ for i in range(num_images + 1):
179
+ cur_new_input_embeds.append(cur_input_embeds_no_im[i])
180
+ cur_new_labels.append(cur_labels_noim[i])
181
+ if i < num_images:
182
+ cur_image_features = image_features[cur_image_idx]
183
+ cur_image_idx += 1
184
+ cur_new_input_embeds.append(cur_image_features)
185
+ cur_new_labels.append(torch.full((cur_image_features.shape[0],), IGNORE_INDEX, device=cur_labels.device, dtype=cur_labels.dtype))
186
+
187
+ cur_new_input_embeds = torch.cat(cur_new_input_embeds)
188
+ cur_new_labels = torch.cat(cur_new_labels)
189
+
190
+ new_input_embeds.append(cur_new_input_embeds)
191
+ new_labels.append(cur_new_labels)
192
+
193
+ # Truncate sequences to max length as image embeddings can make the sequence longer
194
+ tokenizer_model_max_length = getattr(self.config, 'tokenizer_model_max_length', None)
195
+ if tokenizer_model_max_length is not None:
196
+ new_input_embeds = [x[:tokenizer_model_max_length] for x in new_input_embeds]
197
+ new_labels = [x[:tokenizer_model_max_length] for x in new_labels]
198
+
199
+ # Combine them
200
+ max_len = max(x.shape[0] for x in new_input_embeds)
201
+ batch_size = len(new_input_embeds)
202
+
203
+ new_input_embeds_padded = []
204
+ new_labels_padded = torch.full((batch_size, max_len), IGNORE_INDEX, dtype=new_labels[0].dtype, device=new_labels[0].device)
205
+ attention_mask = torch.zeros((batch_size, max_len), dtype=attention_mask.dtype, device=attention_mask.device)
206
+ position_ids = torch.zeros((batch_size, max_len), dtype=position_ids.dtype, device=position_ids.device)
207
+
208
+ for i, (cur_new_embed, cur_new_labels) in enumerate(zip(new_input_embeds, new_labels)):
209
+ cur_len = cur_new_embed.shape[0]
210
+ if getattr(self.config, 'tokenizer_padding_side', 'right') == "left":
211
+ new_input_embeds_padded.append(torch.cat((
212
+ torch.zeros((max_len - cur_len, cur_new_embed.shape[1]), dtype=cur_new_embed.dtype, device=cur_new_embed.device),
213
+ cur_new_embed
214
+ ), dim=0))
215
+ if cur_len > 0:
216
+ new_labels_padded[i, -cur_len:] = cur_new_labels
217
+ attention_mask[i, -cur_len:] = True
218
+ position_ids[i, -cur_len:] = torch.arange(0, cur_len, dtype=position_ids.dtype, device=position_ids.device)
219
+ else:
220
+ new_input_embeds_padded.append(torch.cat((
221
+ cur_new_embed,
222
+ torch.zeros((max_len - cur_len, cur_new_embed.shape[1]), dtype=cur_new_embed.dtype, device=cur_new_embed.device)
223
+ ), dim=0))
224
+ if cur_len > 0:
225
+ new_labels_padded[i, :cur_len] = cur_new_labels
226
+ attention_mask[i, :cur_len] = True
227
+ position_ids[i, :cur_len] = torch.arange(0, cur_len, dtype=position_ids.dtype, device=position_ids.device)
228
+
229
+ new_input_embeds = torch.stack(new_input_embeds_padded, dim=0)
230
+
231
+ if _labels is None:
232
+ new_labels = None
233
+ else:
234
+ new_labels = new_labels_padded
235
+
236
+ if _attention_mask is None:
237
+ attention_mask = None
238
+ else:
239
+ attention_mask = attention_mask.to(dtype=_attention_mask.dtype)
240
+
241
+ if _position_ids is None:
242
+ position_ids = None
243
+
244
+ return None, position_ids, attention_mask, past_key_values, new_input_embeds, new_labels
245
+
246
+ def prepare_inputs_labels_for_multimodal_new(
247
+ self, input_ids: list[torch.tensor], position_ids, attention_mask: list[torch.tensor], past_key_values, labels, images
248
+ ):
249
+ vision_tower = self.get_vision_tower()
250
+ # pdb.set_trace()
251
+ if not self.training: # TODO: check this out!!
252
+ # isinstance(input_ids, torch.Tensor) ensures that we won't enter this when doing evaluation at training
253
+ if vision_tower is None or images is None or (isinstance(input_ids, torch.Tensor) and input_ids.shape[1] == 1):
254
+ if past_key_values is not None and vision_tower is not None and images is not None and input_ids.shape[1] == 1:
255
+ target_shape = past_key_values[-1][-1].shape[-2] + 1
256
+ attention_mask = torch.cat((attention_mask, torch.ones(
257
+ (attention_mask.shape[0], target_shape - attention_mask.shape[1]),
258
+ dtype=attention_mask.dtype,
259
+ device=attention_mask.device
260
+ )), dim=1)
261
+ position_ids = torch.sum(attention_mask, dim=1).unsqueeze(-1) - 1
262
+ return input_ids, position_ids, attention_mask, past_key_values, None, labels
263
+
264
+ if (len(images) == 0):
265
+ image_features = []
266
+ elif type(images) is list or images.ndim == 5:
267
+ # concat_images = torch.cat([image for image in images], dim=0)
268
+ # image_features = self.encode_images(concat_images)
269
+ # split_sizes = [image.shape[0] for image in images]
270
+ # image_features = torch.split(image_features, split_sizes, dim=0)
271
+ # image_features = [x.flatten(0, 1).to(self.device) for x in image_features]
272
+
273
+ if type(images) is list:
274
+ images = [x.unsqueeze(0) if x.ndim == 3 else x for x in images]
275
+ concat_images = torch.cat([image for image in images], dim=0)
276
+ image_features = self.encode_images(concat_images)
277
+ split_sizes = [image.shape[0] for image in images]
278
+ image_features = torch.split(image_features, split_sizes, dim=0)
279
+
280
+ mm_patch_merge_type = getattr(self.config, 'mm_patch_merge_type', 'flat')
281
+ image_aspect_ratio = getattr(self.config, 'image_aspect_ratio', 'square')
282
+ if mm_patch_merge_type == 'flat':
283
+ image_features = [x.flatten(0, 1) for x in image_features]
284
+ elif mm_patch_merge_type.startswith('spatial'):
285
+ new_image_features = []
286
+ for image_idx, image_feature in enumerate(image_features):
287
+ if image_feature.shape[0] > 1:
288
+ base_image_feature = image_feature[0]
289
+ image_feature = image_feature[1:]
290
+ height = width = self.get_vision_tower().num_patches_per_side
291
+ assert height * width == base_image_feature.shape[0]
292
+ if 'anyres' in image_aspect_ratio:
293
+ # num_patch_width, num_patch_height = get_anyres_image_grid_shape(image_sizes[image_idx], self.config.image_grid_pinpoints, self.get_vision_tower().config.image_size)
294
+ patch_size = self.get_vision_tower().config.image_size
295
+ # 默认都是选第一个
296
+ big_width, big_height = self.config.image_grid_pinpoints[0]
297
+ num_patch_width, num_patch_height = big_width // patch_size, big_height // patch_size
298
+ image_feature = image_feature.view(num_patch_height, num_patch_width, height, width, -1)
299
+ else:
300
+ raise NotImplementedError
301
+ # if 'unpad' in mm_patch_merge_type:
302
+ # image_feature = image_feature.permute(4, 0, 2, 1, 3).contiguous()
303
+ # image_feature = image_feature.flatten(1, 2).flatten(2, 3)
304
+ # image_feature = unpad_image(image_feature, image_sizes[image_idx])
305
+ # image_feature = torch.cat((
306
+ # image_feature,
307
+ # self.model.image_newline[:, None, None].expand(*image_feature.shape[:-1], 1).to(image_feature.device)
308
+ # ), dim=-1)
309
+ # image_feature = image_feature.flatten(1, 2).transpose(0, 1)
310
+ # else:
311
+ image_feature = image_feature.permute(0, 2, 1, 3, 4).contiguous()
312
+ image_feature = image_feature.flatten(0, 3)
313
+ image_feature = torch.cat((base_image_feature, image_feature), dim=0)
314
+ else:
315
+ image_feature = image_feature[0]
316
+ new_image_features.append(image_feature)
317
+ image_features = new_image_features
318
+ else:
319
+ raise ValueError(f"Unexpected mm_patch_merge_type: {self.config.mm_patch_merge_type}")
320
+ else:
321
+ # print(f'trained image shape {images.shape}')
322
+ image_features = self.encode_images(images).to(self.device)
323
+
324
+ # TODO: image start / end is not implemented here to support pretraining.
325
+ if getattr(self.config, 'tune_mm_mlp_adapter', False) and getattr(self.config, 'mm_use_im_start_end', False):
326
+ raise NotImplementedError
327
+
328
+ # Let's just add dummy tensors if they do not exist,
329
+ # it is a headache to deal with None all the time.
330
+ # But it is not ideal, and if you have a better idea,
331
+ # please open an issue / submit a PR, thanks.
332
+ _labels = labels
333
+ _position_ids = position_ids
334
+ _attention_mask = attention_mask
335
+ if attention_mask is None:
336
+ # attention_mask = torch.ones_like(input_ids, dtype=torch.bool)
337
+ attention_mask = [torch.tensor([1]*l).to(input_ids).bool() for l in map(len, [ip for ip in input_ids])]
338
+ else:
339
+ # attention_mask = attention_mask.bool()
340
+ attention_mask = [att.bool() for att in attention_mask]
341
+
342
+ # if position_ids is None:
343
+ # position_ids = torch.arange(0, input_ids.shape[1], dtype=torch.long, device=input_ids.device)
344
+ input_ids = [cur_input_ids[cur_attention_mask] for cur_input_ids, cur_attention_mask in zip(input_ids, attention_mask)]
345
+
346
+ if labels is None:
347
+ labels = [torch.tensor([IGNORE_INDEX]*l).to(input_ids[0]) for l in map(len, [ip for ip in input_ids])]
348
+ # labels = torch.full_like(input_ids, IGNORE_INDEX)
349
+ else:
350
+ labels = [cur_labels[cur_attention_mask] for cur_labels, cur_attention_mask in zip(labels, attention_mask)]
351
+
352
+ new_input_embeds = []
353
+ new_labels = []
354
+ cur_image_idx = 0
355
+ for batch_idx, cur_input_ids in enumerate(input_ids):
356
+ num_images = (cur_input_ids == IMAGE_TOKEN_INDEX).sum()
357
+
358
+ # if num_images == 0:
359
+ # new_input_embeds.append(self.get_model().embed_tokens(cur_input_ids))
360
+ # new_labels.append(labels[batch_idx])
361
+ # continue
362
+
363
+
364
+ if num_images == 0:
365
+ if len(image_features) == 0:
366
+ new_input_embeds.append(self.get_model().embed_tokens(cur_input_ids))
367
+ new_labels.append(labels[batch_idx])
368
+ continue
369
+
370
+ ############### FIXME ###############
371
+ if cur_image_idx > len(image_features)-1:
372
+ cur_image_idx = len(image_features)-1
373
+ print(f'warning: {input_ids}')
374
+ ############### FIXME ###############
375
+
376
+ cur_image_features = image_features[cur_image_idx]
377
+ if cur_input_ids is None:
378
+ pdb.set_trace()
379
+ cur_input_embeds_1 = self.get_model().embed_tokens(cur_input_ids)
380
+ cur_input_embeds = torch.cat([cur_input_embeds_1, cur_image_features[0:0]], dim=0)
381
+ new_input_embeds.append(cur_input_embeds)
382
+ new_labels.append(labels[batch_idx])
383
+ cur_image_idx += 1
384
+ continue
385
+
386
+ image_token_indices = [-1] + torch.where(cur_input_ids == IMAGE_TOKEN_INDEX)[0].tolist() + [cur_input_ids.shape[0]]
387
+ cur_input_ids_noim = []
388
+ cur_labels = labels[batch_idx]
389
+ cur_labels_noim = []
390
+ for i in range(len(image_token_indices) - 1):
391
+ cur_input_ids_noim.append(cur_input_ids[image_token_indices[i]+1:image_token_indices[i+1]])
392
+ cur_labels_noim.append(cur_labels[image_token_indices[i]+1:image_token_indices[i+1]])
393
+ split_sizes = [x.shape[0] for x in cur_labels_noim]
394
+ cur_input_embeds = self.get_model().embed_tokens(torch.cat(cur_input_ids_noim))
395
+ cur_input_embeds_no_im = torch.split(cur_input_embeds, split_sizes, dim=0)
396
+ cur_new_input_embeds = []
397
+ cur_new_labels = []
398
+
399
+ # you have 10 images, but you have 11 placeholders
400
+ for i in range(num_images + 1):
401
+ cur_new_input_embeds.append(cur_input_embeds_no_im[i])
402
+ cur_new_labels.append(cur_labels_noim[i])
403
+ if i < num_images:
404
+ ############### FIXME ###############
405
+ if cur_image_idx > len(image_features)-1:
406
+ cur_image_idx = len(image_features)-1
407
+ print(f'warning: {input_ids}')
408
+ ############### FIXME ###############
409
+
410
+ cur_image_features = image_features[cur_image_idx]
411
+ cur_image_idx += 1
412
+ cur_new_input_embeds.append(cur_image_features)
413
+ cur_new_labels.append(torch.full((cur_image_features.shape[0],), IGNORE_INDEX, device=cur_labels.device, dtype=cur_labels.dtype))
414
+
415
+ cur_new_input_embeds = torch.cat(cur_new_input_embeds)
416
+ cur_new_labels = torch.cat(cur_new_labels)
417
+
418
+ new_input_embeds.append(cur_new_input_embeds)
419
+ new_labels.append(cur_new_labels)
420
+
421
+ # assert images are not offser
422
+ assert cur_image_idx == len(image_features), f'wrong!! cur_image_idx != len(image_features) cur_image_idx:{cur_image_idx} len(image_features):{len(image_features)}'
423
+
424
+ # Truncate sequences to max length as image embeddings can make the sequence longer
425
+ tokenizer_model_max_length = getattr(self.config, 'tokenizer_model_max_length', None)
426
+ if tokenizer_model_max_length is not None:
427
+ new_input_embeds = [x[:tokenizer_model_max_length] for x in new_input_embeds]
428
+ new_labels = [x[:tokenizer_model_max_length] for x in new_labels]
429
+
430
+ # Combine them
431
+ max_len = max(x.shape[0] for x in new_input_embeds)
432
+ batch_size = len(new_input_embeds)
433
+
434
+ new_input_embeds_padded = []
435
+ new_labels_padded = torch.full((batch_size, max_len), IGNORE_INDEX, dtype=new_labels[0].dtype, device=new_labels[0].device)
436
+ attention_mask = torch.zeros((batch_size, max_len), dtype=torch.bool, device=attention_mask[0].device)
437
+ position_ids = torch.zeros((batch_size, max_len), dtype=torch.long, device=attention_mask[0].device)
438
+
439
+ for i, (cur_new_embed, cur_new_labels) in enumerate(zip(new_input_embeds, new_labels)):
440
+ cur_len = cur_new_embed.shape[0]
441
+ # print(f'cur_len[{i}]before padding: {cur_len}')
442
+ # if i==0:
443
+ # print(f"{getattr(self.config, 'tokenizer_padding_side', 'right')} {self.get_tokenizer().padding_side}")
444
+ if getattr(self.config, 'tokenizer_padding_side', 'right') == "left": # checked, this is correct
445
+ # if self.get_tokenizer().padding_side == 'left':
446
+ new_input_embeds_padded.append(torch.cat((
447
+ torch.zeros((max_len - cur_len, cur_new_embed.shape[1]), dtype=cur_new_embed.dtype, device=cur_new_embed.device),
448
+ cur_new_embed
449
+ ), dim=0))
450
+ if cur_len > 0:
451
+ new_labels_padded[i, -cur_len:] = cur_new_labels
452
+ attention_mask[i, -cur_len:] = True
453
+ position_ids[i, -cur_len:] = torch.arange(0, cur_len, dtype=position_ids.dtype, device=position_ids.device)
454
+ else:
455
+ new_input_embeds_padded.append(torch.cat((
456
+ cur_new_embed,
457
+ torch.zeros((max_len - cur_len, cur_new_embed.shape[1]), dtype=cur_new_embed.dtype, device=cur_new_embed.device)
458
+ ), dim=0))
459
+ if cur_len > 0:
460
+ new_labels_padded[i, :cur_len] = cur_new_labels
461
+ attention_mask[i, :cur_len] = True
462
+ position_ids[i, :cur_len] = torch.arange(0, cur_len, dtype=position_ids.dtype, device=position_ids.device)
463
+
464
+ new_input_embeds = torch.stack(new_input_embeds_padded, dim=0)
465
+
466
+ if _labels is None:
467
+ new_labels = None
468
+ else:
469
+ new_labels = new_labels_padded
470
+
471
+ if _attention_mask is None:
472
+ attention_mask = None
473
+ else:
474
+ # attention_mask = attention_mask.to(dtype=_attention_mask.dtype)
475
+ attention_mask = attention_mask.to(dtype=torch.bool)
476
+
477
+ if _position_ids is None:
478
+ position_ids = None
479
+
480
+ # print(new_input_embeds.shape) # should be
481
+
482
+ return None, position_ids, attention_mask, past_key_values, new_input_embeds, new_labels
483
+
484
+ def initialize_vision_tokenizer(self, model_args, tokenizer):
485
+ if model_args.mm_use_im_patch_token:
486
+ tokenizer.add_tokens([DEFAULT_IMAGE_PATCH_TOKEN], special_tokens=True)
487
+ self.resize_token_embeddings(len(tokenizer))
488
+
489
+ if model_args.mm_use_im_start_end:
490
+ num_new_tokens = tokenizer.add_tokens([DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN], special_tokens=True)
491
+ self.resize_token_embeddings(len(tokenizer))
492
+
493
+ if num_new_tokens > 0:
494
+ input_embeddings = self.get_input_embeddings().weight.data
495
+ output_embeddings = self.get_output_embeddings().weight.data
496
+
497
+ input_embeddings_avg = input_embeddings[:-num_new_tokens].mean(
498
+ dim=0, keepdim=True)
499
+ output_embeddings_avg = output_embeddings[:-num_new_tokens].mean(
500
+ dim=0, keepdim=True)
501
+
502
+ input_embeddings[-num_new_tokens:] = input_embeddings_avg
503
+ output_embeddings[-num_new_tokens:] = output_embeddings_avg
504
+
505
+ if model_args.tune_mm_mlp_adapter:
506
+ for p in self.get_input_embeddings().parameters():
507
+ p.requires_grad = True
508
+ for p in self.get_output_embeddings().parameters():
509
+ p.requires_grad = False
510
+
511
+ if model_args.pretrain_mm_mlp_adapter:
512
+ mm_projector_weights = torch.load(model_args.pretrain_mm_mlp_adapter, map_location='cpu')
513
+ embed_tokens_weight = mm_projector_weights['model.embed_tokens.weight']
514
+ assert num_new_tokens == 2
515
+ if input_embeddings.shape == embed_tokens_weight.shape:
516
+ input_embeddings[-num_new_tokens:] = embed_tokens_weight[-num_new_tokens:]
517
+ elif embed_tokens_weight.shape[0] == num_new_tokens:
518
+ input_embeddings[-num_new_tokens:] = embed_tokens_weight
519
+ else:
520
+ raise ValueError(f"Unexpected embed_tokens_weight shape. Pretrained: {embed_tokens_weight.shape}. Current: {input_embeddings.shape}. Numer of new tokens: {num_new_tokens}.")
521
+ elif model_args.mm_use_im_patch_token:
522
+ if model_args.tune_mm_mlp_adapter:
523
+ for p in self.get_input_embeddings().parameters():
524
+ p.requires_grad = False
525
+ for p in self.get_output_embeddings().parameters():
526
+ p.requires_grad = False
HuatuoGPT-Vision-Abla/llava/model/make_delta.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Usage:
3
+ python3 -m llava.model.make_delta --base ~/model_weights/llama-7b --target ~/model_weights/llava-7b --delta ~/model_weights/llava-7b-delta --hub-repo-id liuhaotian/llava-7b-delta
4
+ """
5
+ import argparse
6
+
7
+ import torch
8
+ from tqdm import tqdm
9
+ from transformers import AutoTokenizer, AutoModelForCausalLM
10
+ from llava.model.utils import auto_upgrade
11
+
12
+
13
+ def make_delta(base_model_path, target_model_path, delta_path, hub_repo_id):
14
+ print("Loading base model")
15
+ base = AutoModelForCausalLM.from_pretrained(
16
+ base_model_path, torch_dtype=torch.float16, low_cpu_mem_usage=True)
17
+
18
+ print("Loading target model")
19
+ auto_upgrade(target_model_path)
20
+ target = AutoModelForCausalLM.from_pretrained(target_model_path, torch_dtype=torch.float16, low_cpu_mem_usage=True)
21
+
22
+ print("Calculating delta")
23
+ for name, param in tqdm(target.state_dict().items(), desc="Calculating delta"):
24
+ if name not in base.state_dict():
25
+ assert name in ['model.mm_projector.weight', 'model.mm_projector.bias'], f'{name} not in base model'
26
+ continue
27
+ if param.data.shape == base.state_dict()[name].shape:
28
+ param.data -= base.state_dict()[name]
29
+ else:
30
+ assert name in ['model.embed_tokens.weight', 'lm_head.weight'], f'{name} dimension mismatch: {param.data.shape} vs {base.state_dict()[name].shape}'
31
+ bparam = base.state_dict()[name]
32
+ param.data[:bparam.shape[0], :bparam.shape[1]] -= bparam
33
+
34
+ print("Saving delta")
35
+ if hub_repo_id:
36
+ kwargs = {"push_to_hub": True, "repo_id": hub_repo_id}
37
+ else:
38
+ kwargs = {}
39
+ target.save_pretrained(delta_path, **kwargs)
40
+ target_tokenizer = AutoTokenizer.from_pretrained(target_model_path)
41
+ target_tokenizer.save_pretrained(delta_path, **kwargs)
42
+
43
+
44
+ if __name__ == "__main__":
45
+ parser = argparse.ArgumentParser()
46
+ parser.add_argument("--base-model-path", type=str, required=True)
47
+ parser.add_argument("--target-model-path", type=str, required=True)
48
+ parser.add_argument("--delta-path", type=str, required=True)
49
+ parser.add_argument("--hub-repo-id", type=str, default=None)
50
+ args = parser.parse_args()
51
+
52
+ make_delta(args.base_model_path, args.target_model_path, args.delta_path, args.hub_repo_id)
HuatuoGPT-Vision-Abla/llava/model/multimodal_encoder/__pycache__/builder.cpython-310.pyc ADDED
Binary file (738 Bytes). View file
 
HuatuoGPT-Vision-Abla/llava/model/multimodal_encoder/__pycache__/clip_encoder.cpython-310.pyc ADDED
Binary file (3.41 kB). View file
 
HuatuoGPT-Vision-Abla/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/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/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/llava/model/utils.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import AutoConfig
2
+
3
+
4
+ def auto_upgrade(config):
5
+ cfg = AutoConfig.from_pretrained(config)
6
+ if 'llava' in config and 'llava' not in cfg.model_type:
7
+ assert cfg.model_type == 'llama'
8
+ print("You are using newer LLaVA code base, while the checkpoint of v0 is from older code base.")
9
+ print("You must upgrade the checkpoint to the new code base (this can be done automatically).")
10
+ confirm = input("Please confirm that you want to upgrade the checkpoint. [Y/N]")
11
+ if confirm.lower() in ["y", "yes"]:
12
+ print("Upgrading checkpoint...")
13
+ assert len(cfg.architectures) == 1
14
+ setattr(cfg.__class__, "model_type", "llava")
15
+ cfg.architectures[0] = 'LlavaLlamaForCausalLM'
16
+ cfg.save_pretrained(config)
17
+ print("Checkpoint upgraded.")
18
+ else:
19
+ print("Checkpoint upgrade aborted.")
20
+ exit(1)
HuatuoGPT-Vision-Abla/requirements.txt ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ torch==2.0.1
2
+ accelerate==0.21.0
3
+ bitsandbytes==0.41.0
4
+ deepspeed==0.9.5
5
+ einops-exts==0.0.4
6
+ einops==0.6.1
7
+ httpx==0.24.0
8
+ markdown2==2.4.10
9
+ numpy==1.26.0
10
+ peft==0.4.0
11
+ scikit-learn==1.2.2
12
+ sentencepiece==0.1.99
13
+ shortuuid==1.0.11
14
+ timm==0.6.13
15
+ tokenizers==0.13.3
16
+ wandb==0.15.12
17
+ wavedrom==2.0.3.post3
18
+ Pygments==2.16.1
19
+ transformers==4.37.2
HuatuoGPT-Vision-Abla/run_eval_attnbias_sam_both_amplify_only.sh ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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_amplify_only"
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
+ # Ablation: amplify-only. Key positions still get the positive bias, but
15
+ # nonkey_bias_* is 0 instead of negative -- isolates how much of the "both"
16
+ # result comes from amplifying keyword text / SAM patches, with no suppression
17
+ # of distractors. Auction stays ON with the same ratio/alpha/beta as
18
+ # run_eval_attnbias_sam_both.sh, so this differs from "both" by exactly one
19
+ # factor (nonkey_bias_*); compare against run_eval_attnbias_sam_both_suppress_only.sh
20
+ # (same setup, opposite side zeroed) and run_eval_attnbias_sam_both.sh.
21
+ INTERVENTION="both"
22
+ ATTN_LAYERS_TEXT=17
23
+ ATTN_KEY_BIAS_TEXT=5.0
24
+ ATTN_NONKEY_BIAS_TEXT=0.0
25
+ ATTN_LAYERS_VIS=17
26
+ ATTN_KEY_BIAS_VIS=1.0
27
+ ATTN_NONKEY_BIAS_VIS=0.0
28
+
29
+ AUCTION_TOTAL_RATIO=0.8
30
+ AUCTION_NEG_RATIO=0.8
31
+
32
+ MAX_SAMPLES=""
33
+
34
+ accelerate launch --num_processes=1 eval_attnbias_sam.py \
35
+ --data_path "$DATA_PATH" \
36
+ --model_path "$MODEL_PATH" \
37
+ --seed "$SEED" \
38
+ --max_new_tokens "$MAX_NEW_TOKENS" \
39
+ --output_path "$OUTPUT_PATH" \
40
+ --intervention "$INTERVENTION" \
41
+ --attn_layers_text "$ATTN_LAYERS_TEXT" \
42
+ --attn_key_bias_text "$ATTN_KEY_BIAS_TEXT" \
43
+ --attn_nonkey_bias_text "$ATTN_NONKEY_BIAS_TEXT" \
44
+ --attn_layers_vis "$ATTN_LAYERS_VIS" \
45
+ --attn_key_bias_vis "$ATTN_KEY_BIAS_VIS" \
46
+ --attn_nonkey_bias_vis "$ATTN_NONKEY_BIAS_VIS" \
47
+ --medsam3_config "$MEDSAM3_CONFIG" \
48
+ --medsam3_dir "$MEDSAM3_DIR" \
49
+ --auction_enable \
50
+ --auction_total_ratio "$AUCTION_TOTAL_RATIO" \
51
+ --auction_neg_ratio "$AUCTION_NEG_RATIO" \
52
+ ${MAX_SAMPLES:+--max_samples "$MAX_SAMPLES"}
HuatuoGPT-Vision-Abla/run_eval_attnbias_sam_both_noauction.sh ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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_noauction"
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
+ # both mode, auction OFF (legacy behavior): every SAM patch / scispaCy keyword
15
+ # gets amplified, everything else gets suppressed -- no scoring, no budget. This
16
+ # is the "before" half of the main ablation: none vs both-noauction vs both+auction.
17
+ INTERVENTION="both"
18
+ ATTN_LAYERS_TEXT=17
19
+ ATTN_KEY_BIAS_TEXT=5.0
20
+ ATTN_NONKEY_BIAS_TEXT=0
21
+ ATTN_LAYERS_VIS=17
22
+ ATTN_KEY_BIAS_VIS=1.0
23
+ ATTN_NONKEY_BIAS_VIS=0
24
+
25
+ MAX_SAMPLES=""
26
+
27
+ accelerate launch --num_processes=1 eval_attnbias_sam.py \
28
+ --data_path "$DATA_PATH" \
29
+ --model_path "$MODEL_PATH" \
30
+ --seed "$SEED" \
31
+ --max_new_tokens "$MAX_NEW_TOKENS" \
32
+ --output_path "$OUTPUT_PATH" \
33
+ --intervention "$INTERVENTION" \
34
+ --attn_layers_text "$ATTN_LAYERS_TEXT" \
35
+ --attn_key_bias_text "$ATTN_KEY_BIAS_TEXT" \
36
+ --attn_nonkey_bias_text "$ATTN_NONKEY_BIAS_TEXT" \
37
+ --attn_layers_vis "$ATTN_LAYERS_VIS" \
38
+ --attn_key_bias_vis "$ATTN_KEY_BIAS_VIS" \
39
+ --attn_nonkey_bias_vis "$ATTN_NONKEY_BIAS_VIS" \
40
+ --medsam3_config "$MEDSAM3_CONFIG" \
41
+ --medsam3_dir "$MEDSAM3_DIR" \
42
+ ${MAX_SAMPLES:+--max_samples "$MAX_SAMPLES"}
HuatuoGPT-Vision-Abla/run_eval_attnbias_sam_both_random.sh ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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_random"
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
+ # Ablation control: same "both" bias strengths/layers as
15
+ # run_eval_attnbias_sam_both.sh (amplify-only, auction OFF), but the scispaCy
16
+ # keyword positions and SAM bbox patches are each replaced
17
+ # (--ablation_random_text/--ablation_random_vis) with an equal-count RANDOM
18
+ # sample from the same candidate pool (all question text tokens / full 24x24
19
+ # visual grid, excluding the true key positions), seeded by $SEED for
20
+ # reproducibility. This differs from the final method by exactly one factor
21
+ # (random vs real key positions) -- tests whether gains come from biasing the
22
+ # *semantically correct* tokens, or merely from biasing *some* tokens of the
23
+ # same count. Compare this run's accuracy against run_eval_attnbias_sam_both.sh.
24
+ INTERVENTION="both"
25
+ ATTN_LAYERS_TEXT=17
26
+ ATTN_KEY_BIAS_TEXT=5.0
27
+ ATTN_NONKEY_BIAS_TEXT=0
28
+ ATTN_LAYERS_VIS=17
29
+ ATTN_KEY_BIAS_VIS=1.0
30
+ ATTN_NONKEY_BIAS_VIS=0
31
+
32
+ MAX_SAMPLES=""
33
+
34
+ accelerate launch --num_processes=1 eval_attnbias_sam.py \
35
+ --data_path "$DATA_PATH" \
36
+ --model_path "$MODEL_PATH" \
37
+ --seed "$SEED" \
38
+ --max_new_tokens "$MAX_NEW_TOKENS" \
39
+ --output_path "$OUTPUT_PATH" \
40
+ --intervention "$INTERVENTION" \
41
+ --attn_layers_text "$ATTN_LAYERS_TEXT" \
42
+ --attn_key_bias_text "$ATTN_KEY_BIAS_TEXT" \
43
+ --attn_nonkey_bias_text "$ATTN_NONKEY_BIAS_TEXT" \
44
+ --attn_layers_vis "$ATTN_LAYERS_VIS" \
45
+ --attn_key_bias_vis "$ATTN_KEY_BIAS_VIS" \
46
+ --attn_nonkey_bias_vis "$ATTN_NONKEY_BIAS_VIS" \
47
+ --medsam3_config "$MEDSAM3_CONFIG" \
48
+ --medsam3_dir "$MEDSAM3_DIR" \
49
+ --ablation_random_text \
50
+ --ablation_random_vis \
51
+ ${MAX_SAMPLES:+--max_samples "$MAX_SAMPLES"}
HuatuoGPT-Vision-Abla/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-Abla/MedSAM3/configs/full_lora_config.yaml"
12
+ MEDSAM3_DIR="/home/jinhua/ExplainableVQA/HuatuoGPT-Vision-Abla/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=3.0
18
+ ATTN_NONKEY_BIAS_TEXT=-3.0
19
+ ATTN_LAYERS_VIS="17"
20
+ ATTN_KEY_BIAS_VIS=3.0
21
+ ATTN_NONKEY_BIAS_VIS=-3.0
22
+
23
+ MAX_SAMPLES=""
24
+
25
+ accelerate launch --num_processes=1 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:+--max_samples "$MAX_SAMPLES"}
HuatuoGPT-Vision-Abla/sync_attn_params.py ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Sync the best attention-bias hyperparameters (layers + key/nonkey bias for
3
+ text and vis) across all run_eval_attnbias_sam_*.sh ablation scripts, so a
4
+ single grid-search result doesn't have to be hand-copied into 8 files.
5
+
6
+ Two scripts intentionally keep one side pinned at 0 as part of what they're
7
+ ablating, and must NOT be overwritten on that side:
8
+ - run_eval_attnbias_sam_both_amplify_only.sh : ATTN_NONKEY_BIAS_{TEXT,VIS} stay 0
9
+ - run_eval_attnbias_sam_both_suppress_only.sh: ATTN_KEY_BIAS_{TEXT,VIS} stay 0
10
+ run_eval_attnbias_sam_none.sh has no attention-bias variables and is skipped.
11
+
12
+ Usage:
13
+ python sync_attn_params.py --layers_text 17 --key_bias_text 4.0 --nonkey_bias_text -4.0 \\
14
+ --layers_vis 17 --key_bias_vis 1.0 --nonkey_bias_vis -1.0
15
+ python sync_attn_params.py --layers_text 17 --key_bias_text 4.0 --nonkey_bias_text -4.0 \\
16
+ --layers_vis 17 --key_bias_vis 1.0 --nonkey_bias_vis -1.0 --dry_run
17
+ """
18
+ import argparse
19
+ import glob
20
+ import os
21
+ import re
22
+
23
+ SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
24
+
25
+ # variable name -> argparse dest
26
+ VARS = {
27
+ "ATTN_LAYERS_TEXT": "layers_text",
28
+ "ATTN_KEY_BIAS_TEXT": "key_bias_text",
29
+ "ATTN_NONKEY_BIAS_TEXT": "nonkey_bias_text",
30
+ "ATTN_LAYERS_VIS": "layers_vis",
31
+ "ATTN_KEY_BIAS_VIS": "key_bias_vis",
32
+ "ATTN_NONKEY_BIAS_VIS": "nonkey_bias_vis",
33
+ }
34
+
35
+ # files where one side must stay pinned at 0 -- those variables are skipped
36
+ PINNED_ZERO = {
37
+ "run_eval_attnbias_sam_both_amplify_only.sh": {"ATTN_NONKEY_BIAS_TEXT", "ATTN_NONKEY_BIAS_VIS"},
38
+ "run_eval_attnbias_sam_both_suppress_only.sh": {"ATTN_KEY_BIAS_TEXT", "ATTN_KEY_BIAS_VIS"},
39
+ }
40
+
41
+ SKIP_FILES = {"run_eval_attnbias_sam_none.sh"}
42
+
43
+ # text-only / vis-only scripts don't set the other side's bias vars at all
44
+ # (they're forced to 0 inside eval_attnbias_sam.py regardless) -- only sync
45
+ # the side that's actually present in the file.
46
+ ONE_SIDED_FILES = {
47
+ "run_eval_attnbias_sam_text.sh": {"ATTN_LAYERS_VIS", "ATTN_KEY_BIAS_VIS", "ATTN_NONKEY_BIAS_VIS"},
48
+ "run_eval_attnbias_sam_vis.sh": {"ATTN_KEY_BIAS_TEXT", "ATTN_NONKEY_BIAS_TEXT"},
49
+ }
50
+
51
+
52
+ def sync_file(path, values, dry_run):
53
+ fname = os.path.basename(path)
54
+ if fname in SKIP_FILES:
55
+ return 0
56
+
57
+ with open(path, "r", encoding="utf-8") as f:
58
+ content = f.read()
59
+
60
+ skip_vars = PINNED_ZERO.get(fname, set()) | ONE_SIDED_FILES.get(fname, set())
61
+
62
+ n_changed = 0
63
+ for var, dest in VARS.items():
64
+ if var not in content or var in skip_vars or dest not in values:
65
+ continue
66
+ new_val = values[dest]
67
+ pattern = re.compile(rf'^({re.escape(var)}=)(.*)$', re.MULTILINE)
68
+
69
+ def _replace(m, new_val=new_val):
70
+ return f"{m.group(1)}{new_val}"
71
+
72
+ new_content, count = pattern.subn(_replace, content)
73
+ if count:
74
+ content = new_content
75
+ n_changed += count
76
+
77
+ if n_changed and not dry_run:
78
+ with open(path, "w", encoding="utf-8") as f:
79
+ f.write(content)
80
+ return n_changed
81
+
82
+
83
+ def main():
84
+ p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
85
+ p.add_argument("--layers_text", type=str, default=None)
86
+ p.add_argument("--key_bias_text", type=str, default=None)
87
+ p.add_argument("--nonkey_bias_text", type=str, default=None)
88
+ p.add_argument("--layers_vis", type=str, default=None)
89
+ p.add_argument("--key_bias_vis", type=str, default=None)
90
+ p.add_argument("--nonkey_bias_vis", type=str, default=None)
91
+ p.add_argument("--dry_run", action="store_true", default=False,
92
+ help="print what would change, without writing files")
93
+ args = p.parse_args()
94
+
95
+ values = {k: v for k, v in vars(args).items() if k != "dry_run" and v is not None}
96
+ if not values:
97
+ p.error("provide at least one of --layers_text/--key_bias_text/... to sync")
98
+
99
+ sh_files = sorted(glob.glob(os.path.join(SCRIPT_DIR, "run_eval_attnbias_sam_*.sh")))
100
+ total = 0
101
+ for path in sh_files:
102
+ fname = os.path.basename(path)
103
+ n = sync_file(path, values, args.dry_run)
104
+ total += n
105
+ if n:
106
+ tag = " (dry-run)" if args.dry_run else ""
107
+ print(f"[sync]{tag} {fname}: updated {n} variable(s)")
108
+ elif fname not in SKIP_FILES:
109
+ print(f"[sync] {fname}: no matching variables (skipped/pinned)")
110
+
111
+ print(f"[sync] done, {total} variable assignment(s) {'would be ' if args.dry_run else ''}updated "
112
+ f"across {len(sh_files)} file(s)")
113
+
114
+
115
+ if __name__ == "__main__":
116
+ main()