Add files using upload-large-folder tool
Browse files- 之前的代码版本/这一版注意力有问题/MedEvalKit/LLaVA-NeXT/llava/model/__init__.py +16 -0
- 之前的代码版本/这一版注意力有问题/MedEvalKit/LLaVA-NeXT/llava/model/consolidate.py +30 -0
- 之前的代码版本/这一版注意力有问题/MedEvalKit/LLaVA-NeXT/llava/model/llava_arch.py +597 -0
- 之前的代码版本/这一版注意力有问题/MedEvalKit/LLaVA-NeXT/llava/model/make_delta.py +52 -0
- 之前的代码版本/这一版注意力有问题/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/builder.py +41 -0
- 之前的代码版本/这一版注意力有问题/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/clip_encoder.py +173 -0
- 之前的代码版本/这一版注意力有问题/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/__init__.py +9 -0
- 之前的代码版本/这一版注意力有问题/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/hf_model.py +240 -0
- 之前的代码版本/这一版注意力有问题/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/loss.py +123 -0
- 之前的代码版本/这一版注意力有问题/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/modified_resnet.py +179 -0
- 之前的代码版本/这一版注意力有问题/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/openai.py +144 -0
- 之前的代码版本/这一版注意力有问题/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/pretrained.py +314 -0
- 之前的代码版本/这一版注意力有问题/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/timm_model.py +114 -0
- 之前的代码版本/这一版注意力有问题/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_vit.py +141 -0
- 之前的代码版本/这一版注意力有问题/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/hf_vision.py +111 -0
- 之前的代码版本/这一版注意力有问题/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/imagebind.py +73 -0
- 之前的代码版本/这一版注意力有问题/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/mlcd_encoder.py +179 -0
- 之前的代码版本/这一版注意力有问题/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/open_clip_encoder.py +163 -0
- 之前的代码版本/这一版注意力有问题/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/siglip_encoder.py +620 -0
- 之前的代码版本/这一版注意力有问题/MedEvalKit/LLaVA-NeXT/llava/model/utils.py +20 -0
之前的代码版本/这一版注意力有问题/MedEvalKit/LLaVA-NeXT/llava/model/__init__.py
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
|
| 3 |
+
AVAILABLE_MODELS = {
|
| 4 |
+
"llava_llama": "LlavaLlamaForCausalLM, LlavaConfig",
|
| 5 |
+
"llava_qwen": "LlavaQwenForCausalLM, LlavaQwenConfig",
|
| 6 |
+
"llava_mistral": "LlavaMistralForCausalLM, LlavaMistralConfig",
|
| 7 |
+
"llava_mixtral": "LlavaMixtralForCausalLM, LlavaMixtralConfig",
|
| 8 |
+
# "llava_qwen_moe": "LlavaQwenMoeForCausalLM, LlavaQwenMoeConfig",
|
| 9 |
+
# Add other models as needed
|
| 10 |
+
}
|
| 11 |
+
|
| 12 |
+
for model_name, model_classes in AVAILABLE_MODELS.items():
|
| 13 |
+
try:
|
| 14 |
+
exec(f"from .language_model.{model_name} import {model_classes}")
|
| 15 |
+
except Exception as e:
|
| 16 |
+
print(f"Failed to import {model_name} from llava.language_model.{model_name}. Error: {e}")
|
之前的代码版本/这一版注意力有问题/MedEvalKit/LLaVA-NeXT/llava/model/consolidate.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Usage:
|
| 3 |
+
python3 -m llava.model.consolidate --src ~/model_weights/llava-7b --dst ~/model_weights/llava-7b_consolidate
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import argparse
|
| 7 |
+
|
| 8 |
+
import torch
|
| 9 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM
|
| 10 |
+
from llava.model import *
|
| 11 |
+
from llava.model.utils import auto_upgrade
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def consolidate_ckpt(src_path, dst_path):
|
| 15 |
+
print("Loading model")
|
| 16 |
+
auto_upgrade(src_path)
|
| 17 |
+
src_model = AutoModelForCausalLM.from_pretrained(src_path, torch_dtype=torch.float16, low_cpu_mem_usage=True)
|
| 18 |
+
src_tokenizer = AutoTokenizer.from_pretrained(src_path, use_fast=False)
|
| 19 |
+
src_model.save_pretrained(dst_path)
|
| 20 |
+
src_tokenizer.save_pretrained(dst_path)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
if __name__ == "__main__":
|
| 24 |
+
parser = argparse.ArgumentParser()
|
| 25 |
+
parser.add_argument("--src", type=str, required=True)
|
| 26 |
+
parser.add_argument("--dst", type=str, required=True)
|
| 27 |
+
|
| 28 |
+
args = parser.parse_args()
|
| 29 |
+
|
| 30 |
+
consolidate_ckpt(args.src, args.dst)
|
之前的代码版本/这一版注意力有问题/MedEvalKit/LLaVA-NeXT/llava/model/llava_arch.py
ADDED
|
@@ -0,0 +1,597 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 math
|
| 19 |
+
import re
|
| 20 |
+
import time
|
| 21 |
+
import torch
|
| 22 |
+
import torch.nn as nn
|
| 23 |
+
from .multimodal_encoder.builder import build_vision_tower
|
| 24 |
+
from .multimodal_resampler.builder import build_vision_resampler
|
| 25 |
+
from .multimodal_projector.builder import build_vision_projector
|
| 26 |
+
|
| 27 |
+
from llava.constants import IGNORE_INDEX, IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_PATCH_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN
|
| 28 |
+
|
| 29 |
+
from llava.mm_utils import get_anyres_image_grid_shape
|
| 30 |
+
from llava.utils import rank0_print, rank_print
|
| 31 |
+
import random
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
class LlavaMetaModel:
|
| 35 |
+
|
| 36 |
+
def __init__(self, config):
|
| 37 |
+
super(LlavaMetaModel, self).__init__(config)
|
| 38 |
+
|
| 39 |
+
if hasattr(config, "mm_vision_tower"):
|
| 40 |
+
delay_load = getattr(config, "delay_load", False)
|
| 41 |
+
self.vision_tower = build_vision_tower(config, delay_load=delay_load)
|
| 42 |
+
self.vision_resampler = build_vision_resampler(config, vision_tower=self.vision_tower)
|
| 43 |
+
self.mm_projector = build_vision_projector(config, vision_cfg=self.vision_tower.config)
|
| 44 |
+
|
| 45 |
+
if "unpad" in getattr(config, "mm_patch_merge_type", ""):
|
| 46 |
+
self.image_newline = nn.Parameter(torch.empty(config.hidden_size, dtype=self.dtype))
|
| 47 |
+
|
| 48 |
+
def get_vision_tower(self):
|
| 49 |
+
vision_tower = getattr(self, "vision_tower", None)
|
| 50 |
+
if type(vision_tower) is list:
|
| 51 |
+
vision_tower = vision_tower[0]
|
| 52 |
+
return vision_tower
|
| 53 |
+
|
| 54 |
+
def initialize_vision_modules(self, model_args, fsdp=None):
|
| 55 |
+
vision_tower = model_args.vision_tower
|
| 56 |
+
mm_vision_select_layer = model_args.mm_vision_select_layer
|
| 57 |
+
mm_vision_select_feature = model_args.mm_vision_select_feature
|
| 58 |
+
pretrain_mm_mlp_adapter = model_args.pretrain_mm_mlp_adapter
|
| 59 |
+
mm_patch_merge_type = model_args.mm_patch_merge_type
|
| 60 |
+
|
| 61 |
+
self.config.mm_vision_tower = vision_tower
|
| 62 |
+
self.config.vision_tower_pretrained = getattr(model_args, "vision_tower_pretrained", "")
|
| 63 |
+
|
| 64 |
+
if self.get_vision_tower() is None:
|
| 65 |
+
vision_tower = build_vision_tower(model_args)
|
| 66 |
+
vision_resampler = build_vision_resampler(model_args, vision_tower=vision_tower)
|
| 67 |
+
for k, v in vision_resampler.config.items():
|
| 68 |
+
setattr(self.config, k, v)
|
| 69 |
+
|
| 70 |
+
if fsdp is not None and len(fsdp) > 0:
|
| 71 |
+
self.vision_tower = [vision_tower]
|
| 72 |
+
self.vision_resampler = [vision_resampler]
|
| 73 |
+
else:
|
| 74 |
+
self.vision_tower = vision_tower
|
| 75 |
+
self.vision_resampler = vision_resampler
|
| 76 |
+
else:
|
| 77 |
+
if fsdp is not None and len(fsdp) > 0:
|
| 78 |
+
vision_resampler = self.vision_resampler[0]
|
| 79 |
+
vision_tower = self.vision_tower[0]
|
| 80 |
+
else:
|
| 81 |
+
vision_resampler = self.vision_resampler
|
| 82 |
+
vision_tower = self.vision_tower
|
| 83 |
+
vision_tower.load_model()
|
| 84 |
+
|
| 85 |
+
# In case it is frozen by LoRA
|
| 86 |
+
for p in self.vision_resampler.parameters():
|
| 87 |
+
p.requires_grad = True
|
| 88 |
+
|
| 89 |
+
self.config.use_mm_proj = True
|
| 90 |
+
self.config.mm_projector_type = getattr(model_args, "mm_projector_type", "linear")
|
| 91 |
+
self.config.mm_hidden_size = getattr(vision_resampler, "hidden_size", vision_tower.hidden_size)
|
| 92 |
+
self.config.mm_vision_select_layer = mm_vision_select_layer
|
| 93 |
+
self.config.mm_vision_select_feature = mm_vision_select_feature
|
| 94 |
+
self.config.mm_patch_merge_type = mm_patch_merge_type
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
if not hasattr(self.config, 'add_faster_video'):
|
| 98 |
+
if model_args.add_faster_video:
|
| 99 |
+
embed_std = 1 / torch.sqrt(torch.tensor(self.config.hidden_size, dtype=self.dtype))
|
| 100 |
+
self.faster_token = nn.Parameter(
|
| 101 |
+
torch.randn(self.config.hidden_size, dtype=self.dtype) * embed_std
|
| 102 |
+
)
|
| 103 |
+
|
| 104 |
+
if getattr(self, "mm_projector", None) is None:
|
| 105 |
+
self.mm_projector = build_vision_projector(self.config, vision_cfg=vision_tower.config)
|
| 106 |
+
|
| 107 |
+
if "unpad" in mm_patch_merge_type:
|
| 108 |
+
embed_std = 1 / torch.sqrt(torch.tensor(self.config.hidden_size, dtype=self.dtype))
|
| 109 |
+
self.image_newline = nn.Parameter(torch.randn(self.config.hidden_size, dtype=self.dtype) * embed_std)
|
| 110 |
+
else:
|
| 111 |
+
# In case it is frozen by LoRA
|
| 112 |
+
for p in self.mm_projector.parameters():
|
| 113 |
+
p.requires_grad = True
|
| 114 |
+
|
| 115 |
+
if pretrain_mm_mlp_adapter is not None:
|
| 116 |
+
mm_projector_weights = torch.load(pretrain_mm_mlp_adapter, map_location="cpu")
|
| 117 |
+
|
| 118 |
+
def get_w(weights, keyword):
|
| 119 |
+
return {k.split(keyword + ".")[1]: v for k, v in weights.items() if keyword in k}
|
| 120 |
+
|
| 121 |
+
incompatible_keys = self.mm_projector.load_state_dict(get_w(mm_projector_weights, "mm_projector"))
|
| 122 |
+
rank0_print(f"Loaded mm projector weights from {pretrain_mm_mlp_adapter}. Incompatible keys: {incompatible_keys}")
|
| 123 |
+
incompatible_keys = self.vision_resampler.load_state_dict(get_w(mm_projector_weights, "vision_resampler"), strict=False)
|
| 124 |
+
rank0_print(f"Loaded vision resampler weights from {pretrain_mm_mlp_adapter}. Incompatible keys: {incompatible_keys}")
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def unpad_image(tensor, original_size):
|
| 128 |
+
"""
|
| 129 |
+
Unpads a PyTorch tensor of a padded and resized image.
|
| 130 |
+
|
| 131 |
+
Args:
|
| 132 |
+
tensor (torch.Tensor): The image tensor, assumed to be in CxHxW format.
|
| 133 |
+
original_size (tuple): The original size of the image (height, width).
|
| 134 |
+
|
| 135 |
+
Returns:
|
| 136 |
+
torch.Tensor: The unpadded image tensor.
|
| 137 |
+
"""
|
| 138 |
+
original_width, original_height = original_size
|
| 139 |
+
current_height, current_width = tensor.shape[1:]
|
| 140 |
+
|
| 141 |
+
# Compute aspect ratios
|
| 142 |
+
original_aspect_ratio = original_width / original_height
|
| 143 |
+
current_aspect_ratio = current_width / current_height
|
| 144 |
+
|
| 145 |
+
# Determine padding size and direction
|
| 146 |
+
if original_aspect_ratio > current_aspect_ratio:
|
| 147 |
+
# Padding was added to the height
|
| 148 |
+
scale_factor = current_width / original_width
|
| 149 |
+
new_height = int(original_height * scale_factor)
|
| 150 |
+
padding = (current_height - new_height) // 2
|
| 151 |
+
unpadded_tensor = tensor[:, padding : current_height - padding, :]
|
| 152 |
+
else:
|
| 153 |
+
# Padding was added to the width
|
| 154 |
+
scale_factor = current_height / original_height
|
| 155 |
+
new_width = int(original_width * scale_factor)
|
| 156 |
+
padding = (current_width - new_width) // 2
|
| 157 |
+
unpadded_tensor = tensor[:, :, padding : current_width - padding]
|
| 158 |
+
|
| 159 |
+
return unpadded_tensor
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
class LlavaMetaForCausalLM(ABC):
|
| 163 |
+
|
| 164 |
+
@abstractmethod
|
| 165 |
+
def get_model(self):
|
| 166 |
+
pass
|
| 167 |
+
|
| 168 |
+
def get_vision_tower(self):
|
| 169 |
+
return self.get_model().get_vision_tower()
|
| 170 |
+
|
| 171 |
+
def get_2dPool(self, image_feature, stride=2):
|
| 172 |
+
height = width = self.get_vision_tower().num_patches_per_side
|
| 173 |
+
num_frames, num_tokens, num_dim = image_feature.shape
|
| 174 |
+
image_feature = image_feature.view(num_frames, height, width, -1)
|
| 175 |
+
image_feature = image_feature.permute(0, 3, 1, 2).contiguous()
|
| 176 |
+
# image_feature = nn.functional.max_pool2d(image_feature, self.config.mm_spatial_pool_stride)
|
| 177 |
+
if self.config.mm_spatial_pool_mode == "average":
|
| 178 |
+
image_feature = nn.functional.avg_pool2d(image_feature, stride)
|
| 179 |
+
elif self.config.mm_spatial_pool_mode == "max":
|
| 180 |
+
image_feature = nn.functional.max_pool2d(image_feature, stride)
|
| 181 |
+
elif self.config.mm_spatial_pool_mode == "bilinear":
|
| 182 |
+
height, width = image_feature.shape[2:]
|
| 183 |
+
scaled_shape = [math.ceil(height / stride), math.ceil(width / stride)]
|
| 184 |
+
image_feature = nn.functional.interpolate(image_feature, size=scaled_shape, mode='bilinear')
|
| 185 |
+
|
| 186 |
+
else:
|
| 187 |
+
raise ValueError(f"Unexpected mm_spatial_pool_mode: {self.config.mm_spatial_pool_mode}")
|
| 188 |
+
image_feature = image_feature.permute(0, 2, 3, 1)
|
| 189 |
+
image_feature = image_feature.view(num_frames, -1, num_dim)
|
| 190 |
+
return image_feature
|
| 191 |
+
|
| 192 |
+
def encode_images(self, images):
|
| 193 |
+
image_features = self.get_model().get_vision_tower()(images)
|
| 194 |
+
# image_features = self.get_model().vision_resampler(image_features, images=images)
|
| 195 |
+
image_features = self.get_model().mm_projector(image_features)
|
| 196 |
+
return image_features
|
| 197 |
+
|
| 198 |
+
def encode_multimodals(self, videos_or_images, video_idx_in_batch, split_sizes=None):
|
| 199 |
+
videos_or_images_features = self.get_model().get_vision_tower()(videos_or_images)
|
| 200 |
+
per_videos_or_images_features = torch.split(videos_or_images_features, split_sizes, dim=0) # tuple, (dim_1, 576, 4096)
|
| 201 |
+
all_videos_or_images_features = []
|
| 202 |
+
all_faster_video_features = []
|
| 203 |
+
cur_mm_spatial_pool_stride = self.config.mm_spatial_pool_stride
|
| 204 |
+
|
| 205 |
+
for idx, feat in enumerate(per_videos_or_images_features):
|
| 206 |
+
|
| 207 |
+
feat = self.get_model().mm_projector(feat)
|
| 208 |
+
faster_video_feature = 0
|
| 209 |
+
slower_img_feat = 0
|
| 210 |
+
if idx in video_idx_in_batch and cur_mm_spatial_pool_stride > 1:
|
| 211 |
+
slower_img_feat = self.get_2dPool(feat,cur_mm_spatial_pool_stride)
|
| 212 |
+
if self.config.add_faster_video:
|
| 213 |
+
cur_mm_spatial_pool_stride = cur_mm_spatial_pool_stride * 2
|
| 214 |
+
faster_video_feature = self.get_2dPool(feat,cur_mm_spatial_pool_stride)
|
| 215 |
+
if slower_img_feat is not 0:
|
| 216 |
+
all_videos_or_images_features.append(slower_img_feat)
|
| 217 |
+
else:
|
| 218 |
+
all_videos_or_images_features.append(feat)
|
| 219 |
+
all_faster_video_features.append(faster_video_feature)
|
| 220 |
+
return all_videos_or_images_features,all_faster_video_features
|
| 221 |
+
|
| 222 |
+
def add_token_per_grid(self, image_feature):
|
| 223 |
+
resize_h = int(math.sqrt(image_feature.shape[1]))
|
| 224 |
+
num_frames = image_feature.shape[0]
|
| 225 |
+
feature_dim = image_feature.shape[-1]
|
| 226 |
+
|
| 227 |
+
image_feature = image_feature.view(num_frames, 1, resize_h, resize_h, -1)
|
| 228 |
+
image_feature = image_feature.permute(4, 0, 2, 1, 3).contiguous()
|
| 229 |
+
image_feature = image_feature.flatten(1, 2).flatten(2, 3)
|
| 230 |
+
image_feature = torch.cat((image_feature, self.model.image_newline[:, None, None].expand(*image_feature.shape[:-1], 1).to(image_feature.device)), dim=-1)
|
| 231 |
+
if getattr(self.config, "add_faster_video", False):
|
| 232 |
+
# import pdb; pdb.set_trace()
|
| 233 |
+
# (3584, 832, 14) -> (3584, 64, 13, 14)
|
| 234 |
+
image_feature = image_feature.view(feature_dim, num_frames,resize_h, -1)
|
| 235 |
+
# (3584, 64, 13, 14) -> (64, 13, 14, 3584)
|
| 236 |
+
image_feature = image_feature.permute(1, 2, 3, 0).contiguous()
|
| 237 |
+
# (64, 13, 14, 3584) -> (64, 13*14, 3584)
|
| 238 |
+
image_feature = image_feature.flatten(1, 2)
|
| 239 |
+
# import pdb; pdb.set_trace()
|
| 240 |
+
return image_feature
|
| 241 |
+
# import pdb; pdb.set_trace()
|
| 242 |
+
image_feature = image_feature.flatten(1, 2).transpose(0, 1)
|
| 243 |
+
return image_feature
|
| 244 |
+
|
| 245 |
+
def add_token_per_frame(self, image_feature):
|
| 246 |
+
image_feature = image_feature.permute(2, 0, 1).contiguous()
|
| 247 |
+
image_feature = torch.cat((image_feature, self.model.image_newline[:, None, None].expand(*image_feature.shape[:-1], 1).to(image_feature.device)), dim=-1)
|
| 248 |
+
image_feature = image_feature.permute(1, 2, 0).contiguous()
|
| 249 |
+
return image_feature
|
| 250 |
+
|
| 251 |
+
def prepare_inputs_labels_for_multimodal(self, input_ids, position_ids, attention_mask, past_key_values, labels, images, modalities=["image"], image_sizes=None):
|
| 252 |
+
vision_tower = self.get_vision_tower()
|
| 253 |
+
# rank_print(modalities)
|
| 254 |
+
if vision_tower is None or images is None or input_ids.shape[1] == 1:
|
| 255 |
+
return input_ids, position_ids, attention_mask, past_key_values, None, labels
|
| 256 |
+
|
| 257 |
+
if isinstance(modalities, str):
|
| 258 |
+
modalities = [modalities]
|
| 259 |
+
|
| 260 |
+
# import pdb; pdb.set_trace()
|
| 261 |
+
if type(images) is list or images.ndim == 5:
|
| 262 |
+
if type(images) is list:
|
| 263 |
+
images = [x.unsqueeze(0) if x.ndim == 3 else x for x in images]
|
| 264 |
+
|
| 265 |
+
video_idx_in_batch = []
|
| 266 |
+
for _ in range(len(modalities)):
|
| 267 |
+
if modalities[_] == "video":
|
| 268 |
+
video_idx_in_batch.append(_)
|
| 269 |
+
|
| 270 |
+
images_list = []
|
| 271 |
+
for image in images:
|
| 272 |
+
if image.ndim == 4:
|
| 273 |
+
images_list.append(image)
|
| 274 |
+
else:
|
| 275 |
+
images_list.append(image.unsqueeze(0))
|
| 276 |
+
|
| 277 |
+
concat_images = torch.cat([image for image in images_list], dim=0)
|
| 278 |
+
split_sizes = [image.shape[0] for image in images_list]
|
| 279 |
+
encoded_image_features = self.encode_images(concat_images)
|
| 280 |
+
# image_features,all_faster_video_features = self.encode_multimodals(concat_images, video_idx_in_batch, split_sizes)
|
| 281 |
+
|
| 282 |
+
# This is a list, each element is [num_images, patch * patch, dim]
|
| 283 |
+
# rank_print(f"Concat images : {concat_images.shape}")
|
| 284 |
+
encoded_image_features = torch.split(encoded_image_features, split_sizes)
|
| 285 |
+
image_features = []
|
| 286 |
+
for idx, image_feat in enumerate(encoded_image_features):
|
| 287 |
+
if idx in video_idx_in_batch:
|
| 288 |
+
image_features.append(self.get_2dPool(image_feat))
|
| 289 |
+
else:
|
| 290 |
+
image_features.append(image_feat)
|
| 291 |
+
# image_features = self.encode_multimodals(concat_images, video_idx_in_batch, split_sizes)
|
| 292 |
+
# rank_print(f"Encoded image feats : {[x.shape for x in image_features]}")
|
| 293 |
+
# image_features = torch.split(image_features, split_sizes, dim=0)
|
| 294 |
+
mm_patch_merge_type = getattr(self.config, "mm_patch_merge_type", "flat")
|
| 295 |
+
image_aspect_ratio = getattr(self.config, "image_aspect_ratio", "square")
|
| 296 |
+
mm_newline_position = getattr(self.config, "mm_newline_position", "one_token")
|
| 297 |
+
|
| 298 |
+
if mm_patch_merge_type == "flat":
|
| 299 |
+
image_features = [x.flatten(0, 1) for x in image_features]
|
| 300 |
+
|
| 301 |
+
elif mm_patch_merge_type.startswith("spatial"):
|
| 302 |
+
new_image_features = []
|
| 303 |
+
for image_idx, image_feature in enumerate(image_features):
|
| 304 |
+
# FIXME: now assume the image is square, and split to 2x2 patches
|
| 305 |
+
# num_patches = h * w, where h = w = sqrt(num_patches)
|
| 306 |
+
# currently image_feature is a tensor of shape (4, num_patches, hidden_size)
|
| 307 |
+
# we want to first unflatten it to (2, 2, h, w, hidden_size)
|
| 308 |
+
# rank0_print("At least we are reaching here")
|
| 309 |
+
# import pdb; pdb.set_trace()
|
| 310 |
+
if image_idx in video_idx_in_batch: # video operations
|
| 311 |
+
# rank0_print("Video")
|
| 312 |
+
if mm_newline_position == "grid":
|
| 313 |
+
# Grid-wise
|
| 314 |
+
image_feature = self.add_token_per_grid(image_feature)
|
| 315 |
+
if getattr(self.config, "add_faster_video", False):
|
| 316 |
+
faster_video_feature = self.add_token_per_grid(all_faster_video_features[image_idx])
|
| 317 |
+
# Add a token for each frame
|
| 318 |
+
concat_slow_fater_token = []
|
| 319 |
+
# import pdb; pdb.set_trace()
|
| 320 |
+
for _ in range(image_feature.shape[0]):
|
| 321 |
+
if _ % self.config.faster_token_stride == 0:
|
| 322 |
+
concat_slow_fater_token.append(torch.cat((image_feature[_], self.model.faster_token[None].to(image_feature.device)), dim=0))
|
| 323 |
+
else:
|
| 324 |
+
concat_slow_fater_token.append(torch.cat((faster_video_feature[_], self.model.faster_token[None].to(image_feature.device)), dim=0))
|
| 325 |
+
# import pdb; pdb.set_trace()
|
| 326 |
+
image_feature = torch.cat(concat_slow_fater_token)
|
| 327 |
+
|
| 328 |
+
# print("!!!!!!!!!!!!")
|
| 329 |
+
|
| 330 |
+
new_image_features.append(image_feature)
|
| 331 |
+
elif mm_newline_position == "frame":
|
| 332 |
+
# Frame-wise
|
| 333 |
+
image_feature = self.add_token_per_frame(image_feature)
|
| 334 |
+
|
| 335 |
+
new_image_features.append(image_feature.flatten(0, 1))
|
| 336 |
+
|
| 337 |
+
elif mm_newline_position == "one_token":
|
| 338 |
+
# one-token
|
| 339 |
+
image_feature = image_feature.flatten(0, 1)
|
| 340 |
+
if 'unpad' in mm_patch_merge_type:
|
| 341 |
+
image_feature = torch.cat((
|
| 342 |
+
image_feature,
|
| 343 |
+
self.model.image_newline[None].to(image_feature.device)
|
| 344 |
+
), dim=0)
|
| 345 |
+
new_image_features.append(image_feature)
|
| 346 |
+
elif mm_newline_position == "no_token":
|
| 347 |
+
new_image_features.append(image_feature.flatten(0, 1))
|
| 348 |
+
else:
|
| 349 |
+
raise ValueError(f"Unexpected mm_newline_position: {mm_newline_position}")
|
| 350 |
+
elif image_feature.shape[0] > 1: # multi patches and multi images operations
|
| 351 |
+
# rank0_print("Single-images")
|
| 352 |
+
base_image_feature = image_feature[0]
|
| 353 |
+
image_feature = image_feature[1:]
|
| 354 |
+
height = width = self.get_vision_tower().num_patches_per_side
|
| 355 |
+
assert height * width == base_image_feature.shape[0]
|
| 356 |
+
|
| 357 |
+
if "anyres_max" in image_aspect_ratio:
|
| 358 |
+
matched_anyres_max_num_patches = re.match(r"anyres_max_(\d+)", image_aspect_ratio)
|
| 359 |
+
if matched_anyres_max_num_patches:
|
| 360 |
+
max_num_patches = int(matched_anyres_max_num_patches.group(1))
|
| 361 |
+
|
| 362 |
+
if image_aspect_ratio == "anyres" or "anyres_max" in image_aspect_ratio:
|
| 363 |
+
if hasattr(self.get_vision_tower(), "image_size"):
|
| 364 |
+
vision_tower_image_size = self.get_vision_tower().image_size
|
| 365 |
+
else:
|
| 366 |
+
raise ValueError("vision_tower_image_size is not found in the vision tower.")
|
| 367 |
+
try:
|
| 368 |
+
num_patch_width, num_patch_height = get_anyres_image_grid_shape(image_sizes[image_idx], self.config.image_grid_pinpoints, vision_tower_image_size)
|
| 369 |
+
except Exception as e:
|
| 370 |
+
rank0_print(f"Error: {e}")
|
| 371 |
+
num_patch_width, num_patch_height = 2, 2
|
| 372 |
+
image_feature = image_feature.view(num_patch_height, num_patch_width, height, width, -1)
|
| 373 |
+
else:
|
| 374 |
+
image_feature = image_feature.view(2, 2, height, width, -1)
|
| 375 |
+
|
| 376 |
+
if "maxpool2x2" in mm_patch_merge_type:
|
| 377 |
+
image_feature = image_feature.permute(4, 0, 2, 1, 3).contiguous()
|
| 378 |
+
image_feature = image_feature.flatten(1, 2).flatten(2, 3)
|
| 379 |
+
image_feature = nn.functional.max_pool2d(image_feature, 2)
|
| 380 |
+
image_feature = image_feature.flatten(1, 2).transpose(0, 1)
|
| 381 |
+
elif "unpad" in mm_patch_merge_type and "anyres_max" in image_aspect_ratio and matched_anyres_max_num_patches:
|
| 382 |
+
unit = image_feature.shape[2]
|
| 383 |
+
image_feature = image_feature.permute(4, 0, 2, 1, 3).contiguous()
|
| 384 |
+
image_feature = image_feature.flatten(1, 2).flatten(2, 3)
|
| 385 |
+
image_feature = unpad_image(image_feature, image_sizes[image_idx])
|
| 386 |
+
c, h, w = image_feature.shape
|
| 387 |
+
times = math.sqrt(h * w / (max_num_patches * unit**2))
|
| 388 |
+
if times > 1.1:
|
| 389 |
+
image_feature = image_feature[None]
|
| 390 |
+
image_feature = nn.functional.interpolate(image_feature, [int(h // times), int(w // times)], mode="bilinear")[0]
|
| 391 |
+
image_feature = torch.cat((image_feature, self.model.image_newline[:, None, None].expand(*image_feature.shape[:-1], 1).to(image_feature.device)), dim=-1)
|
| 392 |
+
image_feature = image_feature.flatten(1, 2).transpose(0, 1)
|
| 393 |
+
elif "unpad" in mm_patch_merge_type:
|
| 394 |
+
image_feature = image_feature.permute(4, 0, 2, 1, 3).contiguous()
|
| 395 |
+
image_feature = image_feature.flatten(1, 2).flatten(2, 3)
|
| 396 |
+
image_feature = unpad_image(image_feature, image_sizes[image_idx])
|
| 397 |
+
image_feature = torch.cat((image_feature, self.model.image_newline[:, None, None].expand(*image_feature.shape[:-1], 1).to(image_feature.device)), dim=-1)
|
| 398 |
+
image_feature = image_feature.flatten(1, 2).transpose(0, 1)
|
| 399 |
+
else:
|
| 400 |
+
image_feature = image_feature.permute(0, 2, 1, 3, 4).contiguous()
|
| 401 |
+
image_feature = image_feature.flatten(0, 3)
|
| 402 |
+
if "nobase" in mm_patch_merge_type:
|
| 403 |
+
pass
|
| 404 |
+
else:
|
| 405 |
+
image_feature = torch.cat((base_image_feature, image_feature), dim=0)
|
| 406 |
+
new_image_features.append(image_feature)
|
| 407 |
+
else: # single image operations
|
| 408 |
+
image_feature = image_feature[0]
|
| 409 |
+
if "unpad" in mm_patch_merge_type:
|
| 410 |
+
image_feature = torch.cat((image_feature, self.model.image_newline[None]), dim=0)
|
| 411 |
+
|
| 412 |
+
new_image_features.append(image_feature)
|
| 413 |
+
image_features = new_image_features
|
| 414 |
+
else:
|
| 415 |
+
raise ValueError(f"Unexpected mm_patch_merge_type: {self.config.mm_patch_merge_type}")
|
| 416 |
+
else:
|
| 417 |
+
image_features = self.encode_images(images)
|
| 418 |
+
|
| 419 |
+
# TODO: image start / end is not implemented here to support pretraining.
|
| 420 |
+
if getattr(self.config, "tune_mm_mlp_adapter", False) and getattr(self.config, "mm_use_im_start_end", False):
|
| 421 |
+
raise NotImplementedError
|
| 422 |
+
# rank_print(f"Total images : {len(image_features)}")
|
| 423 |
+
|
| 424 |
+
# Let's just add dummy tensors if they do not exist,
|
| 425 |
+
# it is a headache to deal with None all the time.
|
| 426 |
+
# But it is not ideal, and if you have a better idea,
|
| 427 |
+
# please open an issue / submit a PR, thanks.
|
| 428 |
+
_labels = labels
|
| 429 |
+
_position_ids = position_ids
|
| 430 |
+
_attention_mask = attention_mask
|
| 431 |
+
if attention_mask is None:
|
| 432 |
+
attention_mask = torch.ones_like(input_ids, dtype=torch.bool)
|
| 433 |
+
else:
|
| 434 |
+
attention_mask = attention_mask.bool()
|
| 435 |
+
if position_ids is None:
|
| 436 |
+
position_ids = torch.arange(0, input_ids.shape[1], dtype=torch.long, device=input_ids.device)
|
| 437 |
+
if labels is None:
|
| 438 |
+
labels = torch.full_like(input_ids, IGNORE_INDEX)
|
| 439 |
+
|
| 440 |
+
# remove the padding using attention_mask -- FIXME
|
| 441 |
+
_input_ids = input_ids
|
| 442 |
+
input_ids = [cur_input_ids[cur_attention_mask] for cur_input_ids, cur_attention_mask in zip(input_ids, attention_mask)]
|
| 443 |
+
labels = [cur_labels[cur_attention_mask] for cur_labels, cur_attention_mask in zip(labels, attention_mask)]
|
| 444 |
+
|
| 445 |
+
new_input_embeds = []
|
| 446 |
+
new_labels = []
|
| 447 |
+
cur_image_idx = 0
|
| 448 |
+
# rank_print("Inserting Images embedding")
|
| 449 |
+
for batch_idx, cur_input_ids in enumerate(input_ids):
|
| 450 |
+
num_images = (cur_input_ids == IMAGE_TOKEN_INDEX).sum()
|
| 451 |
+
# rank0_print(num_images)
|
| 452 |
+
if num_images == 0:
|
| 453 |
+
cur_image_features = image_features[cur_image_idx]
|
| 454 |
+
cur_input_embeds_1 = self.get_model().embed_tokens(cur_input_ids)
|
| 455 |
+
cur_input_embeds = torch.cat([cur_input_embeds_1, cur_image_features[0:0]], dim=0)
|
| 456 |
+
new_input_embeds.append(cur_input_embeds)
|
| 457 |
+
new_labels.append(labels[batch_idx])
|
| 458 |
+
cur_image_idx += 1
|
| 459 |
+
continue
|
| 460 |
+
|
| 461 |
+
image_token_indices = [-1] + torch.where(cur_input_ids == IMAGE_TOKEN_INDEX)[0].tolist() + [cur_input_ids.shape[0]]
|
| 462 |
+
cur_input_ids_noim = []
|
| 463 |
+
cur_labels = labels[batch_idx]
|
| 464 |
+
cur_labels_noim = []
|
| 465 |
+
for i in range(len(image_token_indices) - 1):
|
| 466 |
+
cur_input_ids_noim.append(cur_input_ids[image_token_indices[i] + 1 : image_token_indices[i + 1]])
|
| 467 |
+
cur_labels_noim.append(cur_labels[image_token_indices[i] + 1 : image_token_indices[i + 1]])
|
| 468 |
+
split_sizes = [x.shape[0] for x in cur_labels_noim]
|
| 469 |
+
cur_input_embeds = self.get_model().embed_tokens(torch.cat(cur_input_ids_noim))
|
| 470 |
+
cur_input_embeds_no_im = torch.split(cur_input_embeds, split_sizes, dim=0)
|
| 471 |
+
cur_new_input_embeds = []
|
| 472 |
+
cur_new_labels = []
|
| 473 |
+
|
| 474 |
+
for i in range(num_images + 1):
|
| 475 |
+
cur_new_input_embeds.append(cur_input_embeds_no_im[i])
|
| 476 |
+
cur_new_labels.append(cur_labels_noim[i])
|
| 477 |
+
if i < num_images:
|
| 478 |
+
try:
|
| 479 |
+
cur_image_features = image_features[cur_image_idx]
|
| 480 |
+
except IndexError:
|
| 481 |
+
cur_image_features = image_features[cur_image_idx - 1]
|
| 482 |
+
cur_image_idx += 1
|
| 483 |
+
cur_new_input_embeds.append(cur_image_features)
|
| 484 |
+
cur_new_labels.append(torch.full((cur_image_features.shape[0],), IGNORE_INDEX, device=cur_labels.device, dtype=cur_labels.dtype))
|
| 485 |
+
|
| 486 |
+
cur_new_input_embeds = [x.to(self.device) for x in cur_new_input_embeds]
|
| 487 |
+
|
| 488 |
+
# import pdb; pdb.set_trace()
|
| 489 |
+
cur_new_input_embeds = torch.cat(cur_new_input_embeds)
|
| 490 |
+
cur_new_labels = torch.cat(cur_new_labels)
|
| 491 |
+
|
| 492 |
+
new_input_embeds.append(cur_new_input_embeds)
|
| 493 |
+
new_labels.append(cur_new_labels)
|
| 494 |
+
|
| 495 |
+
# Truncate sequences to max length as image embeddings can make the sequence longer
|
| 496 |
+
tokenizer_model_max_length = getattr(self.config, "tokenizer_model_max_length", None)
|
| 497 |
+
# rank_print("Finishing Inserting")
|
| 498 |
+
|
| 499 |
+
new_input_embeds = [x[:tokenizer_model_max_length] for x, modality in zip(new_input_embeds, modalities)]
|
| 500 |
+
new_labels = [x[:tokenizer_model_max_length] for x, modality in zip(new_labels, modalities)]
|
| 501 |
+
# TODO: Hard code for control loss spike
|
| 502 |
+
# if tokenizer_model_max_length is not None:
|
| 503 |
+
# new_input_embeds = [x[:4096] if modality != "video" else x[:tokenizer_model_max_length] for x, modality in zip(new_input_embeds, modalities)]
|
| 504 |
+
# new_labels = [x[:4096] if modality != "video" else x[:tokenizer_model_max_length] for x, modality in zip(new_labels, modalities)]
|
| 505 |
+
|
| 506 |
+
# Combine them
|
| 507 |
+
max_len = max(x.shape[0] for x in new_input_embeds)
|
| 508 |
+
batch_size = len(new_input_embeds)
|
| 509 |
+
|
| 510 |
+
new_input_embeds_padded = []
|
| 511 |
+
new_labels_padded = torch.full((batch_size, max_len), IGNORE_INDEX, dtype=new_labels[0].dtype, device=new_labels[0].device)
|
| 512 |
+
attention_mask = torch.zeros((batch_size, max_len), dtype=attention_mask.dtype, device=attention_mask.device)
|
| 513 |
+
position_ids = torch.zeros((batch_size, max_len), dtype=position_ids.dtype, device=position_ids.device)
|
| 514 |
+
# rank0_print("Prepare pos id")
|
| 515 |
+
|
| 516 |
+
for i, (cur_new_embed, cur_new_labels) in enumerate(zip(new_input_embeds, new_labels)):
|
| 517 |
+
cur_len = cur_new_embed.shape[0]
|
| 518 |
+
if getattr(self.config, "tokenizer_padding_side", "right") == "left":
|
| 519 |
+
new_input_embeds_padded.append(torch.cat((torch.zeros((max_len - cur_len, cur_new_embed.shape[1]), dtype=cur_new_embed.dtype, device=cur_new_embed.device), cur_new_embed), dim=0))
|
| 520 |
+
if cur_len > 0:
|
| 521 |
+
new_labels_padded[i, -cur_len:] = cur_new_labels
|
| 522 |
+
attention_mask[i, -cur_len:] = True
|
| 523 |
+
position_ids[i, -cur_len:] = torch.arange(0, cur_len, dtype=position_ids.dtype, device=position_ids.device)
|
| 524 |
+
else:
|
| 525 |
+
new_input_embeds_padded.append(torch.cat((cur_new_embed, torch.zeros((max_len - cur_len, cur_new_embed.shape[1]), dtype=cur_new_embed.dtype, device=cur_new_embed.device)), dim=0))
|
| 526 |
+
if cur_len > 0:
|
| 527 |
+
new_labels_padded[i, :cur_len] = cur_new_labels
|
| 528 |
+
attention_mask[i, :cur_len] = True
|
| 529 |
+
position_ids[i, :cur_len] = torch.arange(0, cur_len, dtype=position_ids.dtype, device=position_ids.device)
|
| 530 |
+
|
| 531 |
+
new_input_embeds = torch.stack(new_input_embeds_padded, dim=0)
|
| 532 |
+
# rank0_print("tokenizer padding")
|
| 533 |
+
|
| 534 |
+
if _labels is None:
|
| 535 |
+
new_labels = None
|
| 536 |
+
else:
|
| 537 |
+
new_labels = new_labels_padded
|
| 538 |
+
|
| 539 |
+
if _attention_mask is None:
|
| 540 |
+
attention_mask = None
|
| 541 |
+
else:
|
| 542 |
+
attention_mask = attention_mask.to(dtype=_attention_mask.dtype)
|
| 543 |
+
|
| 544 |
+
if _position_ids is None:
|
| 545 |
+
position_ids = None
|
| 546 |
+
if getattr(self.config, "use_pos_skipping", False) and self.training:
|
| 547 |
+
position_ids = torch.arange(new_input_embeds.size(1), device=new_input_embeds.device).unsqueeze(0).to(new_input_embeds.device)
|
| 548 |
+
split_position = random.randint(0, new_input_embeds.size(1))
|
| 549 |
+
left_add = random.randint(0, self.config.pos_skipping_range)
|
| 550 |
+
right_add = random.randint(left_add, self.config.pos_skipping_range)
|
| 551 |
+
position_ids[:, :split_position] += left_add
|
| 552 |
+
position_ids[:, split_position:] += right_add
|
| 553 |
+
# import pdb; pdb.set_trace()
|
| 554 |
+
# rank0_print("Finish preparing")
|
| 555 |
+
return None, position_ids, attention_mask, past_key_values, new_input_embeds, new_labels
|
| 556 |
+
|
| 557 |
+
def initialize_vision_tokenizer(self, model_args, tokenizer):
|
| 558 |
+
if model_args.mm_use_im_patch_token:
|
| 559 |
+
tokenizer.add_tokens([DEFAULT_IMAGE_PATCH_TOKEN], special_tokens=True)
|
| 560 |
+
self.resize_token_embeddings(len(tokenizer))
|
| 561 |
+
|
| 562 |
+
if model_args.mm_use_im_start_end:
|
| 563 |
+
num_new_tokens = tokenizer.add_tokens([DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN], special_tokens=True)
|
| 564 |
+
self.resize_token_embeddings(len(tokenizer))
|
| 565 |
+
|
| 566 |
+
if num_new_tokens > 0:
|
| 567 |
+
input_embeddings = self.get_input_embeddings().weight.data
|
| 568 |
+
output_embeddings = self.get_output_embeddings().weight.data
|
| 569 |
+
|
| 570 |
+
input_embeddings_avg = input_embeddings[:-num_new_tokens].mean(dim=0, keepdim=True)
|
| 571 |
+
output_embeddings_avg = output_embeddings[:-num_new_tokens].mean(dim=0, keepdim=True)
|
| 572 |
+
|
| 573 |
+
input_embeddings[-num_new_tokens:] = input_embeddings_avg
|
| 574 |
+
output_embeddings[-num_new_tokens:] = output_embeddings_avg
|
| 575 |
+
|
| 576 |
+
if model_args.tune_mm_mlp_adapter:
|
| 577 |
+
for p in self.get_input_embeddings().parameters():
|
| 578 |
+
p.requires_grad = True
|
| 579 |
+
for p in self.get_output_embeddings().parameters():
|
| 580 |
+
p.requires_grad = False
|
| 581 |
+
|
| 582 |
+
if model_args.pretrain_mm_mlp_adapter:
|
| 583 |
+
mm_projector_weights = torch.load(model_args.pretrain_mm_mlp_adapter, map_location="cpu")
|
| 584 |
+
embed_tokens_weight = mm_projector_weights["model.embed_tokens.weight"]
|
| 585 |
+
assert num_new_tokens == 2
|
| 586 |
+
if input_embeddings.shape == embed_tokens_weight.shape:
|
| 587 |
+
input_embeddings[-num_new_tokens:] = embed_tokens_weight[-num_new_tokens:]
|
| 588 |
+
elif embed_tokens_weight.shape[0] == num_new_tokens:
|
| 589 |
+
input_embeddings[-num_new_tokens:] = embed_tokens_weight
|
| 590 |
+
else:
|
| 591 |
+
raise ValueError(f"Unexpected embed_tokens_weight shape. Pretrained: {embed_tokens_weight.shape}. Current: {input_embeddings.shape}. Numer of new tokens: {num_new_tokens}.")
|
| 592 |
+
elif model_args.mm_use_im_patch_token:
|
| 593 |
+
if model_args.tune_mm_mlp_adapter:
|
| 594 |
+
for p in self.get_input_embeddings().parameters():
|
| 595 |
+
p.requires_grad = False
|
| 596 |
+
for p in self.get_output_embeddings().parameters():
|
| 597 |
+
p.requires_grad = False
|
之前的代码版本/这一版注意力有问题/MedEvalKit/LLaVA-NeXT/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 |
+
|
| 6 |
+
import argparse
|
| 7 |
+
|
| 8 |
+
import torch
|
| 9 |
+
from tqdm import tqdm
|
| 10 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM
|
| 11 |
+
from llava.model.utils import auto_upgrade
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def make_delta(base_model_path, target_model_path, delta_path, hub_repo_id):
|
| 15 |
+
print("Loading base model")
|
| 16 |
+
base = AutoModelForCausalLM.from_pretrained(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)
|
之前的代码版本/这一版注意力有问题/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/builder.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from .clip_encoder import CLIPVisionTower
|
| 3 |
+
from .imagebind import ImageBindWrapper
|
| 4 |
+
from .open_clip_encoder import OpenCLIPVisionTower
|
| 5 |
+
from .hf_vision import HFVisionTower
|
| 6 |
+
from .siglip_encoder import SigLipVisionTower
|
| 7 |
+
from .clip_encoder import CLIPVisionTower, CLIPVisionTowerS2
|
| 8 |
+
from .mlcd_encoder import MLCDVisionTower, MLCDVisionTowerS2
|
| 9 |
+
# from .eva_clip.eva_clip_encoder import EvaClipVisionTower
|
| 10 |
+
# from .dev_eva_clip.eva_vit import EvaViTWrapper
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def build_vision_tower(vision_tower_cfg, **kwargs):
|
| 14 |
+
vision_tower = getattr(vision_tower_cfg, "mm_vision_tower", getattr(vision_tower_cfg, "vision_tower", None))
|
| 15 |
+
is_absolute_path_exists = os.path.exists(vision_tower)
|
| 16 |
+
use_s2 = getattr(vision_tower_cfg, "s2", False)
|
| 17 |
+
if is_absolute_path_exists or vision_tower.startswith("openai") or vision_tower.startswith("laion") or "ShareGPT4V" in vision_tower:
|
| 18 |
+
if use_s2:
|
| 19 |
+
return CLIPVisionTowerS2(vision_tower, args=vision_tower_cfg, **kwargs)
|
| 20 |
+
else:
|
| 21 |
+
return CLIPVisionTower(vision_tower, args=vision_tower_cfg, **kwargs)
|
| 22 |
+
elif "siglip" in vision_tower:
|
| 23 |
+
return SigLipVisionTower(vision_tower, vision_tower_cfg=vision_tower_cfg, **kwargs)
|
| 24 |
+
elif vision_tower.startswith("hf:"):
|
| 25 |
+
return HFVisionTower(vision_tower, args=vision_tower_cfg, **kwargs)
|
| 26 |
+
elif vision_tower in ["imagebind_huge"]:
|
| 27 |
+
return ImageBindWrapper(vision_tower, args=vision_tower_cfg, **kwargs)
|
| 28 |
+
elif vision_tower.startswith("open_clip_hub"):
|
| 29 |
+
return OpenCLIPVisionTower(vision_tower, args=vision_tower_cfg, **kwargs)
|
| 30 |
+
elif "mlcd-vit-bigG-patch14" in vision_tower:
|
| 31 |
+
if use_s2:
|
| 32 |
+
return MLCDVisionTowerS2(vision_tower, args=vision_tower_cfg, **kwargs)
|
| 33 |
+
else:
|
| 34 |
+
return MLCDVisionTower(vision_tower, args=vision_tower_cfg, **kwargs)
|
| 35 |
+
|
| 36 |
+
# elif "internal-eva" in vision_tower.lower() or "eva02" in vision_tower.lower():
|
| 37 |
+
# return EvaClipVisionTower(vision_tower, args=vision_tower_cfg, **kwargs)
|
| 38 |
+
# elif vision_tower in ["EVA-CLIP-8B", "EVA-CLIP-8B-plus"]:
|
| 39 |
+
# return EvaViTWrapper(vision_tower, args=vision_tower_cfg, **kwargs)
|
| 40 |
+
|
| 41 |
+
raise ValueError(f"Unknown vision tower: {vision_tower}")
|
之前的代码版本/这一版注意力有问题/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/clip_encoder.py
ADDED
|
@@ -0,0 +1,173 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
from llava.utils import rank0_print
|
| 4 |
+
from transformers import CLIPVisionModel, CLIPImageProcessor, CLIPVisionConfig
|
| 5 |
+
|
| 6 |
+
try:
|
| 7 |
+
from s2wrapper import forward as multiscale_forward
|
| 8 |
+
except:
|
| 9 |
+
pass
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class CLIPVisionTower(nn.Module):
|
| 13 |
+
def __init__(self, vision_tower, args, delay_load=False):
|
| 14 |
+
super().__init__()
|
| 15 |
+
|
| 16 |
+
self.is_loaded = False
|
| 17 |
+
|
| 18 |
+
self.vision_tower_name = vision_tower
|
| 19 |
+
self.select_layer = args.mm_vision_select_layer
|
| 20 |
+
self.select_feature = getattr(args, "mm_vision_select_feature", "patch")
|
| 21 |
+
|
| 22 |
+
if not delay_load:
|
| 23 |
+
rank0_print(f"Loading vision tower: {vision_tower}")
|
| 24 |
+
self.load_model()
|
| 25 |
+
elif getattr(args, "unfreeze_mm_vision_tower", False):
|
| 26 |
+
# TODO: better detector is needed.
|
| 27 |
+
rank0_print(f"The checkpoint seems to contain `vision_tower` weights: `unfreeze_mm_vision_tower`: True.")
|
| 28 |
+
self.load_model()
|
| 29 |
+
elif hasattr(args, "mm_tunable_parts") and "mm_vision_tower" in args.mm_tunable_parts:
|
| 30 |
+
rank0_print(f"The checkpoint seems to contain `vision_tower` weights: `mm_tunable_parts` contains `mm_vision_tower`.")
|
| 31 |
+
self.load_model()
|
| 32 |
+
else:
|
| 33 |
+
self.cfg_only = CLIPVisionConfig.from_pretrained(self.vision_tower_name)
|
| 34 |
+
|
| 35 |
+
def load_model(self, device_map=None):
|
| 36 |
+
if self.is_loaded:
|
| 37 |
+
rank0_print("{} is already loaded, `load_model` called again, skipping.".format(self.vision_tower_name))
|
| 38 |
+
return
|
| 39 |
+
|
| 40 |
+
self.image_processor = CLIPImageProcessor.from_pretrained(self.vision_tower_name)
|
| 41 |
+
self.vision_tower = CLIPVisionModel.from_pretrained(self.vision_tower_name, device_map=device_map)
|
| 42 |
+
self.vision_tower.requires_grad_(False)
|
| 43 |
+
|
| 44 |
+
self.is_loaded = True
|
| 45 |
+
|
| 46 |
+
def feature_select(self, image_forward_outs):
|
| 47 |
+
select_feature_type = self.select_feature
|
| 48 |
+
|
| 49 |
+
if self.select_feature in ["slicefour_patch", "slicefour_cls_patch"]:
|
| 50 |
+
select_every_k_layer = len(image_forward_outs.hidden_states) // 4
|
| 51 |
+
image_features = torch.cat([image_forward_outs.hidden_states[i] for i in range(select_every_k_layer + self.select_layer, len(image_forward_outs.hidden_states), select_every_k_layer)], dim=-1)
|
| 52 |
+
select_feature_type = select_feature_type.replace("slicefour_", "")
|
| 53 |
+
elif self.select_feature in ["slice_m25811_f6_patch", "slice_m25811_f6_cls_patch"]:
|
| 54 |
+
select_layers = [-2, -5, -8, -11, 6]
|
| 55 |
+
image_features = torch.cat([image_forward_outs.hidden_states[i] for i in select_layers], dim=-1)
|
| 56 |
+
select_feature_type = select_feature_type.replace("slice_m25811_f6_", "")
|
| 57 |
+
else:
|
| 58 |
+
image_features = image_forward_outs.hidden_states[self.select_layer]
|
| 59 |
+
|
| 60 |
+
if select_feature_type == "patch":
|
| 61 |
+
image_features = image_features[:, 1:]
|
| 62 |
+
elif select_feature_type == "cls_patch":
|
| 63 |
+
image_features = image_features
|
| 64 |
+
else:
|
| 65 |
+
raise ValueError(f"Unexpected select feature: {select_feature_type}")
|
| 66 |
+
return image_features
|
| 67 |
+
|
| 68 |
+
def forward(self, images):
|
| 69 |
+
if type(images) is list:
|
| 70 |
+
image_features = []
|
| 71 |
+
for image in images:
|
| 72 |
+
image_forward_out = self.vision_tower(image.to(device=self.device, dtype=self.dtype).unsqueeze(0), output_hidden_states=True)
|
| 73 |
+
image_feature = self.feature_select(image_forward_out).to(image.dtype)
|
| 74 |
+
image_features.append(image_feature)
|
| 75 |
+
else:
|
| 76 |
+
image_forward_outs = self.vision_tower(images.to(device=self.device, dtype=self.dtype), output_hidden_states=True)
|
| 77 |
+
image_features = self.feature_select(image_forward_outs).to(images.dtype)
|
| 78 |
+
|
| 79 |
+
return image_features
|
| 80 |
+
|
| 81 |
+
@property
|
| 82 |
+
def dummy_feature(self):
|
| 83 |
+
return torch.zeros(1, self.hidden_size, device=self.device, dtype=self.dtype)
|
| 84 |
+
|
| 85 |
+
@property
|
| 86 |
+
def dtype(self):
|
| 87 |
+
return self.vision_tower.dtype
|
| 88 |
+
|
| 89 |
+
@property
|
| 90 |
+
def device(self):
|
| 91 |
+
return self.vision_tower.device
|
| 92 |
+
|
| 93 |
+
@property
|
| 94 |
+
def config(self):
|
| 95 |
+
if self.is_loaded:
|
| 96 |
+
return self.vision_tower.config
|
| 97 |
+
else:
|
| 98 |
+
return self.cfg_only
|
| 99 |
+
|
| 100 |
+
@property
|
| 101 |
+
def hidden_size(self):
|
| 102 |
+
_hidden_size = self.config.hidden_size
|
| 103 |
+
if "slicefour" in self.select_feature:
|
| 104 |
+
_hidden_size *= 4
|
| 105 |
+
if "slice_m25811_f6" in self.select_feature:
|
| 106 |
+
_hidden_size *= 5
|
| 107 |
+
return _hidden_size
|
| 108 |
+
|
| 109 |
+
@property
|
| 110 |
+
def num_patches_per_side(self):
|
| 111 |
+
return self.config.image_size // self.config.patch_size
|
| 112 |
+
|
| 113 |
+
@property
|
| 114 |
+
def num_patches(self):
|
| 115 |
+
_num_patches = (self.config.image_size // self.config.patch_size) ** 2
|
| 116 |
+
if "cls_patch" in self.select_feature:
|
| 117 |
+
_num_patches += 1
|
| 118 |
+
return _num_patches
|
| 119 |
+
|
| 120 |
+
@property
|
| 121 |
+
def image_size(self):
|
| 122 |
+
return self.config.image_size
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
class CLIPVisionTowerS2(CLIPVisionTower):
|
| 126 |
+
def __init__(self, vision_tower, args, delay_load=False):
|
| 127 |
+
|
| 128 |
+
self.s2_scales = getattr(args, "s2_scales", "336,672,1008")
|
| 129 |
+
self.s2_scales = list(map(int, self.s2_scales.split(",")))
|
| 130 |
+
self.s2_scales.sort()
|
| 131 |
+
self.s2_split_size = self.s2_scales[0]
|
| 132 |
+
self.s2_image_size = self.s2_scales[-1]
|
| 133 |
+
|
| 134 |
+
super().__init__(vision_tower, args, delay_load)
|
| 135 |
+
|
| 136 |
+
# change resize/crop size in preprocessing to the largest image size in s2_scale
|
| 137 |
+
if not delay_load or getattr(args, "unfreeze_mm_vision_tower", False):
|
| 138 |
+
self.image_processor.size["shortest_edge"] = self.s2_image_size
|
| 139 |
+
self.image_processor.crop_size["height"] = self.image_processor.crop_size["width"] = self.s2_image_size
|
| 140 |
+
|
| 141 |
+
def load_model(self, device_map=None):
|
| 142 |
+
if self.is_loaded:
|
| 143 |
+
rank0_print("{} is already loaded, `load_model` called again, skipping.".format(self.vision_tower_name))
|
| 144 |
+
return
|
| 145 |
+
|
| 146 |
+
self.image_processor = CLIPImageProcessor.from_pretrained(self.vision_tower_name)
|
| 147 |
+
self.vision_tower = CLIPVisionModel.from_pretrained(self.vision_tower_name, device_map=device_map)
|
| 148 |
+
self.vision_tower.requires_grad_(False)
|
| 149 |
+
|
| 150 |
+
self.image_processor.size["shortest_edge"] = self.s2_image_size
|
| 151 |
+
self.image_processor.crop_size["height"] = self.image_processor.crop_size["width"] = self.s2_image_size
|
| 152 |
+
|
| 153 |
+
self.is_loaded = True
|
| 154 |
+
|
| 155 |
+
def forward_feature(self, images):
|
| 156 |
+
image_forward_outs = self.vision_tower(images.to(device=self.device, dtype=self.dtype), output_hidden_states=True)
|
| 157 |
+
image_features = self.feature_select(image_forward_outs).to(images.dtype)
|
| 158 |
+
return image_features
|
| 159 |
+
|
| 160 |
+
def forward(self, images):
|
| 161 |
+
if type(images) is list:
|
| 162 |
+
image_features = []
|
| 163 |
+
for image in images:
|
| 164 |
+
image_feature = multiscale_forward(self.forward_feature, image.unsqueeze(0), img_sizes=self.s2_scales, max_split_size=self.s2_split_size, split_forward=True)
|
| 165 |
+
image_features.append(image_feature)
|
| 166 |
+
else:
|
| 167 |
+
image_features = multiscale_forward(self.forward_feature, images, img_sizes=self.s2_scales, max_split_size=self.s2_split_size, split_forward=True)
|
| 168 |
+
|
| 169 |
+
return image_features
|
| 170 |
+
|
| 171 |
+
@property
|
| 172 |
+
def hidden_size(self):
|
| 173 |
+
return self.config.hidden_size * len(self.s2_scales)
|
之前的代码版本/这一版注意力有问题/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/__init__.py
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .constants import OPENAI_DATASET_MEAN, OPENAI_DATASET_STD
|
| 2 |
+
from .factory import create_model, create_model_and_transforms, create_model_from_pretrained, get_tokenizer
|
| 3 |
+
from .factory import list_models, add_model_config, get_model_config, load_checkpoint
|
| 4 |
+
from .loss import ClipLoss
|
| 5 |
+
from .model import CLIP, CustomCLIP, CLIPTextCfg, CLIPVisionCfg, convert_weights_to_lp, convert_weights_to_fp16, trace_model, get_cast_dtype
|
| 6 |
+
from .openai import load_openai_model, list_openai_models
|
| 7 |
+
from .pretrained import list_pretrained, list_pretrained_models_by_tag, list_pretrained_tags_by_model, get_pretrained_url, download_pretrained_from_url, is_pretrained_cfg, get_pretrained_cfg, download_pretrained
|
| 8 |
+
from .tokenizer import SimpleTokenizer, tokenize
|
| 9 |
+
from .transform import image_transform
|
之前的代码版本/这一版注意力有问题/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/hf_model.py
ADDED
|
@@ -0,0 +1,240 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
""" huggingface model adapter
|
| 2 |
+
|
| 3 |
+
Wraps HuggingFace transformers (https://github.com/huggingface/transformers) models for use as a text tower in CLIP model.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import re
|
| 7 |
+
|
| 8 |
+
import torch
|
| 9 |
+
import torch.nn as nn
|
| 10 |
+
from torch.nn import functional as F
|
| 11 |
+
from torch import TensorType
|
| 12 |
+
|
| 13 |
+
try:
|
| 14 |
+
import transformers
|
| 15 |
+
from transformers import AutoModel, AutoModelForMaskedLM, AutoTokenizer, AutoConfig, PretrainedConfig
|
| 16 |
+
from transformers.modeling_outputs import BaseModelOutput, BaseModelOutputWithPooling, BaseModelOutputWithPoolingAndCrossAttentions
|
| 17 |
+
except ImportError as e:
|
| 18 |
+
transformers = None
|
| 19 |
+
|
| 20 |
+
class BaseModelOutput:
|
| 21 |
+
pass
|
| 22 |
+
|
| 23 |
+
class PretrainedConfig:
|
| 24 |
+
pass
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
from .hf_configs import arch_dict
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
# utils
|
| 31 |
+
def _camel2snake(s):
|
| 32 |
+
return re.sub(r"(?<!^)(?=[A-Z])", "_", s).lower()
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
# TODO: ?last - for gpt-like models
|
| 36 |
+
_POOLERS = {}
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def register_pooler(cls):
|
| 40 |
+
"""Decorator registering pooler class"""
|
| 41 |
+
_POOLERS[_camel2snake(cls.__name__)] = cls
|
| 42 |
+
return cls
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
@register_pooler
|
| 46 |
+
class MeanPooler(nn.Module):
|
| 47 |
+
"""Mean pooling"""
|
| 48 |
+
|
| 49 |
+
def forward(self, x: BaseModelOutput, attention_mask: TensorType):
|
| 50 |
+
masked_output = x.last_hidden_state * attention_mask.unsqueeze(-1)
|
| 51 |
+
return masked_output.sum(dim=1) / attention_mask.sum(-1, keepdim=True)
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
@register_pooler
|
| 55 |
+
class MaxPooler(nn.Module):
|
| 56 |
+
"""Max pooling"""
|
| 57 |
+
|
| 58 |
+
def forward(self, x: BaseModelOutput, attention_mask: TensorType):
|
| 59 |
+
masked_output = x.last_hidden_state.masked_fill(attention_mask.unsqueeze(-1), -torch.inf)
|
| 60 |
+
return masked_output.max(1).values
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
@register_pooler
|
| 64 |
+
class ClsPooler(nn.Module):
|
| 65 |
+
"""CLS token pooling"""
|
| 66 |
+
|
| 67 |
+
def __init__(self, use_pooler_output=True):
|
| 68 |
+
super().__init__()
|
| 69 |
+
self.cls_token_position = 0
|
| 70 |
+
self.use_pooler_output = use_pooler_output
|
| 71 |
+
|
| 72 |
+
def forward(self, x: BaseModelOutput, attention_mask: TensorType):
|
| 73 |
+
|
| 74 |
+
if self.use_pooler_output and isinstance(x, (BaseModelOutputWithPooling, BaseModelOutputWithPoolingAndCrossAttentions)) and (x.pooler_output is not None):
|
| 75 |
+
return x.pooler_output
|
| 76 |
+
|
| 77 |
+
return x.last_hidden_state[:, self.cls_token_position, :]
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
class HFTextEncoder(nn.Module):
|
| 81 |
+
"""HuggingFace model adapter"""
|
| 82 |
+
|
| 83 |
+
def __init__(self, model_name_or_path: str, output_dim: int, tokenizer_name: str = None, config: PretrainedConfig = None, pooler_type: str = None, proj: str = None, pretrained: bool = True, masked_language_modeling: bool = False):
|
| 84 |
+
super().__init__()
|
| 85 |
+
|
| 86 |
+
self.output_dim = output_dim
|
| 87 |
+
|
| 88 |
+
# TODO: find better way to get this information
|
| 89 |
+
uses_transformer_pooler = pooler_type == "cls_pooler"
|
| 90 |
+
|
| 91 |
+
if transformers is None:
|
| 92 |
+
raise RuntimeError("Please `pip install transformers` to use pre-trained HuggingFace models")
|
| 93 |
+
if config is None:
|
| 94 |
+
self.config = AutoConfig.from_pretrained(model_name_or_path)
|
| 95 |
+
if masked_language_modeling:
|
| 96 |
+
create_func, model_args = (AutoModelForMaskedLM.from_pretrained, model_name_or_path) if pretrained else (AutoModelForMaskedLM.from_config, self.config)
|
| 97 |
+
else:
|
| 98 |
+
create_func, model_args = (AutoModel.from_pretrained, model_name_or_path) if pretrained else (AutoModel.from_config, self.config)
|
| 99 |
+
# TODO: do all model configs have this attribute? PretrainedConfig does so yes??
|
| 100 |
+
if hasattr(self.config, "is_encoder_decoder") and self.config.is_encoder_decoder:
|
| 101 |
+
self.transformer = create_func(model_args)
|
| 102 |
+
self.transformer = self.transformer.encoder
|
| 103 |
+
else:
|
| 104 |
+
self.transformer = create_func(model_args, add_pooling_layer=uses_transformer_pooler)
|
| 105 |
+
else:
|
| 106 |
+
self.config = config
|
| 107 |
+
if masked_language_modeling:
|
| 108 |
+
self.transformer = AutoModelForMaskedLM.from_config(config)
|
| 109 |
+
else:
|
| 110 |
+
self.transformer = AutoModel.from_config(config)
|
| 111 |
+
|
| 112 |
+
if pooler_type is None: # get default arch pooler
|
| 113 |
+
self.pooler = _POOLERS[(arch_dict[self.config.model_type]["pooler"])]()
|
| 114 |
+
else:
|
| 115 |
+
self.pooler = _POOLERS[pooler_type]()
|
| 116 |
+
|
| 117 |
+
d_model = getattr(self.config, arch_dict[self.config.model_type]["config_names"]["width"])
|
| 118 |
+
if (d_model == output_dim) and (proj is None): # do we always need a proj?
|
| 119 |
+
self.proj = nn.Identity()
|
| 120 |
+
elif proj == "linear":
|
| 121 |
+
self.proj = nn.Linear(d_model, output_dim, bias=False)
|
| 122 |
+
elif proj == "mlp":
|
| 123 |
+
hidden_size = (d_model + output_dim) // 2
|
| 124 |
+
self.proj = nn.Sequential(
|
| 125 |
+
nn.Linear(d_model, hidden_size, bias=False),
|
| 126 |
+
nn.GELU(),
|
| 127 |
+
nn.Linear(hidden_size, output_dim, bias=False),
|
| 128 |
+
)
|
| 129 |
+
|
| 130 |
+
# self.itm_proj = nn.Linear(d_model, 2, bias=False)
|
| 131 |
+
# self.mlm_proj = nn.Linear(d_model, self.config.vocab_size), bias=False)
|
| 132 |
+
self.tokenizer = AutoTokenizer.from_pretrained(tokenizer_name)
|
| 133 |
+
|
| 134 |
+
# def forward_itm(self, x:TensorType, image_embeds:TensorType) -> TensorType:
|
| 135 |
+
# image_atts = torch.ones(image_embeds.size()[:-1],dtype=torch.long).to(x.device)
|
| 136 |
+
# attn_mask = (x != self.config.pad_token_id).long()
|
| 137 |
+
# out = self.transformer(
|
| 138 |
+
# input_ids=x,
|
| 139 |
+
# attention_mask=attn_mask,
|
| 140 |
+
# encoder_hidden_states = image_embeds,
|
| 141 |
+
# encoder_attention_mask = image_atts,
|
| 142 |
+
# )
|
| 143 |
+
# pooled_out = self.pooler(out, attn_mask)
|
| 144 |
+
|
| 145 |
+
# return self.itm_proj(pooled_out)
|
| 146 |
+
|
| 147 |
+
def mask(self, input_ids, vocab_size, device, targets=None, masked_indices=None, probability_matrix=None):
|
| 148 |
+
if masked_indices is None:
|
| 149 |
+
masked_indices = torch.bernoulli(probability_matrix).bool()
|
| 150 |
+
|
| 151 |
+
masked_indices[input_ids == self.tokenizer.pad_token_id] = False
|
| 152 |
+
masked_indices[input_ids == self.tokenizer.cls_token_id] = False
|
| 153 |
+
|
| 154 |
+
if targets is not None:
|
| 155 |
+
targets[~masked_indices] = -100 # We only compute loss on masked tokens
|
| 156 |
+
|
| 157 |
+
# 80% of the time, we replace masked input tokens with tokenizer.mask_token ([MASK])
|
| 158 |
+
indices_replaced = torch.bernoulli(torch.full(input_ids.shape, 0.8)).bool() & masked_indices
|
| 159 |
+
input_ids[indices_replaced] = self.tokenizer.mask_token_id
|
| 160 |
+
|
| 161 |
+
# 10% of the time, we replace masked input tokens with random word
|
| 162 |
+
indices_random = torch.bernoulli(torch.full(input_ids.shape, 0.5)).bool() & masked_indices & ~indices_replaced
|
| 163 |
+
random_words = torch.randint(vocab_size, input_ids.shape, dtype=torch.long).to(device)
|
| 164 |
+
input_ids[indices_random] = random_words[indices_random]
|
| 165 |
+
# The rest of the time (10% of the time) we keep the masked input tokens unchanged
|
| 166 |
+
|
| 167 |
+
if targets is not None:
|
| 168 |
+
return input_ids, targets
|
| 169 |
+
else:
|
| 170 |
+
return input_ids
|
| 171 |
+
|
| 172 |
+
def forward_mlm(self, input_ids, image_embeds, mlm_probability=0.25):
|
| 173 |
+
labels = input_ids.clone()
|
| 174 |
+
attn_mask = (input_ids != self.config.pad_token_id).long()
|
| 175 |
+
image_atts = torch.ones(image_embeds.size()[:-1], dtype=torch.long).to(input_ids.device)
|
| 176 |
+
vocab_size = getattr(self.config, arch_dict[self.config.model_type]["config_names"]["vocab_size"])
|
| 177 |
+
probability_matrix = torch.full(labels.shape, mlm_probability)
|
| 178 |
+
input_ids, labels = self.mask(input_ids, vocab_size, input_ids.device, targets=labels, probability_matrix=probability_matrix)
|
| 179 |
+
mlm_output = self.transformer(
|
| 180 |
+
input_ids,
|
| 181 |
+
attention_mask=attn_mask,
|
| 182 |
+
encoder_hidden_states=image_embeds,
|
| 183 |
+
encoder_attention_mask=image_atts,
|
| 184 |
+
return_dict=True,
|
| 185 |
+
labels=labels,
|
| 186 |
+
)
|
| 187 |
+
return mlm_output.loss
|
| 188 |
+
# mlm_output = self.transformer(input_ids,
|
| 189 |
+
# attention_mask = attn_mask,
|
| 190 |
+
# encoder_hidden_states = image_embeds,
|
| 191 |
+
# encoder_attention_mask = image_atts,
|
| 192 |
+
# return_dict = True,
|
| 193 |
+
# ).last_hidden_state
|
| 194 |
+
# logits = self.mlm_proj(mlm_output)
|
| 195 |
+
|
| 196 |
+
# # logits = logits[:, :-1, :].contiguous().view(-1, vocab_size)
|
| 197 |
+
# logits = logits[:, 1:, :].contiguous().view(-1, vocab_size)
|
| 198 |
+
# labels = labels[:, 1:].contiguous().view(-1)
|
| 199 |
+
|
| 200 |
+
# mlm_loss = F.cross_entropy(
|
| 201 |
+
# logits,
|
| 202 |
+
# labels,
|
| 203 |
+
# # label_smoothing=0.1,
|
| 204 |
+
# )
|
| 205 |
+
# return mlm_loss
|
| 206 |
+
|
| 207 |
+
def forward(self, x: TensorType) -> TensorType:
|
| 208 |
+
attn_mask = (x != self.config.pad_token_id).long()
|
| 209 |
+
out = self.transformer(input_ids=x, attention_mask=attn_mask)
|
| 210 |
+
pooled_out = self.pooler(out, attn_mask)
|
| 211 |
+
|
| 212 |
+
return self.proj(pooled_out)
|
| 213 |
+
|
| 214 |
+
def lock(self, unlocked_layers: int = 0, freeze_layer_norm: bool = True):
|
| 215 |
+
if not unlocked_layers: # full freezing
|
| 216 |
+
for n, p in self.transformer.named_parameters():
|
| 217 |
+
p.requires_grad = (not freeze_layer_norm) if "LayerNorm" in n.split(".") else False
|
| 218 |
+
return
|
| 219 |
+
|
| 220 |
+
encoder = self.transformer.encoder if hasattr(self.transformer, "encoder") else self.transformer
|
| 221 |
+
layer_list = getattr(encoder, arch_dict[self.config.model_type]["config_names"]["layer_attr"])
|
| 222 |
+
print(f"Unlocking {unlocked_layers}/{len(layer_list) + 1} layers of hf model")
|
| 223 |
+
embeddings = getattr(self.transformer, arch_dict[self.config.model_type]["config_names"]["token_embeddings_attr"])
|
| 224 |
+
modules = [embeddings, *layer_list][:-unlocked_layers]
|
| 225 |
+
# freeze layers
|
| 226 |
+
for module in modules:
|
| 227 |
+
for n, p in module.named_parameters():
|
| 228 |
+
p.requires_grad = (not freeze_layer_norm) if "LayerNorm" in n.split(".") else False
|
| 229 |
+
|
| 230 |
+
@torch.jit.ignore
|
| 231 |
+
def set_grad_checkpointing(self, enable=True):
|
| 232 |
+
self.transformer.gradient_checkpointing_enable()
|
| 233 |
+
|
| 234 |
+
def get_num_layers(self):
|
| 235 |
+
encoder = self.transformer.encoder if hasattr(self.transformer, "encoder") else self.transformer
|
| 236 |
+
layer_list = getattr(encoder, arch_dict[self.config.model_type]["config_names"]["layer_attr"])
|
| 237 |
+
return len(layer_list)
|
| 238 |
+
|
| 239 |
+
def init_parameters(self):
|
| 240 |
+
pass
|
之前的代码版本/这一版注意力有问题/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/loss.py
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
import torch
|
| 3 |
+
import torch.nn as nn
|
| 4 |
+
from torch.nn import functional as F
|
| 5 |
+
|
| 6 |
+
try:
|
| 7 |
+
import torch.distributed.nn
|
| 8 |
+
from torch import distributed as dist
|
| 9 |
+
|
| 10 |
+
has_distributed = True
|
| 11 |
+
except ImportError:
|
| 12 |
+
has_distributed = False
|
| 13 |
+
|
| 14 |
+
try:
|
| 15 |
+
import horovod.torch as hvd
|
| 16 |
+
except ImportError:
|
| 17 |
+
hvd = None
|
| 18 |
+
|
| 19 |
+
from timm.loss import LabelSmoothingCrossEntropy
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def gather_features(image_features, text_features, local_loss=False, gather_with_grad=False, rank=0, world_size=1, use_horovod=False):
|
| 23 |
+
assert has_distributed, "torch.distributed did not import correctly, please use a PyTorch version with support."
|
| 24 |
+
if use_horovod:
|
| 25 |
+
assert hvd is not None, "Please install horovod"
|
| 26 |
+
if gather_with_grad:
|
| 27 |
+
all_image_features = hvd.allgather(image_features)
|
| 28 |
+
all_text_features = hvd.allgather(text_features)
|
| 29 |
+
else:
|
| 30 |
+
with torch.no_grad():
|
| 31 |
+
all_image_features = hvd.allgather(image_features)
|
| 32 |
+
all_text_features = hvd.allgather(text_features)
|
| 33 |
+
if not local_loss:
|
| 34 |
+
# ensure grads for local rank when all_* features don't have a gradient
|
| 35 |
+
gathered_image_features = list(all_image_features.chunk(world_size, dim=0))
|
| 36 |
+
gathered_text_features = list(all_text_features.chunk(world_size, dim=0))
|
| 37 |
+
gathered_image_features[rank] = image_features
|
| 38 |
+
gathered_text_features[rank] = text_features
|
| 39 |
+
all_image_features = torch.cat(gathered_image_features, dim=0)
|
| 40 |
+
all_text_features = torch.cat(gathered_text_features, dim=0)
|
| 41 |
+
else:
|
| 42 |
+
# We gather tensors from all gpus
|
| 43 |
+
if gather_with_grad:
|
| 44 |
+
all_image_features = torch.cat(torch.distributed.nn.all_gather(image_features), dim=0)
|
| 45 |
+
all_text_features = torch.cat(torch.distributed.nn.all_gather(text_features), dim=0)
|
| 46 |
+
# all_image_features = torch.cat(torch.distributed.nn.all_gather(image_features, async_op=True), dim=0)
|
| 47 |
+
# all_text_features = torch.cat(torch.distributed.nn.all_gather(text_features, async_op=True), dim=0)
|
| 48 |
+
else:
|
| 49 |
+
gathered_image_features = [torch.zeros_like(image_features) for _ in range(world_size)]
|
| 50 |
+
gathered_text_features = [torch.zeros_like(text_features) for _ in range(world_size)]
|
| 51 |
+
dist.all_gather(gathered_image_features, image_features)
|
| 52 |
+
dist.all_gather(gathered_text_features, text_features)
|
| 53 |
+
if not local_loss:
|
| 54 |
+
# ensure grads for local rank when all_* features don't have a gradient
|
| 55 |
+
gathered_image_features[rank] = image_features
|
| 56 |
+
gathered_text_features[rank] = text_features
|
| 57 |
+
all_image_features = torch.cat(gathered_image_features, dim=0)
|
| 58 |
+
all_text_features = torch.cat(gathered_text_features, dim=0)
|
| 59 |
+
|
| 60 |
+
return all_image_features, all_text_features
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
class ClipLoss(nn.Module):
|
| 64 |
+
|
| 65 |
+
def __init__(
|
| 66 |
+
self,
|
| 67 |
+
local_loss=False,
|
| 68 |
+
gather_with_grad=False,
|
| 69 |
+
cache_labels=False,
|
| 70 |
+
rank=0,
|
| 71 |
+
world_size=1,
|
| 72 |
+
use_horovod=False,
|
| 73 |
+
smoothing=0.0,
|
| 74 |
+
):
|
| 75 |
+
super().__init__()
|
| 76 |
+
self.local_loss = local_loss
|
| 77 |
+
self.gather_with_grad = gather_with_grad
|
| 78 |
+
self.cache_labels = cache_labels
|
| 79 |
+
self.rank = rank
|
| 80 |
+
self.world_size = world_size
|
| 81 |
+
self.use_horovod = use_horovod
|
| 82 |
+
self.label_smoothing_cross_entropy = LabelSmoothingCrossEntropy(smoothing=smoothing) if smoothing > 0 else None
|
| 83 |
+
|
| 84 |
+
# cache state
|
| 85 |
+
self.prev_num_logits = 0
|
| 86 |
+
self.labels = {}
|
| 87 |
+
|
| 88 |
+
def forward(self, image_features, text_features, logit_scale=1.0):
|
| 89 |
+
device = image_features.device
|
| 90 |
+
if self.world_size > 1:
|
| 91 |
+
all_image_features, all_text_features = gather_features(image_features, text_features, self.local_loss, self.gather_with_grad, self.rank, self.world_size, self.use_horovod)
|
| 92 |
+
|
| 93 |
+
if self.local_loss:
|
| 94 |
+
logits_per_image = logit_scale * image_features @ all_text_features.T
|
| 95 |
+
logits_per_text = logit_scale * text_features @ all_image_features.T
|
| 96 |
+
else:
|
| 97 |
+
logits_per_image = logit_scale * all_image_features @ all_text_features.T
|
| 98 |
+
logits_per_text = logits_per_image.T
|
| 99 |
+
else:
|
| 100 |
+
logits_per_image = logit_scale * image_features @ text_features.T
|
| 101 |
+
logits_per_text = logit_scale * text_features @ image_features.T
|
| 102 |
+
# calculated ground-truth and cache if enabled
|
| 103 |
+
num_logits = logits_per_image.shape[0]
|
| 104 |
+
if self.prev_num_logits != num_logits or device not in self.labels:
|
| 105 |
+
labels = torch.arange(num_logits, device=device, dtype=torch.long)
|
| 106 |
+
if self.world_size > 1 and self.local_loss:
|
| 107 |
+
labels = labels + num_logits * self.rank
|
| 108 |
+
if self.cache_labels:
|
| 109 |
+
self.labels[device] = labels
|
| 110 |
+
self.prev_num_logits = num_logits
|
| 111 |
+
else:
|
| 112 |
+
labels = self.labels[device]
|
| 113 |
+
|
| 114 |
+
if self.label_smoothing_cross_entropy:
|
| 115 |
+
total_loss = (self.label_smoothing_cross_entropy(logits_per_image, labels) + self.label_smoothing_cross_entropy(logits_per_text, labels)) / 2
|
| 116 |
+
else:
|
| 117 |
+
total_loss = (F.cross_entropy(logits_per_image, labels) + F.cross_entropy(logits_per_text, labels)) / 2
|
| 118 |
+
|
| 119 |
+
acc = None
|
| 120 |
+
i2t_acc = (logits_per_image.argmax(-1) == labels).sum() / len(logits_per_image)
|
| 121 |
+
t2i_acc = (logits_per_text.argmax(-1) == labels).sum() / len(logits_per_text)
|
| 122 |
+
acc = {"i2t": i2t_acc, "t2i": t2i_acc}
|
| 123 |
+
return total_loss, acc
|
之前的代码版本/这一版注意力有问题/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/modified_resnet.py
ADDED
|
@@ -0,0 +1,179 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from collections import OrderedDict
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
from torch import nn
|
| 5 |
+
from torch.nn import functional as F
|
| 6 |
+
|
| 7 |
+
from .utils import freeze_batch_norm_2d
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class Bottleneck(nn.Module):
|
| 11 |
+
expansion = 4
|
| 12 |
+
|
| 13 |
+
def __init__(self, inplanes, planes, stride=1):
|
| 14 |
+
super().__init__()
|
| 15 |
+
|
| 16 |
+
# all conv layers have stride 1. an avgpool is performed after the second convolution when stride > 1
|
| 17 |
+
self.conv1 = nn.Conv2d(inplanes, planes, 1, bias=False)
|
| 18 |
+
self.bn1 = nn.BatchNorm2d(planes)
|
| 19 |
+
self.act1 = nn.ReLU(inplace=True)
|
| 20 |
+
|
| 21 |
+
self.conv2 = nn.Conv2d(planes, planes, 3, padding=1, bias=False)
|
| 22 |
+
self.bn2 = nn.BatchNorm2d(planes)
|
| 23 |
+
self.act2 = nn.ReLU(inplace=True)
|
| 24 |
+
|
| 25 |
+
self.avgpool = nn.AvgPool2d(stride) if stride > 1 else nn.Identity()
|
| 26 |
+
|
| 27 |
+
self.conv3 = nn.Conv2d(planes, planes * self.expansion, 1, bias=False)
|
| 28 |
+
self.bn3 = nn.BatchNorm2d(planes * self.expansion)
|
| 29 |
+
self.act3 = nn.ReLU(inplace=True)
|
| 30 |
+
|
| 31 |
+
self.downsample = None
|
| 32 |
+
self.stride = stride
|
| 33 |
+
|
| 34 |
+
if stride > 1 or inplanes != planes * Bottleneck.expansion:
|
| 35 |
+
# downsampling layer is prepended with an avgpool, and the subsequent convolution has stride 1
|
| 36 |
+
self.downsample = nn.Sequential(OrderedDict([("-1", nn.AvgPool2d(stride)), ("0", nn.Conv2d(inplanes, planes * self.expansion, 1, stride=1, bias=False)), ("1", nn.BatchNorm2d(planes * self.expansion))]))
|
| 37 |
+
|
| 38 |
+
def forward(self, x: torch.Tensor):
|
| 39 |
+
identity = x
|
| 40 |
+
|
| 41 |
+
out = self.act1(self.bn1(self.conv1(x)))
|
| 42 |
+
out = self.act2(self.bn2(self.conv2(out)))
|
| 43 |
+
out = self.avgpool(out)
|
| 44 |
+
out = self.bn3(self.conv3(out))
|
| 45 |
+
|
| 46 |
+
if self.downsample is not None:
|
| 47 |
+
identity = self.downsample(x)
|
| 48 |
+
|
| 49 |
+
out += identity
|
| 50 |
+
out = self.act3(out)
|
| 51 |
+
return out
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
class AttentionPool2d(nn.Module):
|
| 55 |
+
def __init__(self, spacial_dim: int, embed_dim: int, num_heads: int, output_dim: int = None):
|
| 56 |
+
super().__init__()
|
| 57 |
+
self.positional_embedding = nn.Parameter(torch.randn(spacial_dim**2 + 1, embed_dim) / embed_dim**0.5)
|
| 58 |
+
self.k_proj = nn.Linear(embed_dim, embed_dim)
|
| 59 |
+
self.q_proj = nn.Linear(embed_dim, embed_dim)
|
| 60 |
+
self.v_proj = nn.Linear(embed_dim, embed_dim)
|
| 61 |
+
self.c_proj = nn.Linear(embed_dim, output_dim or embed_dim)
|
| 62 |
+
self.num_heads = num_heads
|
| 63 |
+
|
| 64 |
+
def forward(self, x):
|
| 65 |
+
x = x.reshape(x.shape[0], x.shape[1], x.shape[2] * x.shape[3]).permute(2, 0, 1) # NCHW -> (HW)NC
|
| 66 |
+
x = torch.cat([x.mean(dim=0, keepdim=True), x], dim=0) # (HW+1)NC
|
| 67 |
+
x = x + self.positional_embedding[:, None, :].to(x.dtype) # (HW+1)NC
|
| 68 |
+
x, _ = F.multi_head_attention_forward(
|
| 69 |
+
query=x,
|
| 70 |
+
key=x,
|
| 71 |
+
value=x,
|
| 72 |
+
embed_dim_to_check=x.shape[-1],
|
| 73 |
+
num_heads=self.num_heads,
|
| 74 |
+
q_proj_weight=self.q_proj.weight,
|
| 75 |
+
k_proj_weight=self.k_proj.weight,
|
| 76 |
+
v_proj_weight=self.v_proj.weight,
|
| 77 |
+
in_proj_weight=None,
|
| 78 |
+
in_proj_bias=torch.cat([self.q_proj.bias, self.k_proj.bias, self.v_proj.bias]),
|
| 79 |
+
bias_k=None,
|
| 80 |
+
bias_v=None,
|
| 81 |
+
add_zero_attn=False,
|
| 82 |
+
dropout_p=0.0,
|
| 83 |
+
out_proj_weight=self.c_proj.weight,
|
| 84 |
+
out_proj_bias=self.c_proj.bias,
|
| 85 |
+
use_separate_proj_weight=True,
|
| 86 |
+
training=self.training,
|
| 87 |
+
need_weights=False,
|
| 88 |
+
)
|
| 89 |
+
|
| 90 |
+
return x[0]
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
class ModifiedResNet(nn.Module):
|
| 94 |
+
"""
|
| 95 |
+
A ResNet class that is similar to torchvision's but contains the following changes:
|
| 96 |
+
- There are now 3 "stem" convolutions as opposed to 1, with an average pool instead of a max pool.
|
| 97 |
+
- Performs anti-aliasing strided convolutions, where an avgpool is prepended to convolutions with stride > 1
|
| 98 |
+
- The final pooling layer is a QKV attention instead of an average pool
|
| 99 |
+
"""
|
| 100 |
+
|
| 101 |
+
def __init__(self, layers, output_dim, heads, image_size=224, width=64):
|
| 102 |
+
super().__init__()
|
| 103 |
+
self.output_dim = output_dim
|
| 104 |
+
self.image_size = image_size
|
| 105 |
+
|
| 106 |
+
# the 3-layer stem
|
| 107 |
+
self.conv1 = nn.Conv2d(3, width // 2, kernel_size=3, stride=2, padding=1, bias=False)
|
| 108 |
+
self.bn1 = nn.BatchNorm2d(width // 2)
|
| 109 |
+
self.act1 = nn.ReLU(inplace=True)
|
| 110 |
+
self.conv2 = nn.Conv2d(width // 2, width // 2, kernel_size=3, padding=1, bias=False)
|
| 111 |
+
self.bn2 = nn.BatchNorm2d(width // 2)
|
| 112 |
+
self.act2 = nn.ReLU(inplace=True)
|
| 113 |
+
self.conv3 = nn.Conv2d(width // 2, width, kernel_size=3, padding=1, bias=False)
|
| 114 |
+
self.bn3 = nn.BatchNorm2d(width)
|
| 115 |
+
self.act3 = nn.ReLU(inplace=True)
|
| 116 |
+
self.avgpool = nn.AvgPool2d(2)
|
| 117 |
+
|
| 118 |
+
# residual layers
|
| 119 |
+
self._inplanes = width # this is a *mutable* variable used during construction
|
| 120 |
+
self.layer1 = self._make_layer(width, layers[0])
|
| 121 |
+
self.layer2 = self._make_layer(width * 2, layers[1], stride=2)
|
| 122 |
+
self.layer3 = self._make_layer(width * 4, layers[2], stride=2)
|
| 123 |
+
self.layer4 = self._make_layer(width * 8, layers[3], stride=2)
|
| 124 |
+
|
| 125 |
+
embed_dim = width * 32 # the ResNet feature dimension
|
| 126 |
+
self.attnpool = AttentionPool2d(image_size // 32, embed_dim, heads, output_dim)
|
| 127 |
+
|
| 128 |
+
self.init_parameters()
|
| 129 |
+
|
| 130 |
+
def _make_layer(self, planes, blocks, stride=1):
|
| 131 |
+
layers = [Bottleneck(self._inplanes, planes, stride)]
|
| 132 |
+
|
| 133 |
+
self._inplanes = planes * Bottleneck.expansion
|
| 134 |
+
for _ in range(1, blocks):
|
| 135 |
+
layers.append(Bottleneck(self._inplanes, planes))
|
| 136 |
+
|
| 137 |
+
return nn.Sequential(*layers)
|
| 138 |
+
|
| 139 |
+
def init_parameters(self):
|
| 140 |
+
if self.attnpool is not None:
|
| 141 |
+
std = self.attnpool.c_proj.in_features**-0.5
|
| 142 |
+
nn.init.normal_(self.attnpool.q_proj.weight, std=std)
|
| 143 |
+
nn.init.normal_(self.attnpool.k_proj.weight, std=std)
|
| 144 |
+
nn.init.normal_(self.attnpool.v_proj.weight, std=std)
|
| 145 |
+
nn.init.normal_(self.attnpool.c_proj.weight, std=std)
|
| 146 |
+
|
| 147 |
+
for resnet_block in [self.layer1, self.layer2, self.layer3, self.layer4]:
|
| 148 |
+
for name, param in resnet_block.named_parameters():
|
| 149 |
+
if name.endswith("bn3.weight"):
|
| 150 |
+
nn.init.zeros_(param)
|
| 151 |
+
|
| 152 |
+
def lock(self, unlocked_groups=0, freeze_bn_stats=False):
|
| 153 |
+
assert unlocked_groups == 0, "partial locking not currently supported for this model"
|
| 154 |
+
for param in self.parameters():
|
| 155 |
+
param.requires_grad = False
|
| 156 |
+
if freeze_bn_stats:
|
| 157 |
+
freeze_batch_norm_2d(self)
|
| 158 |
+
|
| 159 |
+
@torch.jit.ignore
|
| 160 |
+
def set_grad_checkpointing(self, enable=True):
|
| 161 |
+
# FIXME support for non-transformer
|
| 162 |
+
pass
|
| 163 |
+
|
| 164 |
+
def stem(self, x):
|
| 165 |
+
x = self.act1(self.bn1(self.conv1(x)))
|
| 166 |
+
x = self.act2(self.bn2(self.conv2(x)))
|
| 167 |
+
x = self.act3(self.bn3(self.conv3(x)))
|
| 168 |
+
x = self.avgpool(x)
|
| 169 |
+
return x
|
| 170 |
+
|
| 171 |
+
def forward(self, x):
|
| 172 |
+
x = self.stem(x)
|
| 173 |
+
x = self.layer1(x)
|
| 174 |
+
x = self.layer2(x)
|
| 175 |
+
x = self.layer3(x)
|
| 176 |
+
x = self.layer4(x)
|
| 177 |
+
x = self.attnpool(x)
|
| 178 |
+
|
| 179 |
+
return x
|
之前的代码版本/这一版注意力有问题/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/openai.py
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
""" OpenAI pretrained model functions
|
| 2 |
+
|
| 3 |
+
Adapted from https://github.com/openai/CLIP. Originally MIT License, Copyright (c) 2021 OpenAI.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import os
|
| 7 |
+
import warnings
|
| 8 |
+
from typing import List, Optional, Union
|
| 9 |
+
|
| 10 |
+
import torch
|
| 11 |
+
|
| 12 |
+
from .model import build_model_from_openai_state_dict, convert_weights_to_lp, get_cast_dtype
|
| 13 |
+
from .pretrained import get_pretrained_url, list_pretrained_models_by_tag, download_pretrained_from_url
|
| 14 |
+
|
| 15 |
+
__all__ = ["list_openai_models", "load_openai_model"]
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def list_openai_models() -> List[str]:
|
| 19 |
+
"""Returns the names of available CLIP models"""
|
| 20 |
+
return list_pretrained_models_by_tag("openai")
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def load_openai_model(
|
| 24 |
+
name: str,
|
| 25 |
+
precision: Optional[str] = None,
|
| 26 |
+
device: Optional[Union[str, torch.device]] = None,
|
| 27 |
+
jit: bool = True,
|
| 28 |
+
cache_dir: Optional[str] = None,
|
| 29 |
+
):
|
| 30 |
+
"""Load a CLIP model
|
| 31 |
+
|
| 32 |
+
Parameters
|
| 33 |
+
----------
|
| 34 |
+
name : str
|
| 35 |
+
A model name listed by `clip.available_models()`, or the path to a model checkpoint containing the state_dict
|
| 36 |
+
precision: str
|
| 37 |
+
Model precision, if None defaults to 'fp32' if device == 'cpu' else 'fp16'.
|
| 38 |
+
device : Union[str, torch.device]
|
| 39 |
+
The device to put the loaded model
|
| 40 |
+
jit : bool
|
| 41 |
+
Whether to load the optimized JIT model (default) or more hackable non-JIT model.
|
| 42 |
+
cache_dir : Optional[str]
|
| 43 |
+
The directory to cache the downloaded model weights
|
| 44 |
+
|
| 45 |
+
Returns
|
| 46 |
+
-------
|
| 47 |
+
model : torch.nn.Module
|
| 48 |
+
The CLIP model
|
| 49 |
+
preprocess : Callable[[PIL.Image], torch.Tensor]
|
| 50 |
+
A torchvision transform that converts a PIL image into a tensor that the returned model can take as its input
|
| 51 |
+
"""
|
| 52 |
+
if device is None:
|
| 53 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 54 |
+
if precision is None:
|
| 55 |
+
precision = "fp32" if device == "cpu" else "fp16"
|
| 56 |
+
|
| 57 |
+
if get_pretrained_url(name, "openai"):
|
| 58 |
+
model_path = download_pretrained_from_url(get_pretrained_url(name, "openai"), cache_dir=cache_dir)
|
| 59 |
+
elif os.path.isfile(name):
|
| 60 |
+
model_path = name
|
| 61 |
+
else:
|
| 62 |
+
raise RuntimeError(f"Model {name} not found; available models = {list_openai_models()}")
|
| 63 |
+
|
| 64 |
+
try:
|
| 65 |
+
# loading JIT archive
|
| 66 |
+
model = torch.jit.load(model_path, map_location=device if jit else "cpu").eval()
|
| 67 |
+
state_dict = None
|
| 68 |
+
except RuntimeError:
|
| 69 |
+
# loading saved state dict
|
| 70 |
+
if jit:
|
| 71 |
+
warnings.warn(f"File {model_path} is not a JIT archive. Loading as a state dict instead")
|
| 72 |
+
jit = False
|
| 73 |
+
state_dict = torch.load(model_path, map_location="cpu")
|
| 74 |
+
|
| 75 |
+
if not jit:
|
| 76 |
+
# Build a non-jit model from the OpenAI jitted model state dict
|
| 77 |
+
cast_dtype = get_cast_dtype(precision)
|
| 78 |
+
try:
|
| 79 |
+
model = build_model_from_openai_state_dict(state_dict or model.state_dict(), cast_dtype=cast_dtype)
|
| 80 |
+
except KeyError:
|
| 81 |
+
sd = {k[7:]: v for k, v in state_dict["state_dict"].items()}
|
| 82 |
+
model = build_model_from_openai_state_dict(sd, cast_dtype=cast_dtype)
|
| 83 |
+
|
| 84 |
+
# model from OpenAI state dict is in manually cast fp16 mode, must be converted for AMP/fp32/bf16 use
|
| 85 |
+
model = model.to(device)
|
| 86 |
+
if precision.startswith("amp") or precision == "fp32":
|
| 87 |
+
model.float()
|
| 88 |
+
elif precision == "bf16":
|
| 89 |
+
convert_weights_to_lp(model, dtype=torch.bfloat16)
|
| 90 |
+
|
| 91 |
+
return model
|
| 92 |
+
|
| 93 |
+
# patch the device names
|
| 94 |
+
device_holder = torch.jit.trace(lambda: torch.ones([]).to(torch.device(device)), example_inputs=[])
|
| 95 |
+
device_node = [n for n in device_holder.graph.findAllNodes("prim::Constant") if "Device" in repr(n)][-1]
|
| 96 |
+
|
| 97 |
+
def patch_device(module):
|
| 98 |
+
try:
|
| 99 |
+
graphs = [module.graph] if hasattr(module, "graph") else []
|
| 100 |
+
except RuntimeError:
|
| 101 |
+
graphs = []
|
| 102 |
+
|
| 103 |
+
if hasattr(module, "forward1"):
|
| 104 |
+
graphs.append(module.forward1.graph)
|
| 105 |
+
|
| 106 |
+
for graph in graphs:
|
| 107 |
+
for node in graph.findAllNodes("prim::Constant"):
|
| 108 |
+
if "value" in node.attributeNames() and str(node["value"]).startswith("cuda"):
|
| 109 |
+
node.copyAttributes(device_node)
|
| 110 |
+
|
| 111 |
+
model.apply(patch_device)
|
| 112 |
+
patch_device(model.encode_image)
|
| 113 |
+
patch_device(model.encode_text)
|
| 114 |
+
|
| 115 |
+
# patch dtype to float32 (typically for CPU)
|
| 116 |
+
if precision == "fp32":
|
| 117 |
+
float_holder = torch.jit.trace(lambda: torch.ones([]).float(), example_inputs=[])
|
| 118 |
+
float_input = list(float_holder.graph.findNode("aten::to").inputs())[1]
|
| 119 |
+
float_node = float_input.node()
|
| 120 |
+
|
| 121 |
+
def patch_float(module):
|
| 122 |
+
try:
|
| 123 |
+
graphs = [module.graph] if hasattr(module, "graph") else []
|
| 124 |
+
except RuntimeError:
|
| 125 |
+
graphs = []
|
| 126 |
+
|
| 127 |
+
if hasattr(module, "forward1"):
|
| 128 |
+
graphs.append(module.forward1.graph)
|
| 129 |
+
|
| 130 |
+
for graph in graphs:
|
| 131 |
+
for node in graph.findAllNodes("aten::to"):
|
| 132 |
+
inputs = list(node.inputs())
|
| 133 |
+
for i in [1, 2]: # dtype can be the second or third argument to aten::to()
|
| 134 |
+
if inputs[i].node()["value"] == 5:
|
| 135 |
+
inputs[i].node().copyAttributes(float_node)
|
| 136 |
+
|
| 137 |
+
model.apply(patch_float)
|
| 138 |
+
patch_float(model.encode_image)
|
| 139 |
+
patch_float(model.encode_text)
|
| 140 |
+
model.float()
|
| 141 |
+
|
| 142 |
+
# ensure image_size attr available at consistent location for both jit and non-jit
|
| 143 |
+
model.visual.image_size = model.input_resolution.item()
|
| 144 |
+
return model
|
之前的代码版本/这一版注意力有问题/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/pretrained.py
ADDED
|
@@ -0,0 +1,314 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import hashlib
|
| 2 |
+
import os
|
| 3 |
+
import urllib
|
| 4 |
+
import warnings
|
| 5 |
+
from typing import Dict, Union
|
| 6 |
+
|
| 7 |
+
from tqdm import tqdm
|
| 8 |
+
|
| 9 |
+
try:
|
| 10 |
+
from huggingface_hub import hf_hub_download
|
| 11 |
+
|
| 12 |
+
_has_hf_hub = True
|
| 13 |
+
except ImportError:
|
| 14 |
+
hf_hub_download = None
|
| 15 |
+
_has_hf_hub = False
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def _pcfg(url="", hf_hub="", filename="", mean=None, std=None):
|
| 19 |
+
return dict(
|
| 20 |
+
url=url,
|
| 21 |
+
hf_hub=hf_hub,
|
| 22 |
+
mean=mean,
|
| 23 |
+
std=std,
|
| 24 |
+
)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
_VITB32 = dict(
|
| 28 |
+
openai=_pcfg("https://openaipublic.azureedge.net/clip/models/40d365715913c9da98579312b702a82c18be219cc2a73407c4526f58eba950af/ViT-B-32.pt"),
|
| 29 |
+
laion400m_e31=_pcfg("https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/vit_b_32-quickgelu-laion400m_e31-d867053b.pt"),
|
| 30 |
+
laion400m_e32=_pcfg("https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/vit_b_32-quickgelu-laion400m_e32-46683a32.pt"),
|
| 31 |
+
laion2b_e16=_pcfg("https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/vit_b_32-laion2b_e16-af8dbd0c.pth"),
|
| 32 |
+
laion2b_s34b_b79k=_pcfg(hf_hub="laion/CLIP-ViT-B-32-laion2B-s34B-b79K/"),
|
| 33 |
+
)
|
| 34 |
+
|
| 35 |
+
_VITB32_quickgelu = dict(
|
| 36 |
+
openai=_pcfg("https://openaipublic.azureedge.net/clip/models/40d365715913c9da98579312b702a82c18be219cc2a73407c4526f58eba950af/ViT-B-32.pt"),
|
| 37 |
+
laion400m_e31=_pcfg("https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/vit_b_32-quickgelu-laion400m_e31-d867053b.pt"),
|
| 38 |
+
laion400m_e32=_pcfg("https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/vit_b_32-quickgelu-laion400m_e32-46683a32.pt"),
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
_VITB16 = dict(
|
| 42 |
+
openai=_pcfg("https://openaipublic.azureedge.net/clip/models/5806e77cd80f8b59890b7e101eabd078d9fb84e6937f9e85e4ecb61988df416f/ViT-B-16.pt"),
|
| 43 |
+
laion400m_e31=_pcfg("https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/vit_b_16-laion400m_e31-00efa78f.pt"),
|
| 44 |
+
laion400m_e32=_pcfg("https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/vit_b_16-laion400m_e32-55e67d44.pt"),
|
| 45 |
+
laion2b_s34b_b88k=_pcfg(hf_hub="laion/CLIP-ViT-B-16-laion2B-s34B-b88K/"),
|
| 46 |
+
)
|
| 47 |
+
|
| 48 |
+
_EVAB16 = dict(
|
| 49 |
+
eva=_pcfg(hf_hub="QuanSun/EVA-CLIP/EVA02_B_psz14to16.pt"),
|
| 50 |
+
eva02=_pcfg(hf_hub="QuanSun/EVA-CLIP/EVA02_B_psz14to16.pt"),
|
| 51 |
+
eva_clip=_pcfg(hf_hub="QuanSun/EVA-CLIP/EVA02_CLIP_B_psz16_s8B.pt"),
|
| 52 |
+
eva02_clip=_pcfg(hf_hub="QuanSun/EVA-CLIP/EVA02_CLIP_B_psz16_s8B.pt"),
|
| 53 |
+
)
|
| 54 |
+
|
| 55 |
+
_VITB16_PLUS_240 = dict(
|
| 56 |
+
laion400m_e31=_pcfg("https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/vit_b_16_plus_240-laion400m_e31-8fb26589.pt"),
|
| 57 |
+
laion400m_e32=_pcfg("https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/vit_b_16_plus_240-laion400m_e32-699c4b84.pt"),
|
| 58 |
+
)
|
| 59 |
+
|
| 60 |
+
_VITL14 = dict(
|
| 61 |
+
openai=_pcfg("https://openaipublic.azureedge.net/clip/models/b8cca3fd41ae0c99ba7e8951adf17d267cdb84cd88be6f7c2e0eca1737a03836/ViT-L-14.pt"),
|
| 62 |
+
laion400m_e31=_pcfg("https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/vit_l_14-laion400m_e31-69988bb6.pt"),
|
| 63 |
+
laion400m_e32=_pcfg("https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/vit_l_14-laion400m_e32-3d133497.pt"),
|
| 64 |
+
laion2b_s32b_b82k=_pcfg(hf_hub="laion/CLIP-ViT-L-14-laion2B-s32B-b82K/", mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5)),
|
| 65 |
+
)
|
| 66 |
+
|
| 67 |
+
_EVAL14 = dict(
|
| 68 |
+
eva=_pcfg(hf_hub="QuanSun/EVA-CLIP/EVA02_L_psz14.pt"),
|
| 69 |
+
eva02=_pcfg(hf_hub="QuanSun/EVA-CLIP/EVA02_L_psz14.pt"),
|
| 70 |
+
eva_clip=_pcfg(hf_hub="QuanSun/EVA-CLIP/EVA02_CLIP_L_psz14_s4B.pt"),
|
| 71 |
+
eva02_clip=_pcfg(hf_hub="QuanSun/EVA-CLIP/EVA02_CLIP_L_psz14_s4B.pt"),
|
| 72 |
+
)
|
| 73 |
+
|
| 74 |
+
_VITL14_336 = dict(
|
| 75 |
+
openai=_pcfg("https://openaipublic.azureedge.net/clip/models/3035c92b350959924f9f00213499208652fc7ea050643e8b385c2dac08641f02/ViT-L-14-336px.pt"),
|
| 76 |
+
)
|
| 77 |
+
|
| 78 |
+
_EVAL14_336 = dict(
|
| 79 |
+
eva_clip=_pcfg(hf_hub="QuanSun/EVA-CLIP/EVA02_CLIP_L_336_psz14_s6B.pt"),
|
| 80 |
+
eva02_clip=_pcfg(hf_hub="QuanSun/EVA-CLIP/EVA02_CLIP_L_336_psz14_s6B.pt"),
|
| 81 |
+
eva_clip_224to336=_pcfg(hf_hub="QuanSun/EVA-CLIP/EVA02_CLIP_L_psz14_224to336.pt"),
|
| 82 |
+
eva02_clip_224to336=_pcfg(hf_hub="QuanSun/EVA-CLIP/EVA02_CLIP_L_psz14_224to336.pt"),
|
| 83 |
+
)
|
| 84 |
+
|
| 85 |
+
_VITH14 = dict(
|
| 86 |
+
laion2b_s32b_b79k=_pcfg(hf_hub="laion/CLIP-ViT-H-14-laion2B-s32B-b79K/"),
|
| 87 |
+
)
|
| 88 |
+
|
| 89 |
+
_VITg14 = dict(
|
| 90 |
+
laion2b_s12b_b42k=_pcfg(hf_hub="laion/CLIP-ViT-g-14-laion2B-s12B-b42K/"),
|
| 91 |
+
laion2b_s34b_b88k=_pcfg(hf_hub="laion/CLIP-ViT-g-14-laion2B-s34B-b88K/"),
|
| 92 |
+
)
|
| 93 |
+
|
| 94 |
+
_EVAg14 = dict(
|
| 95 |
+
eva=_pcfg(hf_hub="QuanSun/EVA-CLIP/"),
|
| 96 |
+
eva01=_pcfg(hf_hub="QuanSun/EVA-CLIP/EVA01_g_psz14.pt"),
|
| 97 |
+
eva_clip=_pcfg(hf_hub="QuanSun/EVA-CLIP/EVA01_CLIP_g_14_psz14_s11B.pt"),
|
| 98 |
+
eva01_clip=_pcfg(hf_hub="QuanSun/EVA-CLIP/EVA01_CLIP_g_14_psz14_s11B.pt"),
|
| 99 |
+
)
|
| 100 |
+
|
| 101 |
+
_EVAg14_PLUS = dict(
|
| 102 |
+
eva=_pcfg(hf_hub="QuanSun/EVA-CLIP/"),
|
| 103 |
+
eva01=_pcfg(hf_hub="QuanSun/EVA-CLIP/EVA01_g_psz14.pt"),
|
| 104 |
+
eva_clip=_pcfg(hf_hub="QuanSun/EVA-CLIP/EVA01_CLIP_g_14_plus_psz14_s11B.pt"),
|
| 105 |
+
eva01_clip=_pcfg(hf_hub="QuanSun/EVA-CLIP/EVA01_CLIP_g_14_plus_psz14_s11B.pt"),
|
| 106 |
+
)
|
| 107 |
+
|
| 108 |
+
_VITbigG14 = dict(
|
| 109 |
+
laion2b_s39b_b160k=_pcfg(hf_hub="laion/CLIP-ViT-bigG-14-laion2B-39B-b160k/"),
|
| 110 |
+
)
|
| 111 |
+
|
| 112 |
+
_EVAbigE14 = dict(
|
| 113 |
+
eva=_pcfg(hf_hub="QuanSun/EVA-CLIP/EVA02_E_psz14.pt"),
|
| 114 |
+
eva02=_pcfg(hf_hub="QuanSun/EVA-CLIP/EVA02_E_psz14.pt"),
|
| 115 |
+
eva_clip=_pcfg(hf_hub="QuanSun/EVA-CLIP/EVA02_CLIP_E_psz14_s4B.pt"),
|
| 116 |
+
eva02_clip=_pcfg(hf_hub="QuanSun/EVA-CLIP/EVA02_CLIP_E_psz14_s4B.pt"),
|
| 117 |
+
)
|
| 118 |
+
|
| 119 |
+
_EVAbigE14_PLUS = dict(
|
| 120 |
+
eva=_pcfg(hf_hub="QuanSun/EVA-CLIP/EVA02_E_psz14.pt"),
|
| 121 |
+
eva02=_pcfg(hf_hub="QuanSun/EVA-CLIP/EVA02_E_psz14.pt"),
|
| 122 |
+
eva_clip=_pcfg(hf_hub="QuanSun/EVA-CLIP/EVA02_CLIP_E_psz14_plus_s9B.pt"),
|
| 123 |
+
eva02_clip=_pcfg(hf_hub="QuanSun/EVA-CLIP/EVA02_CLIP_E_psz14_plus_s9B.pt"),
|
| 124 |
+
)
|
| 125 |
+
|
| 126 |
+
_EVA_8B = dict(
|
| 127 |
+
eva=_pcfg(hf_hub="BAAI/EVA-CLIP-8B/EVA_8B_psz14.bin"),
|
| 128 |
+
eva_clip=_pcfg(hf_hub="BAAI/EVA-CLIP-8B/EVA_CLIP_8B_psz14_s9B.pt"),
|
| 129 |
+
)
|
| 130 |
+
|
| 131 |
+
_EVA_8B_PLUS = dict(
|
| 132 |
+
eva_clip=_pcfg(hf_hub="BAAI/EVA-CLIP-8B-448/EVA_CLIP_8B_psz14_plus_s0.6B.pt"),
|
| 133 |
+
)
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
_PRETRAINED = {
|
| 137 |
+
# "ViT-B-32": _VITB32,
|
| 138 |
+
"OpenaiCLIP-B-32": _VITB32,
|
| 139 |
+
"OpenCLIP-B-32": _VITB32,
|
| 140 |
+
# "ViT-B-32-quickgelu": _VITB32_quickgelu,
|
| 141 |
+
"OpenaiCLIP-B-32-quickgelu": _VITB32_quickgelu,
|
| 142 |
+
"OpenCLIP-B-32-quickgelu": _VITB32_quickgelu,
|
| 143 |
+
# "ViT-B-16": _VITB16,
|
| 144 |
+
"OpenaiCLIP-B-16": _VITB16,
|
| 145 |
+
"OpenCLIP-B-16": _VITB16,
|
| 146 |
+
"EVA02-B-16": _EVAB16,
|
| 147 |
+
"EVA02-CLIP-B-16": _EVAB16,
|
| 148 |
+
# "ViT-B-16-plus-240": _VITB16_PLUS_240,
|
| 149 |
+
"OpenCLIP-B-16-plus-240": _VITB16_PLUS_240,
|
| 150 |
+
# "ViT-L-14": _VITL14,
|
| 151 |
+
"OpenaiCLIP-L-14": _VITL14,
|
| 152 |
+
"OpenCLIP-L-14": _VITL14,
|
| 153 |
+
"EVA02-L-14": _EVAL14,
|
| 154 |
+
"EVA02-CLIP-L-14": _EVAL14,
|
| 155 |
+
# "ViT-L-14-336": _VITL14_336,
|
| 156 |
+
"OpenaiCLIP-L-14-336": _VITL14_336,
|
| 157 |
+
"EVA02-CLIP-L-14-336": _EVAL14_336,
|
| 158 |
+
# "ViT-H-14": _VITH14,
|
| 159 |
+
# "ViT-g-14": _VITg14,
|
| 160 |
+
"OpenCLIP-H-14": _VITH14,
|
| 161 |
+
"OpenCLIP-g-14": _VITg14,
|
| 162 |
+
"EVA01-CLIP-g-14": _EVAg14,
|
| 163 |
+
"EVA01-CLIP-g-14-plus": _EVAg14_PLUS,
|
| 164 |
+
# "ViT-bigG-14": _VITbigG14,
|
| 165 |
+
"OpenCLIP-bigG-14": _VITbigG14,
|
| 166 |
+
"EVA02-CLIP-bigE-14": _EVAbigE14,
|
| 167 |
+
"EVA02-CLIP-bigE-14-plus": _EVAbigE14_PLUS,
|
| 168 |
+
"EVA-CLIP-8B": _EVA_8B,
|
| 169 |
+
"EVA-CLIP-8B-448": _EVA_8B_PLUS,
|
| 170 |
+
"EVA-CLIP-8B-plus": _EVA_8B_PLUS,
|
| 171 |
+
}
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
def _clean_tag(tag: str):
|
| 175 |
+
# normalize pretrained tags
|
| 176 |
+
return tag.lower().replace("-", "_")
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
def list_pretrained(as_str: bool = False):
|
| 180 |
+
"""returns list of pretrained models
|
| 181 |
+
Returns a tuple (model_name, pretrain_tag) by default or 'name:tag' if as_str == True
|
| 182 |
+
"""
|
| 183 |
+
return [":".join([k, t]) if as_str else (k, t) for k in _PRETRAINED.keys() for t in _PRETRAINED[k].keys()]
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
def list_pretrained_models_by_tag(tag: str):
|
| 187 |
+
"""return all models having the specified pretrain tag"""
|
| 188 |
+
models = []
|
| 189 |
+
tag = _clean_tag(tag)
|
| 190 |
+
for k in _PRETRAINED.keys():
|
| 191 |
+
if tag in _PRETRAINED[k]:
|
| 192 |
+
models.append(k)
|
| 193 |
+
return models
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
def list_pretrained_tags_by_model(model: str):
|
| 197 |
+
"""return all pretrain tags for the specified model architecture"""
|
| 198 |
+
tags = []
|
| 199 |
+
if model in _PRETRAINED:
|
| 200 |
+
tags.extend(_PRETRAINED[model].keys())
|
| 201 |
+
return tags
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
def is_pretrained_cfg(model: str, tag: str):
|
| 205 |
+
if model not in _PRETRAINED:
|
| 206 |
+
return False
|
| 207 |
+
return _clean_tag(tag) in _PRETRAINED[model]
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
def get_pretrained_cfg(model: str, tag: str):
|
| 211 |
+
if model not in _PRETRAINED:
|
| 212 |
+
return {}
|
| 213 |
+
model_pretrained = _PRETRAINED[model]
|
| 214 |
+
return model_pretrained.get(_clean_tag(tag), {})
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
def get_pretrained_url(model: str, tag: str):
|
| 218 |
+
cfg = get_pretrained_cfg(model, _clean_tag(tag))
|
| 219 |
+
return cfg.get("url", "")
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
def download_pretrained_from_url(
|
| 223 |
+
url: str,
|
| 224 |
+
cache_dir: Union[str, None] = None,
|
| 225 |
+
):
|
| 226 |
+
if not cache_dir:
|
| 227 |
+
cache_dir = os.path.expanduser("~/.cache/clip")
|
| 228 |
+
os.makedirs(cache_dir, exist_ok=True)
|
| 229 |
+
filename = os.path.basename(url)
|
| 230 |
+
|
| 231 |
+
if "openaipublic" in url:
|
| 232 |
+
expected_sha256 = url.split("/")[-2]
|
| 233 |
+
elif "mlfoundations" in url:
|
| 234 |
+
expected_sha256 = os.path.splitext(filename)[0].split("-")[-1]
|
| 235 |
+
else:
|
| 236 |
+
expected_sha256 = ""
|
| 237 |
+
|
| 238 |
+
download_target = os.path.join(cache_dir, filename)
|
| 239 |
+
|
| 240 |
+
if os.path.exists(download_target) and not os.path.isfile(download_target):
|
| 241 |
+
raise RuntimeError(f"{download_target} exists and is not a regular file")
|
| 242 |
+
|
| 243 |
+
if os.path.isfile(download_target):
|
| 244 |
+
if expected_sha256:
|
| 245 |
+
if hashlib.sha256(open(download_target, "rb").read()).hexdigest().startswith(expected_sha256):
|
| 246 |
+
return download_target
|
| 247 |
+
else:
|
| 248 |
+
warnings.warn(f"{download_target} exists, but the SHA256 checksum does not match; re-downloading the file")
|
| 249 |
+
else:
|
| 250 |
+
return download_target
|
| 251 |
+
|
| 252 |
+
with urllib.request.urlopen(url) as source, open(download_target, "wb") as output:
|
| 253 |
+
with tqdm(total=int(source.headers.get("Content-Length")), ncols=80, unit="iB", unit_scale=True) as loop:
|
| 254 |
+
while True:
|
| 255 |
+
buffer = source.read(8192)
|
| 256 |
+
if not buffer:
|
| 257 |
+
break
|
| 258 |
+
|
| 259 |
+
output.write(buffer)
|
| 260 |
+
loop.update(len(buffer))
|
| 261 |
+
|
| 262 |
+
if expected_sha256 and not hashlib.sha256(open(download_target, "rb").read()).hexdigest().startswith(expected_sha256):
|
| 263 |
+
raise RuntimeError(f"Model has been downloaded but the SHA256 checksum does not not match")
|
| 264 |
+
|
| 265 |
+
return download_target
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
def has_hf_hub(necessary=False):
|
| 269 |
+
if not _has_hf_hub and necessary:
|
| 270 |
+
# if no HF Hub module installed, and it is necessary to continue, raise error
|
| 271 |
+
raise RuntimeError("Hugging Face hub model specified but package not installed. Run `pip install huggingface_hub`.")
|
| 272 |
+
return _has_hf_hub
|
| 273 |
+
|
| 274 |
+
|
| 275 |
+
def download_pretrained_from_hf(
|
| 276 |
+
model_id: str,
|
| 277 |
+
filename: str = "open_clip_pytorch_model.bin",
|
| 278 |
+
revision=None,
|
| 279 |
+
cache_dir: Union[str, None] = None,
|
| 280 |
+
):
|
| 281 |
+
has_hf_hub(True)
|
| 282 |
+
cached_file = hf_hub_download(model_id, filename, revision=revision, cache_dir=cache_dir)
|
| 283 |
+
return cached_file
|
| 284 |
+
|
| 285 |
+
|
| 286 |
+
def download_pretrained(
|
| 287 |
+
cfg: Dict,
|
| 288 |
+
force_hf_hub: bool = False,
|
| 289 |
+
cache_dir: Union[str, None] = None,
|
| 290 |
+
):
|
| 291 |
+
target = ""
|
| 292 |
+
if not cfg:
|
| 293 |
+
return target
|
| 294 |
+
|
| 295 |
+
download_url = cfg.get("url", "")
|
| 296 |
+
download_hf_hub = cfg.get("hf_hub", "")
|
| 297 |
+
if download_hf_hub and force_hf_hub:
|
| 298 |
+
# use HF hub even if url exists
|
| 299 |
+
download_url = ""
|
| 300 |
+
|
| 301 |
+
if download_url:
|
| 302 |
+
target = download_pretrained_from_url(download_url, cache_dir=cache_dir)
|
| 303 |
+
elif download_hf_hub:
|
| 304 |
+
has_hf_hub(True)
|
| 305 |
+
# we assume the hf_hub entries in pretrained config combine model_id + filename in
|
| 306 |
+
# 'org/model_name/filename.pt' form. To specify just the model id w/o filename and
|
| 307 |
+
# use 'open_clip_pytorch_model.bin' default, there must be a trailing slash 'org/model_name/'.
|
| 308 |
+
model_id, filename = os.path.split(download_hf_hub)
|
| 309 |
+
if filename:
|
| 310 |
+
target = download_pretrained_from_hf(model_id, filename=filename, cache_dir=cache_dir)
|
| 311 |
+
else:
|
| 312 |
+
target = download_pretrained_from_hf(model_id, cache_dir=cache_dir)
|
| 313 |
+
|
| 314 |
+
return target
|
之前的代码版本/这一版注意力有问题/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/timm_model.py
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
""" timm model adapter
|
| 2 |
+
|
| 3 |
+
Wraps timm (https://github.com/rwightman/pytorch-image-models) models for use as a vision tower in CLIP model.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import logging
|
| 7 |
+
from collections import OrderedDict
|
| 8 |
+
|
| 9 |
+
import torch
|
| 10 |
+
import torch.nn as nn
|
| 11 |
+
|
| 12 |
+
try:
|
| 13 |
+
import timm
|
| 14 |
+
from timm.models.layers import Mlp, to_2tuple
|
| 15 |
+
|
| 16 |
+
try:
|
| 17 |
+
# old timm imports < 0.8.1
|
| 18 |
+
from timm.models.layers.attention_pool2d import RotAttentionPool2d
|
| 19 |
+
from timm.models.layers.attention_pool2d import AttentionPool2d as AbsAttentionPool2d
|
| 20 |
+
except ImportError:
|
| 21 |
+
# new timm imports >= 0.8.1
|
| 22 |
+
from timm.layers import RotAttentionPool2d
|
| 23 |
+
from timm.layers import AttentionPool2d as AbsAttentionPool2d
|
| 24 |
+
except ImportError:
|
| 25 |
+
timm = None
|
| 26 |
+
|
| 27 |
+
from .utils import freeze_batch_norm_2d
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class TimmModel(nn.Module):
|
| 31 |
+
"""timm model adapter
|
| 32 |
+
# FIXME this adapter is a work in progress, may change in ways that break weight compat
|
| 33 |
+
"""
|
| 34 |
+
|
| 35 |
+
def __init__(self, model_name, embed_dim, image_size=224, pool="avg", proj="linear", proj_bias=False, drop=0.0, pretrained=False):
|
| 36 |
+
super().__init__()
|
| 37 |
+
if timm is None:
|
| 38 |
+
raise RuntimeError("Please `pip install timm` to use timm models.")
|
| 39 |
+
|
| 40 |
+
self.image_size = to_2tuple(image_size)
|
| 41 |
+
self.trunk = timm.create_model(model_name, pretrained=pretrained)
|
| 42 |
+
feat_size = self.trunk.default_cfg.get("pool_size", None)
|
| 43 |
+
feature_ndim = 1 if not feat_size else 2
|
| 44 |
+
if pool in ("abs_attn", "rot_attn"):
|
| 45 |
+
assert feature_ndim == 2
|
| 46 |
+
# if attn pooling used, remove both classifier and default pool
|
| 47 |
+
self.trunk.reset_classifier(0, global_pool="")
|
| 48 |
+
else:
|
| 49 |
+
# reset global pool if pool config set, otherwise leave as network default
|
| 50 |
+
reset_kwargs = dict(global_pool=pool) if pool else {}
|
| 51 |
+
self.trunk.reset_classifier(0, **reset_kwargs)
|
| 52 |
+
prev_chs = self.trunk.num_features
|
| 53 |
+
|
| 54 |
+
head_layers = OrderedDict()
|
| 55 |
+
if pool == "abs_attn":
|
| 56 |
+
head_layers["pool"] = AbsAttentionPool2d(prev_chs, feat_size=feat_size, out_features=embed_dim)
|
| 57 |
+
prev_chs = embed_dim
|
| 58 |
+
elif pool == "rot_attn":
|
| 59 |
+
head_layers["pool"] = RotAttentionPool2d(prev_chs, out_features=embed_dim)
|
| 60 |
+
prev_chs = embed_dim
|
| 61 |
+
else:
|
| 62 |
+
assert proj, "projection layer needed if non-attention pooling is used."
|
| 63 |
+
|
| 64 |
+
# NOTE attention pool ends with a projection layer, so proj should usually be set to '' if such pooling is used
|
| 65 |
+
if proj == "linear":
|
| 66 |
+
head_layers["drop"] = nn.Dropout(drop)
|
| 67 |
+
head_layers["proj"] = nn.Linear(prev_chs, embed_dim, bias=proj_bias)
|
| 68 |
+
elif proj == "mlp":
|
| 69 |
+
head_layers["mlp"] = Mlp(prev_chs, 2 * embed_dim, embed_dim, drop=drop, bias=(True, proj_bias))
|
| 70 |
+
|
| 71 |
+
self.head = nn.Sequential(head_layers)
|
| 72 |
+
|
| 73 |
+
def lock(self, unlocked_groups=0, freeze_bn_stats=False):
|
| 74 |
+
"""lock modules
|
| 75 |
+
Args:
|
| 76 |
+
unlocked_groups (int): leave last n layer groups unlocked (default: 0)
|
| 77 |
+
"""
|
| 78 |
+
if not unlocked_groups:
|
| 79 |
+
# lock full model
|
| 80 |
+
for param in self.trunk.parameters():
|
| 81 |
+
param.requires_grad = False
|
| 82 |
+
if freeze_bn_stats:
|
| 83 |
+
freeze_batch_norm_2d(self.trunk)
|
| 84 |
+
else:
|
| 85 |
+
# NOTE: partial freeze requires latest timm (master) branch and is subject to change
|
| 86 |
+
try:
|
| 87 |
+
# FIXME import here until API stable and in an official release
|
| 88 |
+
from timm.models.helpers import group_parameters, group_modules
|
| 89 |
+
except ImportError:
|
| 90 |
+
raise RuntimeError("Please install latest timm `pip install git+https://github.com/rwightman/pytorch-image-models`")
|
| 91 |
+
matcher = self.trunk.group_matcher()
|
| 92 |
+
gparams = group_parameters(self.trunk, matcher)
|
| 93 |
+
max_layer_id = max(gparams.keys())
|
| 94 |
+
max_layer_id = max_layer_id - unlocked_groups
|
| 95 |
+
for group_idx in range(max_layer_id + 1):
|
| 96 |
+
group = gparams[group_idx]
|
| 97 |
+
for param in group:
|
| 98 |
+
self.trunk.get_parameter(param).requires_grad = False
|
| 99 |
+
if freeze_bn_stats:
|
| 100 |
+
gmodules = group_modules(self.trunk, matcher, reverse=True)
|
| 101 |
+
gmodules = {k for k, v in gmodules.items() if v <= max_layer_id}
|
| 102 |
+
freeze_batch_norm_2d(self.trunk, gmodules)
|
| 103 |
+
|
| 104 |
+
@torch.jit.ignore
|
| 105 |
+
def set_grad_checkpointing(self, enable=True):
|
| 106 |
+
try:
|
| 107 |
+
self.trunk.set_grad_checkpointing(enable)
|
| 108 |
+
except Exception as e:
|
| 109 |
+
logging.warning("grad checkpointing not supported for this timm image tower, continuing without...")
|
| 110 |
+
|
| 111 |
+
def forward(self, x):
|
| 112 |
+
x = self.trunk(x)
|
| 113 |
+
x = self.head(x)
|
| 114 |
+
return x
|
之前的代码版本/这一版注意力有问题/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_vit.py
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Based on EVA, BEIT, timm and DeiT code bases
|
| 2 |
+
# https://github.com/baaivision/EVA
|
| 3 |
+
# https://github.com/rwightman/pytorch-image-models/tree/master/timm
|
| 4 |
+
# https://github.com/microsoft/unilm/tree/master/beit
|
| 5 |
+
# https://github.com/facebookresearch/deit/
|
| 6 |
+
# https://github.com/facebookresearch/dino
|
| 7 |
+
# --------------------------------------------------------'
|
| 8 |
+
# not tested yet
|
| 9 |
+
import math
|
| 10 |
+
from transformers import CLIPImageProcessor
|
| 11 |
+
|
| 12 |
+
import torch
|
| 13 |
+
import torch.nn as nn
|
| 14 |
+
import torch.nn.functional as F
|
| 15 |
+
import torch.utils.checkpoint as checkpoint
|
| 16 |
+
from timm.models.layers import drop_path, to_2tuple, trunc_normal_
|
| 17 |
+
from .eva_clip import create_model_and_transforms, get_model_config
|
| 18 |
+
import torch
|
| 19 |
+
import torchvision
|
| 20 |
+
import time
|
| 21 |
+
|
| 22 |
+
from llava.utils import rank0_print
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class EvaViTWrapper(nn.Module):
|
| 26 |
+
def __init__(self, vision_tower, args, delay_load=False):
|
| 27 |
+
super().__init__()
|
| 28 |
+
|
| 29 |
+
self.is_loaded = False
|
| 30 |
+
self.vision_tower_name = vision_tower
|
| 31 |
+
self.pretrained = args.vision_tower_pretrained
|
| 32 |
+
self.args = args
|
| 33 |
+
|
| 34 |
+
self.select_layer = args.mm_vision_select_layer
|
| 35 |
+
if self.select_layer < -1:
|
| 36 |
+
self.select_layer += 1
|
| 37 |
+
self.select_feature = getattr(args, "mm_vision_select_feature", "patch")
|
| 38 |
+
|
| 39 |
+
self.model_config = get_model_config(self.vision_tower_name)
|
| 40 |
+
|
| 41 |
+
if not delay_load:
|
| 42 |
+
rank0_print(f"Loading vision tower: {vision_tower}")
|
| 43 |
+
self.load_model()
|
| 44 |
+
elif getattr(args, "unfreeze_mm_vision_tower", False):
|
| 45 |
+
# TODO: better detector is needed.
|
| 46 |
+
rank0_print(f"The checkpoint seems to contain `vision_tower` weights: `unfreeze_mm_vision_tower`: True.")
|
| 47 |
+
self.load_model()
|
| 48 |
+
elif hasattr(args, "mm_tunable_parts") and "mm_vision_tower" in args.mm_tunable_parts:
|
| 49 |
+
rank0_print(f"The checkpoint seems to contain `vision_tower` weights: `mm_tunable_parts` contains `mm_vision_tower`.")
|
| 50 |
+
self.load_model()
|
| 51 |
+
|
| 52 |
+
def load_model(self):
|
| 53 |
+
rank0_print(f"Loading: {self.vision_tower_name}")
|
| 54 |
+
rank0_print(f"Pretrained: {self.pretrained}")
|
| 55 |
+
time_start = time.time()
|
| 56 |
+
model, _, image_processor = create_model_and_transforms(self.vision_tower_name, self.pretrained, force_custom_clip=True, precision="fp16")
|
| 57 |
+
time_end = time.time()
|
| 58 |
+
rank0_print(f"Loaded: {self.vision_tower_name} in {time_end - time_start:.2f}s")
|
| 59 |
+
self.device = next(model.parameters()).device
|
| 60 |
+
self.dtype = next(model.parameters()).dtype
|
| 61 |
+
if self.device.type != "meta":
|
| 62 |
+
model = model.to("cuda")
|
| 63 |
+
self.vision_tower = model.visual
|
| 64 |
+
resize_transform = [t for t in image_processor.transforms if isinstance(t, torchvision.transforms.Resize)][0]
|
| 65 |
+
normalize_transform = [t for t in image_processor.transforms if isinstance(t, torchvision.transforms.Normalize)][0]
|
| 66 |
+
self.resize_transform_size = resize_transform.size
|
| 67 |
+
self.image_processor = CLIPImageProcessor.from_pretrained(
|
| 68 |
+
"openai/clip-vit-large-patch14",
|
| 69 |
+
crop_size=resize_transform.size,
|
| 70 |
+
size={"shortest_edge": resize_transform.size},
|
| 71 |
+
image_mean=list(normalize_transform.mean),
|
| 72 |
+
image_std=list(normalize_transform.std),
|
| 73 |
+
)
|
| 74 |
+
rank0_print(f"Loaded image processor: {self.image_processor}")
|
| 75 |
+
self.vision_tower.requires_grad_(False)
|
| 76 |
+
self.is_loaded = True
|
| 77 |
+
|
| 78 |
+
def feature_select(self, image_features):
|
| 79 |
+
select_feature_type = self.select_feature
|
| 80 |
+
|
| 81 |
+
# if self.select_feature in ["slicefour_patch", "slicefour_cls_patch"]:
|
| 82 |
+
# select_every_k_layer = len(image_features) // 4
|
| 83 |
+
# image_features = torch.cat([image_features[i] for i in range(select_every_k_layer + self.select_layer, len(image_features), select_every_k_layer)], dim=-1)
|
| 84 |
+
# select_feature_type = select_feature_type.replace("slicefour_", "")
|
| 85 |
+
# elif self.select_feature in ["slice_m25811_f6_patch", "slice_m25811_f6_cls_patch"]:
|
| 86 |
+
# select_layers = [-1, -4, -7, -10, 6]
|
| 87 |
+
# image_features = torch.cat([image_features[i] for i in select_layers], dim=-1)
|
| 88 |
+
# select_feature_type = select_feature_type.replace("slice_m25811_f6_", "")
|
| 89 |
+
# else:
|
| 90 |
+
# image_features = image_features[self.select_layer]
|
| 91 |
+
|
| 92 |
+
if select_feature_type == "patch":
|
| 93 |
+
image_features = image_features[:, 1:]
|
| 94 |
+
elif select_feature_type == "cls_patch":
|
| 95 |
+
image_features = image_features
|
| 96 |
+
else:
|
| 97 |
+
raise ValueError(f"Unexpected select feature: {select_feature_type}")
|
| 98 |
+
return image_features
|
| 99 |
+
|
| 100 |
+
def train(self, mode=True):
|
| 101 |
+
self.training = mode
|
| 102 |
+
|
| 103 |
+
if self.is_loaded:
|
| 104 |
+
self.vision_tower.eval()
|
| 105 |
+
|
| 106 |
+
def forward(self, images):
|
| 107 |
+
if type(images) is list:
|
| 108 |
+
image_features = []
|
| 109 |
+
for image in images:
|
| 110 |
+
image_features = self.vision_tower.forward_features(image.to(self.dtype), return_all_features=True)
|
| 111 |
+
image_features = self.feature_select(image_features).to(self.dtype)
|
| 112 |
+
image_features.append(image_features)
|
| 113 |
+
else:
|
| 114 |
+
image_features = self.vision_tower.forward_features(images.to(self.dtype), return_all_features=True)
|
| 115 |
+
image_features = self.feature_select(image_features).to(self.dtype)
|
| 116 |
+
|
| 117 |
+
return image_features
|
| 118 |
+
|
| 119 |
+
@property
|
| 120 |
+
def dummy_feature(self):
|
| 121 |
+
return torch.zeros(1, self.hidden_size, device=self.device, dtype=self.dtype)
|
| 122 |
+
|
| 123 |
+
@property
|
| 124 |
+
def hidden_size(self):
|
| 125 |
+
return self.model_config["vision_cfg"]["width"]
|
| 126 |
+
|
| 127 |
+
@property
|
| 128 |
+
def num_patches(self):
|
| 129 |
+
return (self.model_config["vision_cfg"]["image_size"] // self.model_config["vision_cfg"]["patch_size"]) ** 2
|
| 130 |
+
|
| 131 |
+
@property
|
| 132 |
+
def num_patches_per_side(self):
|
| 133 |
+
return self.model_config["vision_cfg"]["image_size"] // self.model_config["vision_cfg"]["patch_size"]
|
| 134 |
+
|
| 135 |
+
@property
|
| 136 |
+
def config(self):
|
| 137 |
+
return self.model_config
|
| 138 |
+
|
| 139 |
+
@property
|
| 140 |
+
def image_size(self):
|
| 141 |
+
return self.model_config["vision_cfg"]["image_size"]
|
之前的代码版本/这一版注意力有问题/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/hf_vision.py
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
|
| 4 |
+
from transformers import AutoModel, AutoImageProcessor, AutoConfig, CLIPImageProcessor
|
| 5 |
+
from llava.utils import rank0_print
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class HFVisionTower(nn.Module):
|
| 9 |
+
def __init__(self, vision_tower, args, delay_load=False):
|
| 10 |
+
super().__init__()
|
| 11 |
+
|
| 12 |
+
self.is_loaded = False
|
| 13 |
+
|
| 14 |
+
self.vision_tower_name = vision_tower.replace("hf:", "", 1)
|
| 15 |
+
self.select_layer = args.mm_vision_select_layer
|
| 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 = AutoConfig.from_pretrained(self.vision_tower_name)
|
| 22 |
+
|
| 23 |
+
def load_model(self):
|
| 24 |
+
try:
|
| 25 |
+
self.image_processor = AutoImageProcessor.from_pretrained(self.vision_tower_name)
|
| 26 |
+
except Exception as e:
|
| 27 |
+
if "448" in self.vision_tower_name:
|
| 28 |
+
image_size = 448
|
| 29 |
+
# use image processor with conig
|
| 30 |
+
self.image_processor = CLIPImageProcessor(size={"shortest_edge": image_size}, do_center_crop=True, crop_size=image_size)
|
| 31 |
+
else:
|
| 32 |
+
self.image_processor = CLIPImageProcessor.from_pretrained("openai/clip-vit-large-patch14")
|
| 33 |
+
rank0_print(f"Loaded image processor: {self.image_processor}")
|
| 34 |
+
self.vision_tower = AutoModel.from_pretrained(self.vision_tower_name, torch_dtype=torch.bfloat16, trust_remote_code=True).to("cuda")
|
| 35 |
+
self.device = self.vision_tower.device
|
| 36 |
+
self.dtype = self.vision_tower.dtype
|
| 37 |
+
self.config = self.vision_tower.config
|
| 38 |
+
|
| 39 |
+
if hasattr(self.vision_tower, "vision_model"):
|
| 40 |
+
self.vision_tower = self.vision_tower.vision_model
|
| 41 |
+
self.vision_tower.requires_grad_(False)
|
| 42 |
+
# self.vision_tower.eval()
|
| 43 |
+
self.is_loaded = True
|
| 44 |
+
|
| 45 |
+
def feature_select(self, image_forward_outs):
|
| 46 |
+
select_feature_type = self.select_feature
|
| 47 |
+
|
| 48 |
+
if self.select_feature in ["slicefour_patch", "slicefour_cls_patch"]:
|
| 49 |
+
select_every_k_layer = len(image_forward_outs.hidden_states) // 4
|
| 50 |
+
image_features = torch.cat([image_forward_outs.hidden_states[i] for i in range(select_every_k_layer + self.select_layer, len(image_forward_outs.hidden_states), select_every_k_layer)], dim=-1)
|
| 51 |
+
select_feature_type = select_feature_type.replace("slicefour_", "")
|
| 52 |
+
else:
|
| 53 |
+
image_features = image_forward_outs.hidden_states[self.select_layer]
|
| 54 |
+
|
| 55 |
+
if select_feature_type == "patch":
|
| 56 |
+
image_features = image_features[:, 1:]
|
| 57 |
+
elif select_feature_type == "cls_patch":
|
| 58 |
+
image_features = image_features
|
| 59 |
+
else:
|
| 60 |
+
raise ValueError(f"Unexpected select feature: {select_feature_type}")
|
| 61 |
+
return image_features
|
| 62 |
+
|
| 63 |
+
def forward(self, images):
|
| 64 |
+
if type(images) is list:
|
| 65 |
+
image_features = []
|
| 66 |
+
for image in images:
|
| 67 |
+
image_forward_out = self.vision_tower(image.to(device=self.device, dtype=self.dtype).unsqueeze(0), output_hidden_states=True)
|
| 68 |
+
image_feature = self.feature_select(image_forward_out).to(image.dtype)
|
| 69 |
+
image_features.append(image_feature)
|
| 70 |
+
else:
|
| 71 |
+
image_forward_outs = self.vision_tower(images.to(device=self.device, dtype=self.dtype), output_hidden_states=True)
|
| 72 |
+
image_features = self.feature_select(image_forward_outs).to(images.dtype)
|
| 73 |
+
|
| 74 |
+
return image_features
|
| 75 |
+
|
| 76 |
+
@property
|
| 77 |
+
def dummy_feature(self):
|
| 78 |
+
return torch.zeros(1, self.hidden_size, device=self.device, dtype=self.dtype)
|
| 79 |
+
|
| 80 |
+
# @property
|
| 81 |
+
# def dtype(self):
|
| 82 |
+
# return self.vision_tower.dtype
|
| 83 |
+
|
| 84 |
+
# @property
|
| 85 |
+
# def device(self):
|
| 86 |
+
# return self.vision_tower.device
|
| 87 |
+
|
| 88 |
+
@property
|
| 89 |
+
def hidden_size(self):
|
| 90 |
+
try:
|
| 91 |
+
_hidden_size = self.config.hidden_size
|
| 92 |
+
except:
|
| 93 |
+
_hidden_size = self.config.vision_config.hidden_size
|
| 94 |
+
if "slicefour" in self.select_feature:
|
| 95 |
+
_hidden_size *= 4
|
| 96 |
+
return _hidden_size
|
| 97 |
+
|
| 98 |
+
@property
|
| 99 |
+
def num_patches(self):
|
| 100 |
+
_num_patches = (self.config.image_size // self.config.patch_size) ** 2
|
| 101 |
+
if "cls_patch" in self.select_feature:
|
| 102 |
+
_num_patches += 1
|
| 103 |
+
return _num_patches
|
| 104 |
+
|
| 105 |
+
@property
|
| 106 |
+
def num_patches_per_side(self):
|
| 107 |
+
return self.config.image_size // self.config.patch_size
|
| 108 |
+
|
| 109 |
+
@property
|
| 110 |
+
def image_size(self):
|
| 111 |
+
return self.config.image_size
|
之前的代码版本/这一版注意力有问题/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/imagebind.py
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
|
| 4 |
+
from transformers import CLIPImageProcessor
|
| 5 |
+
|
| 6 |
+
try:
|
| 7 |
+
from imagebind.models import imagebind_model
|
| 8 |
+
from imagebind.models.imagebind_model import ModalityType
|
| 9 |
+
from imagebind.data import load_and_transform_audio_data
|
| 10 |
+
except ImportError:
|
| 11 |
+
pass
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class ImageBindWrapper(nn.Module):
|
| 15 |
+
def __init__(self, vision_tower, select_layer, select_feature="patch", delay_load=False):
|
| 16 |
+
super().__init__()
|
| 17 |
+
|
| 18 |
+
self.is_loaded = False
|
| 19 |
+
|
| 20 |
+
self.vision_tower_name = vision_tower
|
| 21 |
+
self.select_layer = select_layer
|
| 22 |
+
self.select_feature = select_feature
|
| 23 |
+
|
| 24 |
+
if not delay_load:
|
| 25 |
+
self.load_model()
|
| 26 |
+
|
| 27 |
+
def load_model(self):
|
| 28 |
+
self.image_processor = CLIPImageProcessor.from_pretrained("openai/clip-vit-large-patch14")
|
| 29 |
+
self.vision_tower = imagebind_model.imagebind_huge(pretrained=True)
|
| 30 |
+
for p in self.vision_tower.parameters():
|
| 31 |
+
p.requires_grad = False
|
| 32 |
+
self.vision_tower.eval()
|
| 33 |
+
self.is_loaded = True
|
| 34 |
+
|
| 35 |
+
def train(self, mode=True):
|
| 36 |
+
self.training = mode
|
| 37 |
+
|
| 38 |
+
if self.is_loaded:
|
| 39 |
+
self.vision_tower.eval()
|
| 40 |
+
|
| 41 |
+
@torch.no_grad()
|
| 42 |
+
def forward(self, x):
|
| 43 |
+
if type(x) == dict:
|
| 44 |
+
if x["audios"] is not None:
|
| 45 |
+
inputs = {ModalityType.AUDIO: load_and_transform_audio_data(x["audios"], device=self.device).half()}
|
| 46 |
+
embeddings = self.vision_tower(inputs)
|
| 47 |
+
audio_embedding = embeddings[ModalityType.AUDIO]
|
| 48 |
+
return audio_embedding.unsqueeze(1)
|
| 49 |
+
else:
|
| 50 |
+
inputs = {ModalityType.VISION: x.to(dtype=self.dtype)}
|
| 51 |
+
embeddings = self.vision_tower(inputs)
|
| 52 |
+
vision_embedding = embeddings[ModalityType.VISION]
|
| 53 |
+
if vision_embedding.ndim == 2:
|
| 54 |
+
return vision_embedding.unsqueeze(1)
|
| 55 |
+
if vision_embedding.shape[1] == 257:
|
| 56 |
+
return vision_embedding[:, 1:]
|
| 57 |
+
raise ValueError(f"Unexpected shape: {vision_embedding.shape}")
|
| 58 |
+
|
| 59 |
+
@property
|
| 60 |
+
def dummy_feature(self):
|
| 61 |
+
return torch.zeros(1, 1024, device=self.device, dtype=self.dtype)
|
| 62 |
+
|
| 63 |
+
@property
|
| 64 |
+
def dtype(self):
|
| 65 |
+
return self.vision_tower.modality_preprocessors.vision.cls_token.dtype
|
| 66 |
+
|
| 67 |
+
@property
|
| 68 |
+
def device(self):
|
| 69 |
+
return self.vision_tower.modality_preprocessors.vision.cls_token.device
|
| 70 |
+
|
| 71 |
+
@property
|
| 72 |
+
def hidden_size(self):
|
| 73 |
+
return 1024
|
之前的代码版本/这一版注意力有问题/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/mlcd_encoder.py
ADDED
|
@@ -0,0 +1,179 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
from llava.utils import rank0_print
|
| 4 |
+
# from transformers import CLIPVisionModel, CLIPImageProcessor, CLIPVisionConfig
|
| 5 |
+
from transformers import CLIPImageProcessor
|
| 6 |
+
from .mlcd.vit_rope2d_hf import MLCDVisionModel, MLCDVisionConfig
|
| 7 |
+
|
| 8 |
+
try:
|
| 9 |
+
from s2wrapper import forward as multiscale_forward
|
| 10 |
+
except:
|
| 11 |
+
pass
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
# class CLIPVisionTower(nn.Module):
|
| 15 |
+
class MLCDVisionTower(nn.Module):
|
| 16 |
+
def __init__(self, vision_tower, args, delay_load=False):
|
| 17 |
+
super().__init__()
|
| 18 |
+
|
| 19 |
+
self.is_loaded = False
|
| 20 |
+
|
| 21 |
+
self.vision_tower_name = vision_tower
|
| 22 |
+
self.select_layer = args.mm_vision_select_layer
|
| 23 |
+
self.select_feature = getattr(args, "mm_vision_select_feature", "patch")
|
| 24 |
+
|
| 25 |
+
if not delay_load:
|
| 26 |
+
rank0_print(f"Loading vision tower: {vision_tower}")
|
| 27 |
+
self.load_model()
|
| 28 |
+
elif getattr(args, "unfreeze_mm_vision_tower", False):
|
| 29 |
+
# TODO: better detector is needed.
|
| 30 |
+
rank0_print(f"The checkpoint seems to contain `vision_tower` weights: `unfreeze_mm_vision_tower`: True.")
|
| 31 |
+
self.load_model()
|
| 32 |
+
elif hasattr(args, "mm_tunable_parts") and "mm_vision_tower" in args.mm_tunable_parts:
|
| 33 |
+
rank0_print(f"The checkpoint seems to contain `vision_tower` weights: `mm_tunable_parts` contains `mm_vision_tower`.")
|
| 34 |
+
self.load_model()
|
| 35 |
+
else:
|
| 36 |
+
# self.cfg_only = CLIPVisionConfig.from_pretrained(self.vision_tower_name)
|
| 37 |
+
self.cfg_only = MLCDVisionConfig.from_pretrained(self.vision_tower_name)
|
| 38 |
+
|
| 39 |
+
def load_model(self, device_map=None):
|
| 40 |
+
if self.is_loaded:
|
| 41 |
+
rank0_print("{} is already loaded, `load_model` called again, skipping.".format(self.vision_tower_name))
|
| 42 |
+
return
|
| 43 |
+
|
| 44 |
+
self.image_processor = CLIPImageProcessor.from_pretrained(self.vision_tower_name)
|
| 45 |
+
# self.vision_tower = CLIPVisionModel.from_pretrained(self.vision_tower_name, device_map=device_map)
|
| 46 |
+
self.vision_tower = MLCDVisionModel.from_pretrained(self.vision_tower_name, device_map=device_map)
|
| 47 |
+
self.vision_tower.requires_grad_(False)
|
| 48 |
+
|
| 49 |
+
self.is_loaded = True
|
| 50 |
+
|
| 51 |
+
def feature_select(self, image_forward_outs):
|
| 52 |
+
select_feature_type = self.select_feature
|
| 53 |
+
|
| 54 |
+
if self.select_feature in ["slicefour_patch", "slicefour_cls_patch"]:
|
| 55 |
+
select_every_k_layer = len(image_forward_outs.hidden_states) // 4
|
| 56 |
+
image_features = torch.cat([image_forward_outs.hidden_states[i] for i in range(select_every_k_layer + self.select_layer, len(image_forward_outs.hidden_states), select_every_k_layer)], dim=-1)
|
| 57 |
+
select_feature_type = select_feature_type.replace("slicefour_", "")
|
| 58 |
+
elif self.select_feature in ["slice_m25811_f6_patch", "slice_m25811_f6_cls_patch"]:
|
| 59 |
+
select_layers = [-2, -5, -8, -11, 6]
|
| 60 |
+
image_features = torch.cat([image_forward_outs.hidden_states[i] for i in select_layers], dim=-1)
|
| 61 |
+
select_feature_type = select_feature_type.replace("slice_m25811_f6_", "")
|
| 62 |
+
else:
|
| 63 |
+
image_features = image_forward_outs.hidden_states[self.select_layer]
|
| 64 |
+
|
| 65 |
+
if select_feature_type == "patch":
|
| 66 |
+
image_features = image_features[:, 1:]
|
| 67 |
+
elif select_feature_type == "cls_patch":
|
| 68 |
+
image_features = image_features
|
| 69 |
+
else:
|
| 70 |
+
raise ValueError(f"Unexpected select feature: {select_feature_type}")
|
| 71 |
+
return image_features
|
| 72 |
+
|
| 73 |
+
def forward(self, images):
|
| 74 |
+
if type(images) is list:
|
| 75 |
+
image_features = []
|
| 76 |
+
for image in images:
|
| 77 |
+
image_forward_out = self.vision_tower(image.to(device=self.device, dtype=self.dtype).unsqueeze(0), output_hidden_states=True)
|
| 78 |
+
image_feature = self.feature_select(image_forward_out).to(image.dtype)
|
| 79 |
+
image_features.append(image_feature)
|
| 80 |
+
else:
|
| 81 |
+
image_forward_outs = self.vision_tower(images.to(device=self.device, dtype=self.dtype), output_hidden_states=True)
|
| 82 |
+
image_features = self.feature_select(image_forward_outs).to(images.dtype)
|
| 83 |
+
|
| 84 |
+
return image_features
|
| 85 |
+
|
| 86 |
+
@property
|
| 87 |
+
def dummy_feature(self):
|
| 88 |
+
return torch.zeros(1, self.hidden_size, device=self.device, dtype=self.dtype)
|
| 89 |
+
|
| 90 |
+
@property
|
| 91 |
+
def dtype(self):
|
| 92 |
+
return self.vision_tower.dtype
|
| 93 |
+
|
| 94 |
+
@property
|
| 95 |
+
def device(self):
|
| 96 |
+
return self.vision_tower.device
|
| 97 |
+
|
| 98 |
+
@property
|
| 99 |
+
def config(self):
|
| 100 |
+
if self.is_loaded:
|
| 101 |
+
return self.vision_tower.config
|
| 102 |
+
else:
|
| 103 |
+
return self.cfg_only
|
| 104 |
+
|
| 105 |
+
@property
|
| 106 |
+
def hidden_size(self):
|
| 107 |
+
_hidden_size = self.config.hidden_size
|
| 108 |
+
if "slicefour" in self.select_feature:
|
| 109 |
+
_hidden_size *= 4
|
| 110 |
+
if "slice_m25811_f6" in self.select_feature:
|
| 111 |
+
_hidden_size *= 5
|
| 112 |
+
return _hidden_size
|
| 113 |
+
|
| 114 |
+
@property
|
| 115 |
+
def num_patches_per_side(self):
|
| 116 |
+
return self.config.image_size // self.config.patch_size
|
| 117 |
+
|
| 118 |
+
@property
|
| 119 |
+
def num_patches(self):
|
| 120 |
+
_num_patches = (self.config.image_size // self.config.patch_size) ** 2
|
| 121 |
+
if "cls_patch" in self.select_feature:
|
| 122 |
+
_num_patches += 1
|
| 123 |
+
return _num_patches
|
| 124 |
+
|
| 125 |
+
@property
|
| 126 |
+
def image_size(self):
|
| 127 |
+
return self.config.image_size
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
# class CLIPVisionTowerS2(CLIPVisionTower):
|
| 131 |
+
class MLCDVisionTowerS2(MLCDVisionTower):
|
| 132 |
+
def __init__(self, vision_tower, args, delay_load=False):
|
| 133 |
+
|
| 134 |
+
self.s2_scales = getattr(args, "s2_scales", "336,672,1008")
|
| 135 |
+
self.s2_scales = list(map(int, self.s2_scales.split(",")))
|
| 136 |
+
self.s2_scales.sort()
|
| 137 |
+
self.s2_split_size = self.s2_scales[0]
|
| 138 |
+
self.s2_image_size = self.s2_scales[-1]
|
| 139 |
+
|
| 140 |
+
super().__init__(vision_tower, args, delay_load)
|
| 141 |
+
|
| 142 |
+
# change resize/crop size in preprocessing to the largest image size in s2_scale
|
| 143 |
+
if not delay_load or getattr(args, "unfreeze_mm_vision_tower", False):
|
| 144 |
+
self.image_processor.size["shortest_edge"] = self.s2_image_size
|
| 145 |
+
self.image_processor.crop_size["height"] = self.image_processor.crop_size["width"] = self.s2_image_size
|
| 146 |
+
|
| 147 |
+
def load_model(self, device_map=None):
|
| 148 |
+
if self.is_loaded:
|
| 149 |
+
rank0_print("{} is already loaded, `load_model` called again, skipping.".format(self.vision_tower_name))
|
| 150 |
+
return
|
| 151 |
+
|
| 152 |
+
self.image_processor = CLIPImageProcessor.from_pretrained(self.vision_tower_name)
|
| 153 |
+
self.vision_tower = MLCDVisionModel.from_pretrained(self.vision_tower_name, device_map=device_map)
|
| 154 |
+
self.vision_tower.requires_grad_(False)
|
| 155 |
+
|
| 156 |
+
self.image_processor.size["shortest_edge"] = self.s2_image_size
|
| 157 |
+
self.image_processor.crop_size["height"] = self.image_processor.crop_size["width"] = self.s2_image_size
|
| 158 |
+
|
| 159 |
+
self.is_loaded = True
|
| 160 |
+
|
| 161 |
+
def forward_feature(self, images):
|
| 162 |
+
image_forward_outs = self.vision_tower(images.to(device=self.device, dtype=self.dtype), output_hidden_states=True)
|
| 163 |
+
image_features = self.feature_select(image_forward_outs).to(images.dtype)
|
| 164 |
+
return image_features
|
| 165 |
+
|
| 166 |
+
def forward(self, images):
|
| 167 |
+
if type(images) is list:
|
| 168 |
+
image_features = []
|
| 169 |
+
for image in images:
|
| 170 |
+
image_feature = multiscale_forward(self.forward_feature, image.unsqueeze(0), img_sizes=self.s2_scales, max_split_size=self.s2_split_size, split_forward=True)
|
| 171 |
+
image_features.append(image_feature)
|
| 172 |
+
else:
|
| 173 |
+
image_features = multiscale_forward(self.forward_feature, images, img_sizes=self.s2_scales, max_split_size=self.s2_split_size, split_forward=True)
|
| 174 |
+
|
| 175 |
+
return image_features
|
| 176 |
+
|
| 177 |
+
@property
|
| 178 |
+
def hidden_size(self):
|
| 179 |
+
return self.config.hidden_size * len(self.s2_scales)
|
之前的代码版本/这一版注意力有问题/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/open_clip_encoder.py
ADDED
|
@@ -0,0 +1,163 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
from transformers import CLIPImageProcessor
|
| 4 |
+
from llava.utils import rank0_print
|
| 5 |
+
|
| 6 |
+
try:
|
| 7 |
+
import open_clip
|
| 8 |
+
import torchvision
|
| 9 |
+
from open_clip.transformer import _expand_token
|
| 10 |
+
except ImportError:
|
| 11 |
+
print("OpenCLIP not installed")
|
| 12 |
+
open_clip = None
|
| 13 |
+
|
| 14 |
+
HIDDEN_SIZE_DICT = {
|
| 15 |
+
"ViT-H-14-378-quickgelu": 1280,
|
| 16 |
+
}
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class OpenCLIPVisionTower(nn.Module):
|
| 20 |
+
def __init__(self, vision_tower, args, delay_load=False):
|
| 21 |
+
super().__init__()
|
| 22 |
+
|
| 23 |
+
self.is_loaded = False
|
| 24 |
+
self.model_name = vision_tower.replace("open_clip_hub:", "")
|
| 25 |
+
self.pretrained = args.vision_tower_pretrained
|
| 26 |
+
self.select_layer = args.mm_vision_select_layer
|
| 27 |
+
self.select_feature = getattr(args, "mm_vision_select_feature", "patch")
|
| 28 |
+
|
| 29 |
+
if not delay_load:
|
| 30 |
+
rank0_print(f"Loading vision tower: {vision_tower}")
|
| 31 |
+
self.load_model()
|
| 32 |
+
elif getattr(args, "unfreeze_mm_vision_tower", False):
|
| 33 |
+
# TODO: better detector is needed.
|
| 34 |
+
rank0_print(f"The checkpoint seems to contain `vision_tower` weights: `unfreeze_mm_vision_tower`: True.")
|
| 35 |
+
self.load_model()
|
| 36 |
+
elif hasattr(args, "mm_tunable_parts") and "mm_vision_tower" in args.mm_tunable_parts:
|
| 37 |
+
rank0_print(f"The checkpoint seems to contain `vision_tower` weights: `mm_tunable_parts` contains `mm_vision_tower`.")
|
| 38 |
+
self.load_model()
|
| 39 |
+
|
| 40 |
+
def load_model(self, device_map="auto"):
|
| 41 |
+
rank0_print(f"Loading OpenCLIP model: {self.model_name}")
|
| 42 |
+
rank0_print(f"Pretrained: {self.pretrained}")
|
| 43 |
+
vision_tower, _, image_processor = open_clip.create_model_and_transforms(model_name=self.model_name, pretrained=self.pretrained, precision="fp32", device="cuda")
|
| 44 |
+
|
| 45 |
+
resize_transform = [t for t in image_processor.transforms if isinstance(t, torchvision.transforms.Resize)][0]
|
| 46 |
+
normalize_transform = [t for t in image_processor.transforms if isinstance(t, torchvision.transforms.Normalize)][0]
|
| 47 |
+
self.resize_transform_size = resize_transform.size # 224 or 384
|
| 48 |
+
self.patch_size = vision_tower.visual.conv1.kernel_size[0] # 14 or 16
|
| 49 |
+
|
| 50 |
+
self.image_processor = CLIPImageProcessor.from_pretrained(
|
| 51 |
+
"openai/clip-vit-large-patch14",
|
| 52 |
+
crop_size=resize_transform.size,
|
| 53 |
+
size={"shortest_edge": resize_transform.size},
|
| 54 |
+
image_mean=list(normalize_transform.mean),
|
| 55 |
+
image_std=list(normalize_transform.std),
|
| 56 |
+
)
|
| 57 |
+
rank0_print(f"Loaded image processor: {self.image_processor}")
|
| 58 |
+
self.vision_tower = vision_tower.visual
|
| 59 |
+
self.vision_tower.requires_grad_(False)
|
| 60 |
+
|
| 61 |
+
self.is_loaded = True
|
| 62 |
+
|
| 63 |
+
def feature_select(self, image_forward_outs):
|
| 64 |
+
image_features = image_forward_outs[self.select_layer]
|
| 65 |
+
if self.select_feature == "patch":
|
| 66 |
+
image_features = image_features[:, 1:]
|
| 67 |
+
elif self.select_feature == "cls_patch":
|
| 68 |
+
image_features = image_features
|
| 69 |
+
elif self.select_feature == "conv_flatten":
|
| 70 |
+
image_features = image_features.flatten(2).transpose(1, 2)
|
| 71 |
+
else:
|
| 72 |
+
raise ValueError(f"Unexpected select feature: {self.select_feature}")
|
| 73 |
+
return image_features
|
| 74 |
+
|
| 75 |
+
def forward_visual(self, x, output_hidden_states=False):
|
| 76 |
+
if hasattr(self.vision_tower, "trunk") and hasattr(self.vision_tower.trunk, "_intermediate_layers"):
|
| 77 |
+
return self.vision_tower.trunk._intermediate_layers(x, abs(self.select_layer))
|
| 78 |
+
else:
|
| 79 |
+
|
| 80 |
+
def forward_openclip(self, x: torch.Tensor):
|
| 81 |
+
features = []
|
| 82 |
+
x = self.conv1(x) # shape = [*, width, grid, grid]
|
| 83 |
+
x = x.reshape(x.shape[0], x.shape[1], -1) # shape = [*, width, grid ** 2]
|
| 84 |
+
x = x.permute(0, 2, 1) # shape = [*, grid ** 2, width]
|
| 85 |
+
|
| 86 |
+
# class embeddings and positional embeddings
|
| 87 |
+
x = torch.cat(
|
| 88 |
+
[_expand_token(self.class_embedding, x.shape[0]).to(x.dtype), x],
|
| 89 |
+
dim=1,
|
| 90 |
+
)
|
| 91 |
+
# shape = [*, grid ** 2 + 1, width]
|
| 92 |
+
x = x + self.positional_embedding.to(x.dtype)
|
| 93 |
+
|
| 94 |
+
x = self.patch_dropout(x)
|
| 95 |
+
x = self.ln_pre(x)
|
| 96 |
+
|
| 97 |
+
x = x.permute(1, 0, 2) # NLD -> LND
|
| 98 |
+
for r in self.transformer.resblocks:
|
| 99 |
+
x = r(x, attn_mask=None)
|
| 100 |
+
features.append(x)
|
| 101 |
+
return features
|
| 102 |
+
|
| 103 |
+
return forward_openclip(self.vision_tower, x)
|
| 104 |
+
|
| 105 |
+
def forward(self, images):
|
| 106 |
+
if type(images) is list:
|
| 107 |
+
image_features = []
|
| 108 |
+
for image in images:
|
| 109 |
+
image_forward_out = self.forward_visual(image.to(self.dtype).unsqueeze(0), output_hidden_states=True)
|
| 110 |
+
image_feature = self.feature_select(image_forward_out).to(image.dtype)
|
| 111 |
+
image_features.append(image_feature)
|
| 112 |
+
else:
|
| 113 |
+
image_forward_outs = self.forward_visual(images.to(self.dtype), output_hidden_states=True)
|
| 114 |
+
image_features = self.feature_select(image_forward_outs).to(images.dtype)
|
| 115 |
+
|
| 116 |
+
return image_features
|
| 117 |
+
|
| 118 |
+
@property
|
| 119 |
+
def dummy_feature(self):
|
| 120 |
+
return torch.zeros(1, self.hidden_size, device=self.device, dtype=self.dtype)
|
| 121 |
+
|
| 122 |
+
@property
|
| 123 |
+
def dtype(self):
|
| 124 |
+
if hasattr(self.vision_tower, "conv1"):
|
| 125 |
+
return self.vision_tower.conv1.weight.dtype
|
| 126 |
+
if hasattr(self.vision_tower, "trunk"):
|
| 127 |
+
return self.vision_tower.trunk.patch_embed.proj.weight.dtype
|
| 128 |
+
raise NotImplementedError
|
| 129 |
+
|
| 130 |
+
@property
|
| 131 |
+
def device(self):
|
| 132 |
+
if hasattr(self.vision_tower, "conv1"):
|
| 133 |
+
return self.vision_tower.conv1.weight.device
|
| 134 |
+
if hasattr(self.vision_tower, "trunk"):
|
| 135 |
+
return self.vision_tower.trunk.patch_embed.proj.weight.device
|
| 136 |
+
raise NotImplementedError
|
| 137 |
+
|
| 138 |
+
@property
|
| 139 |
+
def config(self):
|
| 140 |
+
return None
|
| 141 |
+
|
| 142 |
+
@property
|
| 143 |
+
def hidden_size(self):
|
| 144 |
+
if self.model_name in HIDDEN_SIZE_DICT:
|
| 145 |
+
return HIDDEN_SIZE_DICT[self.model_name]
|
| 146 |
+
else:
|
| 147 |
+
raise NotImplementedError
|
| 148 |
+
|
| 149 |
+
@property
|
| 150 |
+
def num_patches(self):
|
| 151 |
+
image_size = self.resize_transform_size if isinstance(self.resize_transform_size, int) else self.resize_transform_size[0]
|
| 152 |
+
_num_patches = (image_size // self.patch_size) ** 2
|
| 153 |
+
if "cls_patch" in self.select_feature:
|
| 154 |
+
_num_patches += 1
|
| 155 |
+
return _num_patches
|
| 156 |
+
|
| 157 |
+
@property
|
| 158 |
+
def image_size(self):
|
| 159 |
+
return self.resize_transform_size
|
| 160 |
+
|
| 161 |
+
@property
|
| 162 |
+
def num_patches_per_side(self):
|
| 163 |
+
return self.resize_transform_size // self.patch_size
|
之前的代码版本/这一版注意力有问题/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/siglip_encoder.py
ADDED
|
@@ -0,0 +1,620 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
# Adapted from https://huggingface.co/MILVLG/imp-v1-3b/blob/main/vision_encoder.py
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
from typing import Optional, Tuple, Union, Dict
|
| 6 |
+
from dataclasses import dataclass
|
| 7 |
+
from functools import partial, reduce
|
| 8 |
+
from PIL import Image
|
| 9 |
+
import torch
|
| 10 |
+
import torch.utils.checkpoint
|
| 11 |
+
from torch import nn
|
| 12 |
+
import os
|
| 13 |
+
from transformers.image_processing_utils import BatchFeature, get_size_dict
|
| 14 |
+
from transformers.image_transforms import (
|
| 15 |
+
convert_to_rgb,
|
| 16 |
+
normalize,
|
| 17 |
+
rescale,
|
| 18 |
+
resize,
|
| 19 |
+
to_channel_dimension_format,
|
| 20 |
+
)
|
| 21 |
+
from transformers.image_utils import (
|
| 22 |
+
ChannelDimension,
|
| 23 |
+
PILImageResampling,
|
| 24 |
+
to_numpy_array,
|
| 25 |
+
)
|
| 26 |
+
from transformers.activations import ACT2FN
|
| 27 |
+
from transformers.modeling_outputs import BaseModelOutput, BaseModelOutputWithPooling
|
| 28 |
+
from transformers.modeling_utils import PreTrainedModel
|
| 29 |
+
from transformers import PretrainedConfig
|
| 30 |
+
from transformers.utils import ModelOutput
|
| 31 |
+
from llava.utils import rank0_print
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
class SigLipImageProcessor:
|
| 35 |
+
def __init__(self, image_mean=(0.5, 0.5, 0.5), image_std=(0.5, 0.5, 0.5), size=(384, 384), crop_size: Dict[str, int] = None, resample=PILImageResampling.BICUBIC, rescale_factor=1 / 255, data_format=ChannelDimension.FIRST):
|
| 36 |
+
crop_size = crop_size if crop_size is not None else {"height": 384, "width": 384}
|
| 37 |
+
crop_size = get_size_dict(crop_size, default_to_square=True, param_name="crop_size")
|
| 38 |
+
|
| 39 |
+
self.image_mean = image_mean
|
| 40 |
+
self.image_std = image_std
|
| 41 |
+
self.size = size
|
| 42 |
+
self.resample = resample
|
| 43 |
+
self.rescale_factor = rescale_factor
|
| 44 |
+
self.data_format = data_format
|
| 45 |
+
self.crop_size = crop_size
|
| 46 |
+
|
| 47 |
+
def preprocess(self, images, return_tensors):
|
| 48 |
+
if isinstance(images, Image.Image):
|
| 49 |
+
images = [images]
|
| 50 |
+
else:
|
| 51 |
+
# to adapt video data
|
| 52 |
+
images = [to_numpy_array(image) for image in images]
|
| 53 |
+
assert isinstance(images, list)
|
| 54 |
+
|
| 55 |
+
transforms = [
|
| 56 |
+
convert_to_rgb,
|
| 57 |
+
to_numpy_array,
|
| 58 |
+
partial(resize, size=self.size, resample=self.resample, data_format=self.data_format),
|
| 59 |
+
partial(rescale, scale=self.rescale_factor, data_format=self.data_format),
|
| 60 |
+
partial(normalize, mean=self.image_mean, std=self.image_std, data_format=self.data_format),
|
| 61 |
+
partial(to_channel_dimension_format, channel_dim=self.data_format, input_channel_dim=self.data_format),
|
| 62 |
+
]
|
| 63 |
+
|
| 64 |
+
images = reduce(lambda x, f: [*map(f, x)], transforms, images)
|
| 65 |
+
data = {"pixel_values": images}
|
| 66 |
+
|
| 67 |
+
return BatchFeature(data=data, tensor_type=return_tensors)
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
class SigLipVisionConfig(PretrainedConfig):
|
| 71 |
+
model_type = "siglip_vision_model"
|
| 72 |
+
|
| 73 |
+
def __init__(
|
| 74 |
+
self,
|
| 75 |
+
hidden_size=1152,
|
| 76 |
+
image_mean=(0.5, 0.5, 0.5),
|
| 77 |
+
intermediate_size=4304,
|
| 78 |
+
num_hidden_layers=27,
|
| 79 |
+
num_attention_heads=16,
|
| 80 |
+
num_channels=3,
|
| 81 |
+
image_size=384,
|
| 82 |
+
patch_size=14,
|
| 83 |
+
hidden_act="gelu_pytorch_tanh",
|
| 84 |
+
layer_norm_eps=1e-6,
|
| 85 |
+
attention_dropout=0.0,
|
| 86 |
+
**kwargs,
|
| 87 |
+
):
|
| 88 |
+
super().__init__(**kwargs)
|
| 89 |
+
|
| 90 |
+
self.hidden_size = hidden_size
|
| 91 |
+
self.intermediate_size = intermediate_size
|
| 92 |
+
self.num_hidden_layers = num_hidden_layers
|
| 93 |
+
self.num_attention_heads = num_attention_heads
|
| 94 |
+
self.num_channels = num_channels
|
| 95 |
+
self.patch_size = patch_size
|
| 96 |
+
self.image_size = image_size
|
| 97 |
+
self.attention_dropout = attention_dropout
|
| 98 |
+
self.layer_norm_eps = layer_norm_eps
|
| 99 |
+
self.hidden_act = hidden_act
|
| 100 |
+
self.image_mean = image_mean
|
| 101 |
+
|
| 102 |
+
@classmethod
|
| 103 |
+
def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs) -> "PretrainedConfig":
|
| 104 |
+
cls._set_token_in_kwargs(kwargs)
|
| 105 |
+
|
| 106 |
+
config_dict, kwargs = cls.get_config_dict(pretrained_model_name_or_path, **kwargs)
|
| 107 |
+
|
| 108 |
+
# get the vision config dict if we are loading from SigLipConfig
|
| 109 |
+
if config_dict.get("model_type") == "siglip":
|
| 110 |
+
config_dict = config_dict["vision_config"]
|
| 111 |
+
|
| 112 |
+
if "model_type" in config_dict and hasattr(cls, "model_type") and config_dict["model_type"] != cls.model_type:
|
| 113 |
+
print(f"You are using a model of type {config_dict['model_type']} to instantiate a model of type " f"{cls.model_type}. This is not supported for all configurations of models and can yield errors.")
|
| 114 |
+
|
| 115 |
+
return cls.from_dict(config_dict, **kwargs)
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
@dataclass
|
| 119 |
+
# Copied from transformers.models.clip.modeling_clip.CLIPVisionModelOutput with CLIP->SigLip
|
| 120 |
+
class SigLipVisionModelOutput(ModelOutput):
|
| 121 |
+
"""
|
| 122 |
+
Base class for vision model's outputs that also contains image embeddings of the pooling of the last hidden states.
|
| 123 |
+
|
| 124 |
+
Args:
|
| 125 |
+
image_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim)` *optional* returned when model is initialized with `with_projection=True`):
|
| 126 |
+
The image embeddings obtained by applying the projection layer to the pooler_output.
|
| 127 |
+
last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
|
| 128 |
+
Sequence of hidden-states at the output of the last layer of the model.
|
| 129 |
+
hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
| 130 |
+
Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
|
| 131 |
+
one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
|
| 132 |
+
|
| 133 |
+
Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
|
| 134 |
+
attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
| 135 |
+
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
| 136 |
+
sequence_length)`.
|
| 137 |
+
|
| 138 |
+
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
|
| 139 |
+
heads.
|
| 140 |
+
"""
|
| 141 |
+
|
| 142 |
+
image_embeds: Optional[torch.FloatTensor] = None
|
| 143 |
+
last_hidden_state: torch.FloatTensor = None
|
| 144 |
+
hidden_states: Optional[Tuple[torch.FloatTensor]] = None
|
| 145 |
+
attentions: Optional[Tuple[torch.FloatTensor]] = None
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
class SigLipVisionEmbeddings(nn.Module):
|
| 149 |
+
def __init__(self, config: SigLipVisionConfig):
|
| 150 |
+
super().__init__()
|
| 151 |
+
self.config = config
|
| 152 |
+
self.embed_dim = config.hidden_size
|
| 153 |
+
self.image_size = config.image_size
|
| 154 |
+
self.patch_size = config.patch_size
|
| 155 |
+
|
| 156 |
+
self.patch_embedding = nn.Conv2d(
|
| 157 |
+
in_channels=config.num_channels,
|
| 158 |
+
out_channels=self.embed_dim,
|
| 159 |
+
kernel_size=self.patch_size,
|
| 160 |
+
stride=self.patch_size,
|
| 161 |
+
padding="valid",
|
| 162 |
+
)
|
| 163 |
+
|
| 164 |
+
self.num_patches = (self.image_size // self.patch_size) ** 2
|
| 165 |
+
self.num_positions = self.num_patches
|
| 166 |
+
self.position_embedding = nn.Embedding(self.num_positions, self.embed_dim)
|
| 167 |
+
self.register_buffer("position_ids", torch.arange(self.num_positions).expand((1, -1)), persistent=False)
|
| 168 |
+
|
| 169 |
+
def forward(self, pixel_values: torch.FloatTensor) -> torch.Tensor:
|
| 170 |
+
patch_embeds = self.patch_embedding(pixel_values) # shape = [*, width, grid, grid]
|
| 171 |
+
embeddings = patch_embeds.flatten(2).transpose(1, 2)
|
| 172 |
+
|
| 173 |
+
embeddings = embeddings + self.position_embedding(self.position_ids)
|
| 174 |
+
return embeddings
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
class SigLipAttention(nn.Module):
|
| 178 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
| 179 |
+
|
| 180 |
+
# Copied from transformers.models.clip.modeling_clip.CLIPAttention.__init__
|
| 181 |
+
def __init__(self, config):
|
| 182 |
+
super().__init__()
|
| 183 |
+
self.config = config
|
| 184 |
+
self.embed_dim = config.hidden_size
|
| 185 |
+
self.num_heads = config.num_attention_heads
|
| 186 |
+
self.head_dim = self.embed_dim // self.num_heads
|
| 187 |
+
if self.head_dim * self.num_heads != self.embed_dim:
|
| 188 |
+
raise ValueError(f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:" f" {self.num_heads}).")
|
| 189 |
+
self.scale = self.head_dim**-0.5
|
| 190 |
+
self.dropout = config.attention_dropout
|
| 191 |
+
|
| 192 |
+
self.k_proj = nn.Linear(self.embed_dim, self.embed_dim)
|
| 193 |
+
self.v_proj = nn.Linear(self.embed_dim, self.embed_dim)
|
| 194 |
+
self.q_proj = nn.Linear(self.embed_dim, self.embed_dim)
|
| 195 |
+
self.out_proj = nn.Linear(self.embed_dim, self.embed_dim)
|
| 196 |
+
|
| 197 |
+
def forward(
|
| 198 |
+
self,
|
| 199 |
+
hidden_states: torch.Tensor,
|
| 200 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 201 |
+
output_attentions: Optional[bool] = False,
|
| 202 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
| 203 |
+
"""Input shape: Batch x Time x Channel"""
|
| 204 |
+
|
| 205 |
+
batch_size, q_len, _ = hidden_states.size()
|
| 206 |
+
|
| 207 |
+
query_states = self.q_proj(hidden_states)
|
| 208 |
+
key_states = self.k_proj(hidden_states)
|
| 209 |
+
value_states = self.v_proj(hidden_states)
|
| 210 |
+
|
| 211 |
+
query_states = query_states.view(batch_size, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
| 212 |
+
key_states = key_states.view(batch_size, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
| 213 |
+
value_states = value_states.view(batch_size, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
| 214 |
+
|
| 215 |
+
k_v_seq_len = key_states.shape[-2]
|
| 216 |
+
attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) * self.scale
|
| 217 |
+
|
| 218 |
+
if attn_weights.size() != (batch_size, self.num_heads, q_len, k_v_seq_len):
|
| 219 |
+
raise ValueError(f"Attention weights should be of size {(batch_size, self.num_heads, q_len, k_v_seq_len)}, but is" f" {attn_weights.size()}")
|
| 220 |
+
|
| 221 |
+
if attention_mask is not None:
|
| 222 |
+
if attention_mask.size() != (batch_size, 1, q_len, k_v_seq_len):
|
| 223 |
+
raise ValueError(f"Attention mask should be of size {(batch_size, 1, q_len, k_v_seq_len)}, but is {attention_mask.size()}")
|
| 224 |
+
attn_weights = attn_weights + attention_mask
|
| 225 |
+
|
| 226 |
+
# upcast attention to fp32
|
| 227 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
|
| 228 |
+
attn_weights = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training)
|
| 229 |
+
attn_output = torch.matmul(attn_weights, value_states)
|
| 230 |
+
|
| 231 |
+
if attn_output.size() != (batch_size, self.num_heads, q_len, self.head_dim):
|
| 232 |
+
raise ValueError(f"`attn_output` should be of size {(batch_size, self.num_heads, q_len, self.head_dim)}, but is" f" {attn_output.size()}")
|
| 233 |
+
|
| 234 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
| 235 |
+
attn_output = attn_output.reshape(batch_size, q_len, self.embed_dim)
|
| 236 |
+
|
| 237 |
+
attn_output = self.out_proj(attn_output)
|
| 238 |
+
|
| 239 |
+
return attn_output, attn_weights
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
# Copied from transformers.models.clip.modeling_clip.CLIPMLP with CLIP->SigLip
|
| 243 |
+
class SigLipMLP(nn.Module):
|
| 244 |
+
def __init__(self, config):
|
| 245 |
+
super().__init__()
|
| 246 |
+
self.config = config
|
| 247 |
+
self.activation_fn = ACT2FN[config.hidden_act]
|
| 248 |
+
self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
|
| 249 |
+
self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
|
| 250 |
+
|
| 251 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 252 |
+
hidden_states = self.fc1(hidden_states)
|
| 253 |
+
hidden_states = self.activation_fn(hidden_states)
|
| 254 |
+
hidden_states = self.fc2(hidden_states)
|
| 255 |
+
return hidden_states
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
# Copied from transformers.models.clip.modeling_clip.CLIPEncoderLayer with CLIP->SigLip
|
| 259 |
+
class SigLipEncoderLayer(nn.Module):
|
| 260 |
+
def __init__(self, config: SigLipVisionConfig):
|
| 261 |
+
super().__init__()
|
| 262 |
+
self.embed_dim = config.hidden_size
|
| 263 |
+
self.self_attn = SigLipAttention(config)
|
| 264 |
+
self.layer_norm1 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
|
| 265 |
+
self.mlp = SigLipMLP(config)
|
| 266 |
+
self.layer_norm2 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
|
| 267 |
+
|
| 268 |
+
# Ignore copy
|
| 269 |
+
def forward(
|
| 270 |
+
self,
|
| 271 |
+
hidden_states: torch.Tensor,
|
| 272 |
+
attention_mask: torch.Tensor,
|
| 273 |
+
output_attentions: Optional[bool] = False,
|
| 274 |
+
) -> Tuple[torch.FloatTensor]:
|
| 275 |
+
"""
|
| 276 |
+
Args:
|
| 277 |
+
hidden_states (`torch.FloatTensor`):
|
| 278 |
+
Input to the layer of shape `(batch, seq_len, embed_dim)`.
|
| 279 |
+
attention_mask (`torch.FloatTensor`):
|
| 280 |
+
Attention mask of shape `(batch, 1, q_len, k_v_seq_len)` where padding elements are indicated by very large negative values.
|
| 281 |
+
output_attentions (`bool`, *optional*, defaults to `False`):
|
| 282 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
| 283 |
+
returned tensors for more detail.
|
| 284 |
+
"""
|
| 285 |
+
residual = hidden_states
|
| 286 |
+
|
| 287 |
+
hidden_states = self.layer_norm1(hidden_states)
|
| 288 |
+
hidden_states, attn_weights = self.self_attn(
|
| 289 |
+
hidden_states=hidden_states,
|
| 290 |
+
attention_mask=attention_mask,
|
| 291 |
+
output_attentions=output_attentions,
|
| 292 |
+
)
|
| 293 |
+
hidden_states = residual + hidden_states
|
| 294 |
+
|
| 295 |
+
residual = hidden_states
|
| 296 |
+
hidden_states = self.layer_norm2(hidden_states)
|
| 297 |
+
hidden_states = self.mlp(hidden_states)
|
| 298 |
+
hidden_states = residual + hidden_states
|
| 299 |
+
|
| 300 |
+
outputs = (hidden_states,)
|
| 301 |
+
|
| 302 |
+
if output_attentions:
|
| 303 |
+
outputs += (attn_weights,)
|
| 304 |
+
|
| 305 |
+
return outputs
|
| 306 |
+
|
| 307 |
+
|
| 308 |
+
class SigLipPreTrainedModel(PreTrainedModel):
|
| 309 |
+
"""
|
| 310 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
| 311 |
+
models.
|
| 312 |
+
"""
|
| 313 |
+
|
| 314 |
+
config_class = SigLipVisionConfig
|
| 315 |
+
base_model_prefix = "siglip"
|
| 316 |
+
supports_gradient_checkpointing = True
|
| 317 |
+
|
| 318 |
+
def _init_weights(self, module):
|
| 319 |
+
"""Initialize the weights"""
|
| 320 |
+
pass
|
| 321 |
+
|
| 322 |
+
|
| 323 |
+
# Copied from transformers.models.clip.modeling_clip.CLIPEncoder with CLIP->SigLip
|
| 324 |
+
class SigLipEncoder(nn.Module):
|
| 325 |
+
"""
|
| 326 |
+
Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a
|
| 327 |
+
[`SigLipEncoderLayer`].
|
| 328 |
+
|
| 329 |
+
Args:
|
| 330 |
+
config: SigLipVisionConfig
|
| 331 |
+
"""
|
| 332 |
+
|
| 333 |
+
def __init__(self, config: SigLipVisionConfig):
|
| 334 |
+
super().__init__()
|
| 335 |
+
self.config = config
|
| 336 |
+
self.layers = nn.ModuleList([SigLipEncoderLayer(config) for _ in range(config.num_hidden_layers)])
|
| 337 |
+
self.gradient_checkpointing = False
|
| 338 |
+
|
| 339 |
+
# Ignore copy
|
| 340 |
+
def forward(
|
| 341 |
+
self,
|
| 342 |
+
inputs_embeds,
|
| 343 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 344 |
+
output_attentions: Optional[bool] = None,
|
| 345 |
+
output_hidden_states: Optional[bool] = None,
|
| 346 |
+
return_dict: Optional[bool] = None,
|
| 347 |
+
) -> Union[Tuple, BaseModelOutput]:
|
| 348 |
+
r"""
|
| 349 |
+
Args:
|
| 350 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
|
| 351 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
|
| 352 |
+
This is useful if you want more control over how to convert `input_ids` indices into associated vectors
|
| 353 |
+
than the model's internal embedding lookup matrix.
|
| 354 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 355 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 356 |
+
|
| 357 |
+
- 1 for tokens that are **not masked**,
|
| 358 |
+
- 0 for tokens that are **masked**.
|
| 359 |
+
|
| 360 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 361 |
+
output_attentions (`bool`, *optional*):
|
| 362 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
| 363 |
+
returned tensors for more detail.
|
| 364 |
+
output_hidden_states (`bool`, *optional*):
|
| 365 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
|
| 366 |
+
for more detail.
|
| 367 |
+
return_dict (`bool`, *optional*):
|
| 368 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 369 |
+
"""
|
| 370 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 371 |
+
output_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 372 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 373 |
+
|
| 374 |
+
encoder_states = () if output_hidden_states else None
|
| 375 |
+
all_attentions = () if output_attentions else None
|
| 376 |
+
|
| 377 |
+
hidden_states = inputs_embeds
|
| 378 |
+
for encoder_layer in self.layers:
|
| 379 |
+
if output_hidden_states:
|
| 380 |
+
encoder_states = encoder_states + (hidden_states,)
|
| 381 |
+
if self.gradient_checkpointing and self.training:
|
| 382 |
+
layer_outputs = self._gradient_checkpointing_func(
|
| 383 |
+
encoder_layer.__call__,
|
| 384 |
+
hidden_states,
|
| 385 |
+
attention_mask,
|
| 386 |
+
output_attentions,
|
| 387 |
+
)
|
| 388 |
+
else:
|
| 389 |
+
layer_outputs = encoder_layer(
|
| 390 |
+
hidden_states,
|
| 391 |
+
attention_mask,
|
| 392 |
+
output_attentions=output_attentions,
|
| 393 |
+
)
|
| 394 |
+
|
| 395 |
+
hidden_states = layer_outputs[0]
|
| 396 |
+
|
| 397 |
+
if output_attentions:
|
| 398 |
+
all_attentions = all_attentions + (layer_outputs[1],)
|
| 399 |
+
|
| 400 |
+
if output_hidden_states:
|
| 401 |
+
encoder_states = encoder_states + (hidden_states,)
|
| 402 |
+
|
| 403 |
+
if not return_dict:
|
| 404 |
+
return tuple(v for v in [hidden_states, encoder_states, all_attentions] if v is not None)
|
| 405 |
+
return BaseModelOutput(last_hidden_state=hidden_states, hidden_states=encoder_states, attentions=all_attentions)
|
| 406 |
+
|
| 407 |
+
|
| 408 |
+
class SigLipVisionTransformer(nn.Module):
|
| 409 |
+
def __init__(self, config: SigLipVisionConfig):
|
| 410 |
+
super().__init__()
|
| 411 |
+
self.config = config
|
| 412 |
+
embed_dim = config.hidden_size
|
| 413 |
+
|
| 414 |
+
self.embeddings = SigLipVisionEmbeddings(config)
|
| 415 |
+
self.encoder = SigLipEncoder(config)
|
| 416 |
+
self.post_layernorm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
|
| 417 |
+
self.head = SigLipMultiheadAttentionPoolingHead(config)
|
| 418 |
+
|
| 419 |
+
def forward(
|
| 420 |
+
self,
|
| 421 |
+
pixel_values,
|
| 422 |
+
output_attentions: Optional[bool] = None,
|
| 423 |
+
output_hidden_states: Optional[bool] = None,
|
| 424 |
+
return_dict: Optional[bool] = None,
|
| 425 |
+
) -> Union[Tuple, BaseModelOutputWithPooling]:
|
| 426 |
+
r"""
|
| 427 |
+
Returns:
|
| 428 |
+
|
| 429 |
+
"""
|
| 430 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 431 |
+
output_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 432 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 433 |
+
|
| 434 |
+
hidden_states = self.embeddings(pixel_values)
|
| 435 |
+
|
| 436 |
+
encoder_outputs = self.encoder(
|
| 437 |
+
inputs_embeds=hidden_states,
|
| 438 |
+
output_attentions=output_attentions,
|
| 439 |
+
output_hidden_states=output_hidden_states,
|
| 440 |
+
return_dict=return_dict,
|
| 441 |
+
)
|
| 442 |
+
|
| 443 |
+
last_hidden_state = encoder_outputs[0]
|
| 444 |
+
last_hidden_state = self.post_layernorm(last_hidden_state)
|
| 445 |
+
|
| 446 |
+
pooled_output = self.head(last_hidden_state)
|
| 447 |
+
|
| 448 |
+
if not return_dict:
|
| 449 |
+
return (last_hidden_state, pooled_output) + encoder_outputs[1:]
|
| 450 |
+
|
| 451 |
+
return BaseModelOutputWithPooling(
|
| 452 |
+
last_hidden_state=last_hidden_state,
|
| 453 |
+
pooler_output=pooled_output,
|
| 454 |
+
hidden_states=encoder_outputs.hidden_states,
|
| 455 |
+
attentions=encoder_outputs.attentions,
|
| 456 |
+
)
|
| 457 |
+
|
| 458 |
+
|
| 459 |
+
class SigLipMultiheadAttentionPoolingHead(nn.Module):
|
| 460 |
+
"""Multihead Attention Pooling."""
|
| 461 |
+
|
| 462 |
+
def __init__(self, config: SigLipVisionConfig):
|
| 463 |
+
super().__init__()
|
| 464 |
+
|
| 465 |
+
self.probe = nn.Parameter(torch.randn(1, 1, config.hidden_size))
|
| 466 |
+
self.attention = torch.nn.MultiheadAttention(config.hidden_size, config.num_attention_heads, batch_first=True)
|
| 467 |
+
self.layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 468 |
+
self.mlp = SigLipMLP(config)
|
| 469 |
+
|
| 470 |
+
def forward(self, hidden_state):
|
| 471 |
+
batch_size = hidden_state.shape[0]
|
| 472 |
+
probe = self.probe.repeat(batch_size, 1, 1)
|
| 473 |
+
|
| 474 |
+
hidden_state = self.attention(probe, hidden_state, hidden_state)[0]
|
| 475 |
+
|
| 476 |
+
residual = hidden_state
|
| 477 |
+
hidden_state = self.layernorm(hidden_state)
|
| 478 |
+
hidden_state = residual + self.mlp(hidden_state)
|
| 479 |
+
|
| 480 |
+
return hidden_state[:, 0]
|
| 481 |
+
|
| 482 |
+
|
| 483 |
+
class SigLipVisionModel(SigLipPreTrainedModel):
|
| 484 |
+
config_class = SigLipVisionConfig
|
| 485 |
+
main_input_name = "pixel_values"
|
| 486 |
+
_no_split_modules = ["SigLipEncoderLayer"]
|
| 487 |
+
|
| 488 |
+
def __init__(self, config: SigLipVisionConfig):
|
| 489 |
+
super().__init__(config)
|
| 490 |
+
|
| 491 |
+
self.vision_model = SigLipVisionTransformer(config)
|
| 492 |
+
|
| 493 |
+
# Initialize weights and apply final processing
|
| 494 |
+
self.post_init()
|
| 495 |
+
|
| 496 |
+
def get_input_embeddings(self) -> nn.Module:
|
| 497 |
+
return self.vision_model.embeddings.patch_embedding
|
| 498 |
+
|
| 499 |
+
def forward(
|
| 500 |
+
self,
|
| 501 |
+
pixel_values,
|
| 502 |
+
output_attentions: Optional[bool] = None,
|
| 503 |
+
output_hidden_states: Optional[bool] = None,
|
| 504 |
+
return_dict: Optional[bool] = None,
|
| 505 |
+
) -> Union[Tuple, BaseModelOutputWithPooling]:
|
| 506 |
+
r"""
|
| 507 |
+
Returns:
|
| 508 |
+
|
| 509 |
+
Examples:
|
| 510 |
+
|
| 511 |
+
```python
|
| 512 |
+
>>> from PIL import Image
|
| 513 |
+
>>> import requests
|
| 514 |
+
>>> from transformers import AutoProcessor, SigLipVisionModel
|
| 515 |
+
|
| 516 |
+
>>> model = SigLipVisionModel.from_pretrained("google/siglip-base-patch16-224")
|
| 517 |
+
>>> processor = AutoProcessor.from_pretrained("google/siglip-base-patch16-224")
|
| 518 |
+
|
| 519 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 520 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
| 521 |
+
|
| 522 |
+
>>> inputs = processor(images=image, return_tensors="pt")
|
| 523 |
+
|
| 524 |
+
>>> outputs = model(**inputs)
|
| 525 |
+
>>> last_hidden_state = outputs.last_hidden_state
|
| 526 |
+
>>> pooled_output = outputs.pooler_output # pooled features
|
| 527 |
+
```"""
|
| 528 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 529 |
+
|
| 530 |
+
return self.vision_model(
|
| 531 |
+
pixel_values=pixel_values,
|
| 532 |
+
output_attentions=output_attentions,
|
| 533 |
+
output_hidden_states=output_hidden_states,
|
| 534 |
+
return_dict=return_dict,
|
| 535 |
+
)
|
| 536 |
+
|
| 537 |
+
|
| 538 |
+
class SigLipVisionTower(nn.Module):
|
| 539 |
+
def __init__(self, vision_tower, vision_tower_cfg, delay_load=False):
|
| 540 |
+
super().__init__()
|
| 541 |
+
|
| 542 |
+
self.is_loaded = False
|
| 543 |
+
|
| 544 |
+
self.config = SigLipVisionConfig()
|
| 545 |
+
|
| 546 |
+
self.vision_tower_name = vision_tower
|
| 547 |
+
|
| 548 |
+
self.image_processor = SigLipImageProcessor()
|
| 549 |
+
|
| 550 |
+
if not delay_load:
|
| 551 |
+
rank0_print(f"Loading vision tower: {vision_tower}")
|
| 552 |
+
self.load_model()
|
| 553 |
+
elif getattr(vision_tower_cfg, "unfreeze_mm_vision_tower", False):
|
| 554 |
+
# TODO: better detector is needed.
|
| 555 |
+
rank0_print(f"The checkpoint seems to contain `vision_tower` weights: `unfreeze_mm_vision_tower`: True.")
|
| 556 |
+
self.load_model()
|
| 557 |
+
elif hasattr(vision_tower_cfg, "mm_tunable_parts") and "mm_vision_tower" in vision_tower_cfg.mm_tunable_parts:
|
| 558 |
+
rank0_print(f"The checkpoint seems to contain `vision_tower` weights: `mm_tunable_parts` contains `mm_vision_tower`.")
|
| 559 |
+
self.load_model()
|
| 560 |
+
else:
|
| 561 |
+
self.cfg_only = self.config
|
| 562 |
+
|
| 563 |
+
def load_model(self, device_map=None):
|
| 564 |
+
if self.is_loaded:
|
| 565 |
+
rank0_print("{} is already loaded, `load_model` called again, skipping.".format(self.vision_tower_name))
|
| 566 |
+
return
|
| 567 |
+
|
| 568 |
+
self.vision_tower = SigLipVisionModel.from_pretrained(self.vision_tower_name, device_map=device_map)
|
| 569 |
+
|
| 570 |
+
del self.vision_tower.vision_model.encoder.layers[-1:]
|
| 571 |
+
self.vision_tower.vision_model.head = nn.Identity()
|
| 572 |
+
self.vision_tower.requires_grad_(False)
|
| 573 |
+
|
| 574 |
+
self.is_loaded = True
|
| 575 |
+
|
| 576 |
+
def forward(self, images):
|
| 577 |
+
if type(images) is list:
|
| 578 |
+
image_features = []
|
| 579 |
+
for image in images:
|
| 580 |
+
image_forward_out = self.vision_tower(image.to(device=self.device, dtype=self.dtype).unsqueeze(0), output_hidden_states=True)
|
| 581 |
+
image_feature = image_forward_out.hidden_states[-1].to(image.dtype)
|
| 582 |
+
assert image_features.shape[-2] == 729
|
| 583 |
+
image_features.append(image_feature)
|
| 584 |
+
else:
|
| 585 |
+
image_forward_outs = self.vision_tower(images.to(device=self.device, dtype=self.dtype), output_hidden_states=True)
|
| 586 |
+
image_features = image_forward_outs.hidden_states[-1].to(images.dtype)
|
| 587 |
+
assert image_features.shape[-2] == 729
|
| 588 |
+
|
| 589 |
+
return image_features
|
| 590 |
+
|
| 591 |
+
@property
|
| 592 |
+
def dummy_feature(self):
|
| 593 |
+
return torch.zeros(1, self.hidden_size, device=self.device, dtype=self.dtype)
|
| 594 |
+
|
| 595 |
+
@property
|
| 596 |
+
def dtype(self):
|
| 597 |
+
for p in self.vision_tower.parameters():
|
| 598 |
+
return p.dtype
|
| 599 |
+
|
| 600 |
+
@property
|
| 601 |
+
def device(self):
|
| 602 |
+
for p in self.vision_tower.parameters():
|
| 603 |
+
return p.device
|
| 604 |
+
|
| 605 |
+
@property
|
| 606 |
+
def hidden_size(self):
|
| 607 |
+
return self.config.hidden_size
|
| 608 |
+
|
| 609 |
+
@property
|
| 610 |
+
def num_patches(self):
|
| 611 |
+
return (self.config.image_size // self.config.patch_size) ** 2
|
| 612 |
+
|
| 613 |
+
@property
|
| 614 |
+
def num_patches_per_side(self):
|
| 615 |
+
return self.config.image_size // self.config.patch_size
|
| 616 |
+
# return self.model_config["vision_cfg"]["image_size"] // self.model_config["vision_cfg"]["patch_size"]
|
| 617 |
+
|
| 618 |
+
@property
|
| 619 |
+
def image_size(self):
|
| 620 |
+
return self.config.image_size
|
之前的代码版本/这一版注意力有问题/MedEvalKit/LLaVA-NeXT/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)
|