Add files using upload-large-folder tool
Browse files- spatial-model/VLM-3R/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/model_configs/EVA01-CLIP-g-14-plus.json +24 -0
- spatial-model/VLM-3R/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/model_configs/EVA01-CLIP-g-14.json +24 -0
- spatial-model/VLM-3R/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/model_configs/EVA02-CLIP-L-14.json +29 -0
- spatial-model/VLM-3R/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/model_configs/EVA02-CLIP-bigE-14.json +25 -0
- spatial-model/VLM-3R/llava/model/multimodal_encoder/eva_clip/eva_clip_encoder.py +74 -0
- spatial-model/VLM-3R/llava/model/multimodal_encoder/eva_clip/eva_clip_processors.py +72 -0
- spatial-model/VLM-3R/llava/model/multimodal_encoder/eva_clip/eva_vit.py +856 -0
- spatial-model/VLM-3R/llava/model/multimodal_encoder/eva_clip/factory.py +60 -0
- spatial-model/VLM-3R/llava/model/multimodal_encoder/mlcd/vit_rope2d_hf.py +452 -0
- spatial-model/VLM-3R/scripts/archived/convert_gqa_for_eval.py +18 -0
- spatial-model/VLM-3R/scripts/archived/convert_mmvet_for_eval.py +18 -0
- spatial-model/VLM-3R/scripts/archived/convert_sqa_to_llava.py +88 -0
- spatial-model/VLM-3R/scripts/archived/convert_sqa_to_llava_base_prompt.py +298 -0
- spatial-model/VLM-3R/scripts/archived/convert_vqav2_for_submission.py +50 -0
- spatial-model/VLM-3R/scripts/archived/finetune_lora.sh +47 -0
- spatial-model/VLM-3R/scripts/archived/finetune_mixtral_1.5.sh +96 -0
- spatial-model/VLM-3R/scripts/archived/finetune_mixtral_1.6_336px_anyres_freeze_vision.sh +97 -0
- spatial-model/VLM-3R/scripts/archived/finetune_mixtral_copy.sh +96 -0
- spatial-model/VLM-3R/scripts/archived/finetune_qlora.sh +48 -0
- spatial-model/VLM-3R/scripts/archived/pretrain.sh +43 -0
spatial-model/VLM-3R/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/model_configs/EVA01-CLIP-g-14-plus.json
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"embed_dim": 1024,
|
| 3 |
+
"vision_cfg": {
|
| 4 |
+
"image_size": 224,
|
| 5 |
+
"layers": 40,
|
| 6 |
+
"width": 1408,
|
| 7 |
+
"head_width": 88,
|
| 8 |
+
"mlp_ratio": 4.3637,
|
| 9 |
+
"patch_size": 14,
|
| 10 |
+
"eva_model_name": "eva-clip-g-14-x",
|
| 11 |
+
"drop_path_rate": 0,
|
| 12 |
+
"xattn": true,
|
| 13 |
+
"fusedLN": true
|
| 14 |
+
},
|
| 15 |
+
"text_cfg": {
|
| 16 |
+
"context_length": 77,
|
| 17 |
+
"vocab_size": 49408,
|
| 18 |
+
"width": 1024,
|
| 19 |
+
"heads": 16,
|
| 20 |
+
"layers": 24,
|
| 21 |
+
"xattn": false,
|
| 22 |
+
"fusedLN": true
|
| 23 |
+
}
|
| 24 |
+
}
|
spatial-model/VLM-3R/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/model_configs/EVA01-CLIP-g-14.json
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"embed_dim": 1024,
|
| 3 |
+
"vision_cfg": {
|
| 4 |
+
"image_size": 224,
|
| 5 |
+
"layers": 40,
|
| 6 |
+
"width": 1408,
|
| 7 |
+
"head_width": 88,
|
| 8 |
+
"mlp_ratio": 4.3637,
|
| 9 |
+
"patch_size": 14,
|
| 10 |
+
"eva_model_name": "eva-clip-g-14-x",
|
| 11 |
+
"drop_path_rate": 0.4,
|
| 12 |
+
"xattn": true,
|
| 13 |
+
"fusedLN": true
|
| 14 |
+
},
|
| 15 |
+
"text_cfg": {
|
| 16 |
+
"context_length": 77,
|
| 17 |
+
"vocab_size": 49408,
|
| 18 |
+
"width": 768,
|
| 19 |
+
"heads": 12,
|
| 20 |
+
"layers": 12,
|
| 21 |
+
"xattn": false,
|
| 22 |
+
"fusedLN": true
|
| 23 |
+
}
|
| 24 |
+
}
|
spatial-model/VLM-3R/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/model_configs/EVA02-CLIP-L-14.json
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"embed_dim": 768,
|
| 3 |
+
"vision_cfg": {
|
| 4 |
+
"image_size": 224,
|
| 5 |
+
"layers": 24,
|
| 6 |
+
"width": 1024,
|
| 7 |
+
"drop_path_rate": 0,
|
| 8 |
+
"head_width": 64,
|
| 9 |
+
"mlp_ratio": 2.6667,
|
| 10 |
+
"patch_size": 14,
|
| 11 |
+
"eva_model_name": "eva-clip-l-14",
|
| 12 |
+
"xattn": true,
|
| 13 |
+
"fusedLN": true,
|
| 14 |
+
"rope": true,
|
| 15 |
+
"pt_hw_seq_len": 16,
|
| 16 |
+
"intp_freq": true,
|
| 17 |
+
"naiveswiglu": true,
|
| 18 |
+
"subln": true
|
| 19 |
+
},
|
| 20 |
+
"text_cfg": {
|
| 21 |
+
"context_length": 77,
|
| 22 |
+
"vocab_size": 49408,
|
| 23 |
+
"width": 768,
|
| 24 |
+
"heads": 12,
|
| 25 |
+
"layers": 12,
|
| 26 |
+
"xattn": false,
|
| 27 |
+
"fusedLN": true
|
| 28 |
+
}
|
| 29 |
+
}
|
spatial-model/VLM-3R/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/model_configs/EVA02-CLIP-bigE-14.json
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"embed_dim": 1024,
|
| 3 |
+
"vision_cfg": {
|
| 4 |
+
"image_size": 224,
|
| 5 |
+
"layers": 64,
|
| 6 |
+
"width": 1792,
|
| 7 |
+
"head_width": 112,
|
| 8 |
+
"mlp_ratio": 8.571428571428571,
|
| 9 |
+
"patch_size": 14,
|
| 10 |
+
"eva_model_name": "eva-clip-4b-14-x",
|
| 11 |
+
"drop_path_rate": 0,
|
| 12 |
+
"xattn": true,
|
| 13 |
+
"postnorm": true,
|
| 14 |
+
"fusedLN": true
|
| 15 |
+
},
|
| 16 |
+
"text_cfg": {
|
| 17 |
+
"context_length": 77,
|
| 18 |
+
"vocab_size": 49408,
|
| 19 |
+
"width": 1024,
|
| 20 |
+
"heads": 16,
|
| 21 |
+
"layers": 24,
|
| 22 |
+
"xattn": false,
|
| 23 |
+
"fusedLN": true
|
| 24 |
+
}
|
| 25 |
+
}
|
spatial-model/VLM-3R/llava/model/multimodal_encoder/eva_clip/eva_clip_encoder.py
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
|
| 4 |
+
from .eva_clip_processors import EvaClipImageTrainProcessor
|
| 5 |
+
from .eva_vit import EVAEncoderWrapper
|
| 6 |
+
from .factory import list_models, add_model_config, get_model_config
|
| 7 |
+
|
| 8 |
+
from llava.utils import rank0_print
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class EvaClipVisionTower(nn.Module):
|
| 12 |
+
def __init__(self, vision_tower, args, delay_load=False):
|
| 13 |
+
super().__init__()
|
| 14 |
+
|
| 15 |
+
self.is_loaded = False
|
| 16 |
+
self.vision_tower_name = vision_tower
|
| 17 |
+
self.vision_tower_pretrained = args.vision_tower_pretrained
|
| 18 |
+
self.config = get_model_config(vision_tower)
|
| 19 |
+
|
| 20 |
+
if not delay_load:
|
| 21 |
+
rank0_print(f"Loading EVA ViT: {self.vision_tower_name}")
|
| 22 |
+
self.load_model()
|
| 23 |
+
elif getattr(args, "unfreeze_mm_vision_tower", False):
|
| 24 |
+
# TODO: better detector is needed.
|
| 25 |
+
rank0_print(f"The checkpoint seems to contain `vision_tower` weights: `unfreeze_mm_vision_tower`: True.")
|
| 26 |
+
self.load_model()
|
| 27 |
+
elif hasattr(args, "mm_tunable_parts") and "mm_vision_tower" in args.mm_tunable_parts:
|
| 28 |
+
rank0_print(f"The checkpoint seems to contain `vision_tower` weights: `mm_tunable_parts` contains `mm_vision_tower`.")
|
| 29 |
+
self.load_model()
|
| 30 |
+
else:
|
| 31 |
+
self.cfg_only = self.config
|
| 32 |
+
|
| 33 |
+
def load_model(self, device_map=None):
|
| 34 |
+
rank0_print(f"Pretrained: {self.vision_tower_pretrained}")
|
| 35 |
+
self.image_processor = EvaClipImageTrainProcessor(self.config["vision_cfg"]["image_size"])
|
| 36 |
+
self.vision_tower = EVAEncoderWrapper(self.vision_tower_pretrained, self.config)
|
| 37 |
+
rank0_print(f"Loaded image processor: {self.image_processor}")
|
| 38 |
+
self.vision_tower.requires_grad_(False)
|
| 39 |
+
self.is_loaded = True
|
| 40 |
+
|
| 41 |
+
def forward(self, images):
|
| 42 |
+
if type(images) is list:
|
| 43 |
+
image_features = []
|
| 44 |
+
for image in images:
|
| 45 |
+
image_feature = self.vision_tower(image.to(device=self.device, dtype=self.dtype).unsqueeze(0)).to(image.dtype)
|
| 46 |
+
image_features.append(image_feature)
|
| 47 |
+
else:
|
| 48 |
+
image_features = self.vision_tower(images.to(device=self.device, dtype=self.dtype)).to(images.dtype)
|
| 49 |
+
|
| 50 |
+
return image_features
|
| 51 |
+
|
| 52 |
+
@property
|
| 53 |
+
def dtype(self):
|
| 54 |
+
return self.vision_tower.dtype
|
| 55 |
+
|
| 56 |
+
@property
|
| 57 |
+
def device(self):
|
| 58 |
+
return self.vision_tower.device
|
| 59 |
+
|
| 60 |
+
@property
|
| 61 |
+
def hidden_size(self):
|
| 62 |
+
return self.config["vision_cfg"]["width"]
|
| 63 |
+
|
| 64 |
+
@property
|
| 65 |
+
def num_patches(self):
|
| 66 |
+
return (self.config["vision_cfg"]["image_size"] // self.config["vision_cfg"]["patch_size"]) ** 2
|
| 67 |
+
|
| 68 |
+
@property
|
| 69 |
+
def num_patches_per_side(self):
|
| 70 |
+
return self.config["vision_cfg"]["image_size"] // self.config["vision_cfg"]["patch_size"]
|
| 71 |
+
|
| 72 |
+
@property
|
| 73 |
+
def image_size(self):
|
| 74 |
+
return self.config["vision_cfg"]["image_size"]
|
spatial-model/VLM-3R/llava/model/multimodal_encoder/eva_clip/eva_clip_processors.py
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
# Adapted from https://github.com/baaivision/EVA/tree/master/EVA-CLIP
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
from torchvision import transforms
|
| 6 |
+
from torchvision.transforms.functional import InterpolationMode
|
| 7 |
+
from transformers.image_processing_utils import BatchFeature
|
| 8 |
+
from PIL import Image
|
| 9 |
+
from transformers.image_transforms import convert_to_rgb
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class BaseProcessor:
|
| 13 |
+
def __init__(self):
|
| 14 |
+
self.transform = lambda x: x
|
| 15 |
+
return
|
| 16 |
+
|
| 17 |
+
def __call__(self, item):
|
| 18 |
+
return self.transform(item)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class EvaClipImageBaseProcessor(BaseProcessor):
|
| 22 |
+
def __init__(self, mean=None, std=None):
|
| 23 |
+
self.mean = (0.48145466, 0.4578275, 0.40821073) if mean is None else mean
|
| 24 |
+
self.std = (0.26862954, 0.26130258, 0.27577711) if std is None else std
|
| 25 |
+
|
| 26 |
+
self.normalize = transforms.Normalize(self.mean, self.std)
|
| 27 |
+
|
| 28 |
+
@property
|
| 29 |
+
def image_mean(self):
|
| 30 |
+
return self.mean
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class EvaClipImageTrainProcessor(EvaClipImageBaseProcessor):
|
| 34 |
+
def __init__(self, image_size=224, mean=None, std=None, min_scale=0.5, max_scale=1.0):
|
| 35 |
+
super().__init__(mean=mean, std=std)
|
| 36 |
+
|
| 37 |
+
self.transform = transforms.Compose(
|
| 38 |
+
[
|
| 39 |
+
convert_to_rgb,
|
| 40 |
+
transforms.Resize(
|
| 41 |
+
image_size,
|
| 42 |
+
interpolation=InterpolationMode.BICUBIC,
|
| 43 |
+
),
|
| 44 |
+
transforms.CenterCrop(image_size),
|
| 45 |
+
transforms.ToTensor(),
|
| 46 |
+
self.normalize,
|
| 47 |
+
]
|
| 48 |
+
)
|
| 49 |
+
|
| 50 |
+
self.image_size = image_size
|
| 51 |
+
|
| 52 |
+
def preprocess(self, images, return_tensors):
|
| 53 |
+
if isinstance(images, Image.Image):
|
| 54 |
+
images = [images]
|
| 55 |
+
else:
|
| 56 |
+
assert isinstance(images, list)
|
| 57 |
+
|
| 58 |
+
transformed_images = [self.transform(image).numpy() for image in images]
|
| 59 |
+
data = {"pixel_values": transformed_images}
|
| 60 |
+
|
| 61 |
+
return BatchFeature(data=data, tensor_type=return_tensors)
|
| 62 |
+
|
| 63 |
+
def __call__(self, item):
|
| 64 |
+
return self.transform(item)
|
| 65 |
+
|
| 66 |
+
@property
|
| 67 |
+
def crop_size(self):
|
| 68 |
+
return {"height": self.image_size, "width": self.image_size}
|
| 69 |
+
|
| 70 |
+
@property
|
| 71 |
+
def size(self):
|
| 72 |
+
return {"shortest_edge": self.image_size}
|
spatial-model/VLM-3R/llava/model/multimodal_encoder/eva_clip/eva_vit.py
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
# Adapted from https://github.com/baaivision/EVA/tree/master/EVA-CLIP
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
from math import pi
|
| 6 |
+
import torch
|
| 7 |
+
from torch import nn
|
| 8 |
+
from einops import rearrange, repeat
|
| 9 |
+
import logging
|
| 10 |
+
from llava.utils import rank0_print
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def broadcat(tensors, dim=-1):
|
| 14 |
+
num_tensors = len(tensors)
|
| 15 |
+
shape_lens = set(list(map(lambda t: len(t.shape), tensors)))
|
| 16 |
+
assert len(shape_lens) == 1, "tensors must all have the same number of dimensions"
|
| 17 |
+
shape_len = list(shape_lens)[0]
|
| 18 |
+
dim = (dim + shape_len) if dim < 0 else dim
|
| 19 |
+
dims = list(zip(*map(lambda t: list(t.shape), tensors)))
|
| 20 |
+
expandable_dims = [(i, val) for i, val in enumerate(dims) if i != dim]
|
| 21 |
+
assert all([*map(lambda t: len(set(t[1])) <= 2, expandable_dims)]), "invalid dimensions for broadcastable concatentation"
|
| 22 |
+
max_dims = list(map(lambda t: (t[0], max(t[1])), expandable_dims))
|
| 23 |
+
expanded_dims = list(map(lambda t: (t[0], (t[1],) * num_tensors), max_dims))
|
| 24 |
+
expanded_dims.insert(dim, (dim, dims[dim]))
|
| 25 |
+
expandable_shapes = list(zip(*map(lambda t: t[1], expanded_dims)))
|
| 26 |
+
tensors = list(map(lambda t: t[0].expand(*t[1]), zip(tensors, expandable_shapes)))
|
| 27 |
+
return torch.cat(tensors, dim=dim)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def rotate_half(x):
|
| 31 |
+
x = rearrange(x, "... (d r) -> ... d r", r=2)
|
| 32 |
+
x1, x2 = x.unbind(dim=-1)
|
| 33 |
+
x = torch.stack((-x2, x1), dim=-1)
|
| 34 |
+
return rearrange(x, "... d r -> ... (d r)")
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
class VisionRotaryEmbeddingFast(nn.Module):
|
| 38 |
+
def __init__(self, dim, pt_seq_len, ft_seq_len=None, custom_freqs=None, freqs_for="lang", theta=10000, max_freq=10, num_freqs=1, patch_dropout=0.0):
|
| 39 |
+
super().__init__()
|
| 40 |
+
if custom_freqs:
|
| 41 |
+
freqs = custom_freqs
|
| 42 |
+
elif freqs_for == "lang":
|
| 43 |
+
freqs = 1.0 / (theta ** (torch.arange(0, dim, 2)[: (dim // 2)].float() / dim))
|
| 44 |
+
elif freqs_for == "pixel":
|
| 45 |
+
freqs = torch.linspace(1.0, max_freq / 2, dim // 2) * pi
|
| 46 |
+
elif freqs_for == "constant":
|
| 47 |
+
freqs = torch.ones(num_freqs).float()
|
| 48 |
+
else:
|
| 49 |
+
raise ValueError(f"unknown modality {freqs_for}")
|
| 50 |
+
|
| 51 |
+
if ft_seq_len is None:
|
| 52 |
+
ft_seq_len = pt_seq_len
|
| 53 |
+
t = torch.arange(ft_seq_len) / ft_seq_len * pt_seq_len
|
| 54 |
+
|
| 55 |
+
freqs = torch.einsum("..., f -> ... f", t, freqs)
|
| 56 |
+
freqs = repeat(freqs, "... n -> ... (n r)", r=2)
|
| 57 |
+
freqs = broadcat((freqs[:, None, :], freqs[None, :, :]), dim=-1)
|
| 58 |
+
|
| 59 |
+
freqs_cos = freqs.cos().view(-1, freqs.shape[-1])
|
| 60 |
+
freqs_sin = freqs.sin().view(-1, freqs.shape[-1])
|
| 61 |
+
|
| 62 |
+
self.patch_dropout = patch_dropout
|
| 63 |
+
|
| 64 |
+
self.register_buffer("freqs_cos", freqs_cos)
|
| 65 |
+
self.register_buffer("freqs_sin", freqs_sin)
|
| 66 |
+
|
| 67 |
+
logging.info(f"Shape of rope freq: {self.freqs_cos.shape}")
|
| 68 |
+
|
| 69 |
+
def forward(self, t, patch_indices_keep=None):
|
| 70 |
+
if patch_indices_keep is not None:
|
| 71 |
+
batch = t.size()[0]
|
| 72 |
+
batch_indices = torch.arange(batch)
|
| 73 |
+
batch_indices = batch_indices[..., None]
|
| 74 |
+
|
| 75 |
+
freqs_cos = repeat(self.freqs_cos, "i j -> n i m j", n=t.shape[0], m=t.shape[1])
|
| 76 |
+
freqs_sin = repeat(self.freqs_sin, "i j -> n i m j", n=t.shape[0], m=t.shape[1])
|
| 77 |
+
|
| 78 |
+
freqs_cos = freqs_cos[batch_indices, patch_indices_keep]
|
| 79 |
+
freqs_cos = rearrange(freqs_cos, "n i m j -> n m i j")
|
| 80 |
+
freqs_sin = freqs_sin[batch_indices, patch_indices_keep]
|
| 81 |
+
freqs_sin = rearrange(freqs_sin, "n i m j -> n m i j")
|
| 82 |
+
|
| 83 |
+
return t * freqs_cos + rotate_half(t) * freqs_sin
|
| 84 |
+
|
| 85 |
+
return t * self.freqs_cos + rotate_half(t) * self.freqs_sin
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
class LayerNorm(nn.LayerNorm):
|
| 89 |
+
"""Subclass torch's LayerNorm (with cast back to input dtype)."""
|
| 90 |
+
|
| 91 |
+
def forward(self, x: torch.Tensor):
|
| 92 |
+
orig_type = x.dtype
|
| 93 |
+
x = F.layer_norm(x, self.normalized_shape, self.weight, self.bias, self.eps)
|
| 94 |
+
return x.to(orig_type)
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
class PatchDropout(nn.Module):
|
| 98 |
+
"""
|
| 99 |
+
https://arxiv.org/abs/2212.00794
|
| 100 |
+
"""
|
| 101 |
+
|
| 102 |
+
def __init__(self, prob, exclude_first_token=True):
|
| 103 |
+
super().__init__()
|
| 104 |
+
assert 0 <= prob < 1.0
|
| 105 |
+
self.prob = prob
|
| 106 |
+
self.exclude_first_token = exclude_first_token # exclude CLS token
|
| 107 |
+
logging.info(f"os.getenv('RoPE')={os.getenv('RoPE')}")
|
| 108 |
+
|
| 109 |
+
def forward(self, x):
|
| 110 |
+
if not self.training or self.prob == 0.0:
|
| 111 |
+
return x
|
| 112 |
+
|
| 113 |
+
if self.exclude_first_token:
|
| 114 |
+
cls_tokens, x = x[:, :1], x[:, 1:]
|
| 115 |
+
else:
|
| 116 |
+
cls_tokens = torch.jit.annotate(torch.Tensor, x[:, :1])
|
| 117 |
+
|
| 118 |
+
batch = x.size()[0]
|
| 119 |
+
num_tokens = x.size()[1]
|
| 120 |
+
|
| 121 |
+
batch_indices = torch.arange(batch)
|
| 122 |
+
batch_indices = batch_indices[..., None]
|
| 123 |
+
|
| 124 |
+
keep_prob = 1 - self.prob
|
| 125 |
+
num_patches_keep = max(1, int(num_tokens * keep_prob))
|
| 126 |
+
|
| 127 |
+
rand = torch.randn(batch, num_tokens)
|
| 128 |
+
patch_indices_keep = rand.topk(num_patches_keep, dim=-1).indices
|
| 129 |
+
|
| 130 |
+
x = x[batch_indices, patch_indices_keep]
|
| 131 |
+
|
| 132 |
+
if self.exclude_first_token:
|
| 133 |
+
x = torch.cat((cls_tokens, x), dim=1)
|
| 134 |
+
|
| 135 |
+
if self.training and os.getenv("RoPE") == "1":
|
| 136 |
+
return x, patch_indices_keep
|
| 137 |
+
|
| 138 |
+
return x
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
# --------------------------------------------------------
|
| 142 |
+
# Adapted from https://github.com/microsoft/unilm/tree/master/beit
|
| 143 |
+
# --------------------------------------------------------
|
| 144 |
+
import math
|
| 145 |
+
import os
|
| 146 |
+
import torch.nn as nn
|
| 147 |
+
import torch.nn.functional as F
|
| 148 |
+
|
| 149 |
+
try:
|
| 150 |
+
from timm.models.layers import drop_path, to_2tuple, trunc_normal_
|
| 151 |
+
except:
|
| 152 |
+
from timm.layers import drop_path, to_2tuple, trunc_normal_
|
| 153 |
+
|
| 154 |
+
if os.getenv("ENV_TYPE") == "deepspeed":
|
| 155 |
+
try:
|
| 156 |
+
from deepspeed.runtime.activation_checkpointing.checkpointing import checkpoint
|
| 157 |
+
except:
|
| 158 |
+
from torch.utils.checkpoint import checkpoint
|
| 159 |
+
else:
|
| 160 |
+
from torch.utils.checkpoint import checkpoint
|
| 161 |
+
|
| 162 |
+
try:
|
| 163 |
+
import xformers.ops as xops
|
| 164 |
+
except ImportError:
|
| 165 |
+
xops = None
|
| 166 |
+
# print("Please 'pip install xformers'")
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
class DropPath(nn.Module):
|
| 170 |
+
"""Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks)."""
|
| 171 |
+
|
| 172 |
+
def __init__(self, drop_prob=None):
|
| 173 |
+
super(DropPath, self).__init__()
|
| 174 |
+
self.drop_prob = drop_prob
|
| 175 |
+
|
| 176 |
+
def forward(self, x):
|
| 177 |
+
return drop_path(x, self.drop_prob, self.training)
|
| 178 |
+
|
| 179 |
+
def extra_repr(self) -> str:
|
| 180 |
+
return "p={}".format(self.drop_prob)
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
class Mlp(nn.Module):
|
| 184 |
+
def __init__(
|
| 185 |
+
self,
|
| 186 |
+
in_features,
|
| 187 |
+
hidden_features=None,
|
| 188 |
+
out_features=None,
|
| 189 |
+
act_layer=nn.GELU,
|
| 190 |
+
norm_layer=nn.LayerNorm,
|
| 191 |
+
drop=0.0,
|
| 192 |
+
subln=False,
|
| 193 |
+
):
|
| 194 |
+
super().__init__()
|
| 195 |
+
out_features = out_features or in_features
|
| 196 |
+
hidden_features = hidden_features or in_features
|
| 197 |
+
self.fc1 = nn.Linear(in_features, hidden_features)
|
| 198 |
+
self.act = act_layer()
|
| 199 |
+
|
| 200 |
+
self.ffn_ln = norm_layer(hidden_features) if subln else nn.Identity()
|
| 201 |
+
|
| 202 |
+
self.fc2 = nn.Linear(hidden_features, out_features)
|
| 203 |
+
self.drop = nn.Dropout(drop)
|
| 204 |
+
|
| 205 |
+
def forward(self, x):
|
| 206 |
+
x = self.fc1(x)
|
| 207 |
+
x = self.act(x)
|
| 208 |
+
# x = self.drop(x)
|
| 209 |
+
# commit this for the orignal BERT implement
|
| 210 |
+
x = self.ffn_ln(x)
|
| 211 |
+
|
| 212 |
+
x = self.fc2(x)
|
| 213 |
+
x = self.drop(x)
|
| 214 |
+
return x
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
class SwiGLU(nn.Module):
|
| 218 |
+
def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.SiLU, drop=0.0, norm_layer=nn.LayerNorm, subln=False):
|
| 219 |
+
super().__init__()
|
| 220 |
+
out_features = out_features or in_features
|
| 221 |
+
hidden_features = hidden_features or in_features
|
| 222 |
+
|
| 223 |
+
self.w1 = nn.Linear(in_features, hidden_features)
|
| 224 |
+
self.w2 = nn.Linear(in_features, hidden_features)
|
| 225 |
+
|
| 226 |
+
self.act = act_layer()
|
| 227 |
+
self.ffn_ln = norm_layer(hidden_features) if subln else nn.Identity()
|
| 228 |
+
self.w3 = nn.Linear(hidden_features, out_features)
|
| 229 |
+
|
| 230 |
+
self.drop = nn.Dropout(drop)
|
| 231 |
+
|
| 232 |
+
def forward(self, x):
|
| 233 |
+
x1 = self.w1(x)
|
| 234 |
+
x2 = self.w2(x)
|
| 235 |
+
hidden = self.act(x1) * x2
|
| 236 |
+
x = self.ffn_ln(hidden)
|
| 237 |
+
x = self.w3(x)
|
| 238 |
+
x = self.drop(x)
|
| 239 |
+
return x
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
class Attention(nn.Module):
|
| 243 |
+
def __init__(self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0.0, proj_drop=0.0, window_size=None, attn_head_dim=None, xattn=False, rope=None, subln=False, norm_layer=nn.LayerNorm):
|
| 244 |
+
super().__init__()
|
| 245 |
+
self.num_heads = num_heads
|
| 246 |
+
head_dim = dim // num_heads
|
| 247 |
+
if attn_head_dim is not None:
|
| 248 |
+
head_dim = attn_head_dim
|
| 249 |
+
all_head_dim = head_dim * self.num_heads
|
| 250 |
+
self.scale = qk_scale or head_dim**-0.5
|
| 251 |
+
|
| 252 |
+
self.subln = subln
|
| 253 |
+
if self.subln:
|
| 254 |
+
self.q_proj = nn.Linear(dim, all_head_dim, bias=False)
|
| 255 |
+
self.k_proj = nn.Linear(dim, all_head_dim, bias=False)
|
| 256 |
+
self.v_proj = nn.Linear(dim, all_head_dim, bias=False)
|
| 257 |
+
else:
|
| 258 |
+
self.qkv = nn.Linear(dim, all_head_dim * 3, bias=False)
|
| 259 |
+
|
| 260 |
+
if qkv_bias:
|
| 261 |
+
self.q_bias = nn.Parameter(torch.zeros(all_head_dim))
|
| 262 |
+
self.v_bias = nn.Parameter(torch.zeros(all_head_dim))
|
| 263 |
+
else:
|
| 264 |
+
self.q_bias = None
|
| 265 |
+
self.v_bias = None
|
| 266 |
+
|
| 267 |
+
if window_size:
|
| 268 |
+
self.window_size = window_size
|
| 269 |
+
self.num_relative_distance = (2 * window_size[0] - 1) * (2 * window_size[1] - 1) + 3
|
| 270 |
+
self.relative_position_bias_table = nn.Parameter(torch.zeros(self.num_relative_distance, num_heads)) # 2*Wh-1 * 2*Ww-1, nH
|
| 271 |
+
# cls to token & token 2 cls & cls to cls
|
| 272 |
+
|
| 273 |
+
# get pair-wise relative position index for each token inside the window
|
| 274 |
+
coords_h = torch.arange(window_size[0])
|
| 275 |
+
coords_w = torch.arange(window_size[1])
|
| 276 |
+
coords = torch.stack(torch.meshgrid([coords_h, coords_w])) # 2, Wh, Ww
|
| 277 |
+
coords_flatten = torch.flatten(coords, 1) # 2, Wh*Ww
|
| 278 |
+
relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :] # 2, Wh*Ww, Wh*Ww
|
| 279 |
+
relative_coords = relative_coords.permute(1, 2, 0).contiguous() # Wh*Ww, Wh*Ww, 2
|
| 280 |
+
relative_coords[:, :, 0] += window_size[0] - 1 # shift to start from 0
|
| 281 |
+
relative_coords[:, :, 1] += window_size[1] - 1
|
| 282 |
+
relative_coords[:, :, 0] *= 2 * window_size[1] - 1
|
| 283 |
+
relative_position_index = torch.zeros(size=(window_size[0] * window_size[1] + 1,) * 2, dtype=relative_coords.dtype)
|
| 284 |
+
relative_position_index[1:, 1:] = relative_coords.sum(-1) # Wh*Ww, Wh*Ww
|
| 285 |
+
relative_position_index[0, 0:] = self.num_relative_distance - 3
|
| 286 |
+
relative_position_index[0:, 0] = self.num_relative_distance - 2
|
| 287 |
+
relative_position_index[0, 0] = self.num_relative_distance - 1
|
| 288 |
+
|
| 289 |
+
self.register_buffer("relative_position_index", relative_position_index)
|
| 290 |
+
else:
|
| 291 |
+
self.window_size = None
|
| 292 |
+
self.relative_position_bias_table = None
|
| 293 |
+
self.relative_position_index = None
|
| 294 |
+
|
| 295 |
+
self.attn_drop = nn.Dropout(attn_drop)
|
| 296 |
+
self.inner_attn_ln = norm_layer(all_head_dim) if subln else nn.Identity()
|
| 297 |
+
# self.proj = nn.Linear(all_head_dim, all_head_dim)
|
| 298 |
+
self.proj = nn.Linear(all_head_dim, dim)
|
| 299 |
+
self.proj_drop = nn.Dropout(proj_drop)
|
| 300 |
+
self.xattn = xattn
|
| 301 |
+
self.xattn_drop = attn_drop
|
| 302 |
+
|
| 303 |
+
self.rope = rope
|
| 304 |
+
|
| 305 |
+
def forward(self, x, rel_pos_bias=None, attn_mask=None):
|
| 306 |
+
B, N, C = x.shape
|
| 307 |
+
if self.subln:
|
| 308 |
+
q = F.linear(input=x, weight=self.q_proj.weight, bias=self.q_bias)
|
| 309 |
+
k = F.linear(input=x, weight=self.k_proj.weight, bias=None)
|
| 310 |
+
v = F.linear(input=x, weight=self.v_proj.weight, bias=self.v_bias)
|
| 311 |
+
|
| 312 |
+
q = q.reshape(B, N, self.num_heads, -1).permute(0, 2, 1, 3) # B, num_heads, N, C
|
| 313 |
+
k = k.reshape(B, N, self.num_heads, -1).permute(0, 2, 1, 3)
|
| 314 |
+
v = v.reshape(B, N, self.num_heads, -1).permute(0, 2, 1, 3)
|
| 315 |
+
else:
|
| 316 |
+
|
| 317 |
+
qkv_bias = None
|
| 318 |
+
if self.q_bias is not None:
|
| 319 |
+
qkv_bias = torch.cat((self.q_bias, torch.zeros_like(self.v_bias, requires_grad=False), self.v_bias))
|
| 320 |
+
|
| 321 |
+
qkv = F.linear(input=x, weight=self.qkv.weight, bias=qkv_bias)
|
| 322 |
+
qkv = qkv.reshape(B, N, 3, self.num_heads, -1).permute(2, 0, 3, 1, 4) # 3, B, num_heads, N, C
|
| 323 |
+
q, k, v = qkv[0], qkv[1], qkv[2]
|
| 324 |
+
|
| 325 |
+
if self.rope:
|
| 326 |
+
# slightly fast impl
|
| 327 |
+
q_t = q[:, :, 1:, :]
|
| 328 |
+
ro_q_t = self.rope(q_t)
|
| 329 |
+
q = torch.cat((q[:, :, :1, :], ro_q_t), -2).type_as(v)
|
| 330 |
+
|
| 331 |
+
k_t = k[:, :, 1:, :]
|
| 332 |
+
ro_k_t = self.rope(k_t)
|
| 333 |
+
k = torch.cat((k[:, :, :1, :], ro_k_t), -2).type_as(v)
|
| 334 |
+
|
| 335 |
+
if self.xattn and xops is not None:
|
| 336 |
+
q = q.permute(0, 2, 1, 3) # B, num_heads, N, C -> B, N, num_heads, C
|
| 337 |
+
k = k.permute(0, 2, 1, 3)
|
| 338 |
+
v = v.permute(0, 2, 1, 3)
|
| 339 |
+
|
| 340 |
+
x = xops.memory_efficient_attention(
|
| 341 |
+
q,
|
| 342 |
+
k,
|
| 343 |
+
v,
|
| 344 |
+
p=self.xattn_drop,
|
| 345 |
+
scale=self.scale,
|
| 346 |
+
)
|
| 347 |
+
x = x.reshape(B, N, -1)
|
| 348 |
+
x = self.inner_attn_ln(x)
|
| 349 |
+
x = self.proj(x)
|
| 350 |
+
x = self.proj_drop(x)
|
| 351 |
+
else:
|
| 352 |
+
q = q * self.scale
|
| 353 |
+
attn = q @ k.transpose(-2, -1)
|
| 354 |
+
|
| 355 |
+
if self.relative_position_bias_table is not None:
|
| 356 |
+
relative_position_bias = self.relative_position_bias_table[self.relative_position_index.view(-1)].view(self.window_size[0] * self.window_size[1] + 1, self.window_size[0] * self.window_size[1] + 1, -1) # Wh*Ww,Wh*Ww,nH
|
| 357 |
+
relative_position_bias = relative_position_bias.permute(2, 0, 1).contiguous() # nH, Wh*Ww, Wh*Ww
|
| 358 |
+
attn = attn + relative_position_bias.unsqueeze(0).type_as(attn)
|
| 359 |
+
|
| 360 |
+
if rel_pos_bias is not None:
|
| 361 |
+
attn = attn + rel_pos_bias.type_as(attn)
|
| 362 |
+
|
| 363 |
+
if attn_mask is not None:
|
| 364 |
+
attn_mask = attn_mask.bool()
|
| 365 |
+
attn = attn.masked_fill(~attn_mask[:, None, None, :], float("-inf"))
|
| 366 |
+
|
| 367 |
+
attn = attn.softmax(dim=-1)
|
| 368 |
+
attn = self.attn_drop(attn)
|
| 369 |
+
|
| 370 |
+
x = (attn @ v).transpose(1, 2).reshape(B, N, -1)
|
| 371 |
+
x = self.inner_attn_ln(x)
|
| 372 |
+
x = self.proj(x)
|
| 373 |
+
x = self.proj_drop(x)
|
| 374 |
+
return x
|
| 375 |
+
|
| 376 |
+
|
| 377 |
+
class Block(nn.Module):
|
| 378 |
+
|
| 379 |
+
def __init__(
|
| 380 |
+
self,
|
| 381 |
+
dim,
|
| 382 |
+
num_heads,
|
| 383 |
+
mlp_ratio=4.0,
|
| 384 |
+
qkv_bias=False,
|
| 385 |
+
qk_scale=None,
|
| 386 |
+
drop=0.0,
|
| 387 |
+
attn_drop=0.0,
|
| 388 |
+
drop_path=0.0,
|
| 389 |
+
init_values=None,
|
| 390 |
+
act_layer=nn.GELU,
|
| 391 |
+
norm_layer=nn.LayerNorm,
|
| 392 |
+
window_size=None,
|
| 393 |
+
attn_head_dim=None,
|
| 394 |
+
xattn=False,
|
| 395 |
+
rope=None,
|
| 396 |
+
postnorm=False,
|
| 397 |
+
subln=False,
|
| 398 |
+
naiveswiglu=False,
|
| 399 |
+
):
|
| 400 |
+
super().__init__()
|
| 401 |
+
self.norm1 = norm_layer(dim)
|
| 402 |
+
self.attn = Attention(
|
| 403 |
+
dim, num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop, window_size=window_size, attn_head_dim=attn_head_dim, xattn=xattn, rope=rope, subln=subln, norm_layer=norm_layer
|
| 404 |
+
)
|
| 405 |
+
# NOTE: drop path for stochastic depth, we shall see if this is better than dropout here
|
| 406 |
+
self.drop_path = DropPath(drop_path) if drop_path > 0.0 else nn.Identity()
|
| 407 |
+
self.norm2 = norm_layer(dim)
|
| 408 |
+
mlp_hidden_dim = int(dim * mlp_ratio)
|
| 409 |
+
|
| 410 |
+
if naiveswiglu:
|
| 411 |
+
self.mlp = SwiGLU(
|
| 412 |
+
in_features=dim,
|
| 413 |
+
hidden_features=mlp_hidden_dim,
|
| 414 |
+
subln=subln,
|
| 415 |
+
norm_layer=norm_layer,
|
| 416 |
+
)
|
| 417 |
+
else:
|
| 418 |
+
self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, subln=subln, drop=drop)
|
| 419 |
+
|
| 420 |
+
if init_values is not None and init_values > 0:
|
| 421 |
+
self.gamma_1 = nn.Parameter(init_values * torch.ones((dim)), requires_grad=True)
|
| 422 |
+
self.gamma_2 = nn.Parameter(init_values * torch.ones((dim)), requires_grad=True)
|
| 423 |
+
else:
|
| 424 |
+
self.gamma_1, self.gamma_2 = None, None
|
| 425 |
+
|
| 426 |
+
self.postnorm = postnorm
|
| 427 |
+
|
| 428 |
+
def forward(self, x, rel_pos_bias=None, attn_mask=None):
|
| 429 |
+
if self.gamma_1 is None:
|
| 430 |
+
if self.postnorm:
|
| 431 |
+
x = x + self.drop_path(self.norm1(self.attn(x, rel_pos_bias=rel_pos_bias, attn_mask=attn_mask)))
|
| 432 |
+
x = x + self.drop_path(self.norm2(self.mlp(x)))
|
| 433 |
+
else:
|
| 434 |
+
x = x + self.drop_path(self.attn(self.norm1(x), rel_pos_bias=rel_pos_bias, attn_mask=attn_mask))
|
| 435 |
+
x = x + self.drop_path(self.mlp(self.norm2(x)))
|
| 436 |
+
else:
|
| 437 |
+
if self.postnorm:
|
| 438 |
+
x = x + self.drop_path(self.gamma_1 * self.norm1(self.attn(x, rel_pos_bias=rel_pos_bias, attn_mask=attn_mask)))
|
| 439 |
+
x = x + self.drop_path(self.gamma_2 * self.norm2(self.mlp(x)))
|
| 440 |
+
else:
|
| 441 |
+
x = x + self.drop_path(self.gamma_1 * self.attn(self.norm1(x), rel_pos_bias=rel_pos_bias, attn_mask=attn_mask))
|
| 442 |
+
x = x + self.drop_path(self.gamma_2 * self.mlp(self.norm2(x)))
|
| 443 |
+
return x
|
| 444 |
+
|
| 445 |
+
|
| 446 |
+
class PatchEmbed(nn.Module):
|
| 447 |
+
"""Image to Patch Embedding"""
|
| 448 |
+
|
| 449 |
+
def __init__(self, img_size=224, patch_size=16, in_chans=3, embed_dim=768):
|
| 450 |
+
super().__init__()
|
| 451 |
+
img_size = to_2tuple(img_size)
|
| 452 |
+
patch_size = to_2tuple(patch_size)
|
| 453 |
+
num_patches = (img_size[1] // patch_size[1]) * (img_size[0] // patch_size[0])
|
| 454 |
+
self.patch_shape = (img_size[0] // patch_size[0], img_size[1] // patch_size[1])
|
| 455 |
+
self.img_size = img_size
|
| 456 |
+
self.patch_size = patch_size
|
| 457 |
+
self.num_patches = num_patches
|
| 458 |
+
|
| 459 |
+
self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=patch_size)
|
| 460 |
+
|
| 461 |
+
def forward(self, x, **kwargs):
|
| 462 |
+
B, C, H, W = x.shape
|
| 463 |
+
# FIXME look at relaxing size constraints
|
| 464 |
+
assert H == self.img_size[0] and W == self.img_size[1], f"Input image size ({H}*{W}) doesn't match model ({self.img_size[0]}*{self.img_size[1]})."
|
| 465 |
+
x = self.proj(x).flatten(2).transpose(1, 2)
|
| 466 |
+
return x
|
| 467 |
+
|
| 468 |
+
|
| 469 |
+
class RelativePositionBias(nn.Module):
|
| 470 |
+
|
| 471 |
+
def __init__(self, window_size, num_heads):
|
| 472 |
+
super().__init__()
|
| 473 |
+
self.window_size = window_size
|
| 474 |
+
self.num_relative_distance = (2 * window_size[0] - 1) * (2 * window_size[1] - 1) + 3
|
| 475 |
+
self.relative_position_bias_table = nn.Parameter(torch.zeros(self.num_relative_distance, num_heads)) # 2*Wh-1 * 2*Ww-1, nH
|
| 476 |
+
# cls to token & token 2 cls & cls to cls
|
| 477 |
+
|
| 478 |
+
# get pair-wise relative position index for each token inside the window
|
| 479 |
+
coords_h = torch.arange(window_size[0])
|
| 480 |
+
coords_w = torch.arange(window_size[1])
|
| 481 |
+
coords = torch.stack(torch.meshgrid([coords_h, coords_w])) # 2, Wh, Ww
|
| 482 |
+
coords_flatten = torch.flatten(coords, 1) # 2, Wh*Ww
|
| 483 |
+
relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :] # 2, Wh*Ww, Wh*Ww
|
| 484 |
+
relative_coords = relative_coords.permute(1, 2, 0).contiguous() # Wh*Ww, Wh*Ww, 2
|
| 485 |
+
relative_coords[:, :, 0] += window_size[0] - 1 # shift to start from 0
|
| 486 |
+
relative_coords[:, :, 1] += window_size[1] - 1
|
| 487 |
+
relative_coords[:, :, 0] *= 2 * window_size[1] - 1
|
| 488 |
+
relative_position_index = torch.zeros(size=(window_size[0] * window_size[1] + 1,) * 2, dtype=relative_coords.dtype)
|
| 489 |
+
relative_position_index[1:, 1:] = relative_coords.sum(-1) # Wh*Ww, Wh*Ww
|
| 490 |
+
relative_position_index[0, 0:] = self.num_relative_distance - 3
|
| 491 |
+
relative_position_index[0:, 0] = self.num_relative_distance - 2
|
| 492 |
+
relative_position_index[0, 0] = self.num_relative_distance - 1
|
| 493 |
+
|
| 494 |
+
self.register_buffer("relative_position_index", relative_position_index)
|
| 495 |
+
|
| 496 |
+
def forward(self):
|
| 497 |
+
relative_position_bias = self.relative_position_bias_table[self.relative_position_index.view(-1)].view(self.window_size[0] * self.window_size[1] + 1, self.window_size[0] * self.window_size[1] + 1, -1) # Wh*Ww,Wh*Ww,nH
|
| 498 |
+
return relative_position_bias.permute(2, 0, 1).contiguous() # nH, Wh*Ww, Wh*Ww
|
| 499 |
+
|
| 500 |
+
|
| 501 |
+
class EVAVisionTransformer(nn.Module):
|
| 502 |
+
"""Vision Transformer with support for patch or hybrid CNN input stage"""
|
| 503 |
+
|
| 504 |
+
def __init__(
|
| 505 |
+
self,
|
| 506 |
+
img_size=224,
|
| 507 |
+
patch_size=16,
|
| 508 |
+
in_chans=3,
|
| 509 |
+
num_classes=1000,
|
| 510 |
+
embed_dim=768,
|
| 511 |
+
depth=12,
|
| 512 |
+
num_heads=12,
|
| 513 |
+
mlp_ratio=4.0,
|
| 514 |
+
qkv_bias=False,
|
| 515 |
+
qk_scale=None,
|
| 516 |
+
drop_rate=0.0,
|
| 517 |
+
attn_drop_rate=0.0,
|
| 518 |
+
drop_path_rate=0.0,
|
| 519 |
+
norm_layer=nn.LayerNorm,
|
| 520 |
+
init_values=None,
|
| 521 |
+
patch_dropout=0.0,
|
| 522 |
+
use_abs_pos_emb=True,
|
| 523 |
+
use_rel_pos_bias=False,
|
| 524 |
+
use_shared_rel_pos_bias=False,
|
| 525 |
+
rope=False,
|
| 526 |
+
use_mean_pooling=True,
|
| 527 |
+
init_scale=0.001,
|
| 528 |
+
grad_checkpointing=False,
|
| 529 |
+
xattn=False,
|
| 530 |
+
postnorm=False,
|
| 531 |
+
pt_hw_seq_len=16,
|
| 532 |
+
intp_freq=False,
|
| 533 |
+
naiveswiglu=False,
|
| 534 |
+
subln=False,
|
| 535 |
+
):
|
| 536 |
+
super().__init__()
|
| 537 |
+
self.image_size = img_size
|
| 538 |
+
self.num_classes = num_classes
|
| 539 |
+
self.num_features = self.embed_dim = embed_dim # num_features for consistency with other models
|
| 540 |
+
|
| 541 |
+
self.patch_embed = PatchEmbed(img_size=img_size, patch_size=patch_size, in_chans=in_chans, embed_dim=embed_dim)
|
| 542 |
+
num_patches = self.patch_embed.num_patches
|
| 543 |
+
|
| 544 |
+
self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim))
|
| 545 |
+
# self.mask_token = nn.Parameter(torch.zeros(1, 1, embed_dim))
|
| 546 |
+
if use_abs_pos_emb:
|
| 547 |
+
self.pos_embed = nn.Parameter(torch.zeros(1, num_patches + 1, embed_dim))
|
| 548 |
+
else:
|
| 549 |
+
self.pos_embed = None
|
| 550 |
+
self.pos_drop = nn.Dropout(p=drop_rate)
|
| 551 |
+
|
| 552 |
+
if use_shared_rel_pos_bias:
|
| 553 |
+
self.rel_pos_bias = RelativePositionBias(window_size=self.patch_embed.patch_shape, num_heads=num_heads)
|
| 554 |
+
else:
|
| 555 |
+
self.rel_pos_bias = None
|
| 556 |
+
|
| 557 |
+
if rope:
|
| 558 |
+
half_head_dim = embed_dim // num_heads // 2
|
| 559 |
+
hw_seq_len = img_size // patch_size
|
| 560 |
+
self.rope = VisionRotaryEmbeddingFast(
|
| 561 |
+
dim=half_head_dim,
|
| 562 |
+
pt_seq_len=pt_hw_seq_len,
|
| 563 |
+
ft_seq_len=hw_seq_len if intp_freq else None,
|
| 564 |
+
# patch_dropout=patch_dropout
|
| 565 |
+
)
|
| 566 |
+
else:
|
| 567 |
+
self.rope = None
|
| 568 |
+
|
| 569 |
+
self.naiveswiglu = naiveswiglu
|
| 570 |
+
|
| 571 |
+
dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)] # stochastic depth decay rule
|
| 572 |
+
self.use_rel_pos_bias = use_rel_pos_bias
|
| 573 |
+
self.blocks = nn.ModuleList(
|
| 574 |
+
[
|
| 575 |
+
Block(
|
| 576 |
+
dim=embed_dim,
|
| 577 |
+
num_heads=num_heads,
|
| 578 |
+
mlp_ratio=mlp_ratio,
|
| 579 |
+
qkv_bias=qkv_bias,
|
| 580 |
+
qk_scale=qk_scale,
|
| 581 |
+
drop=drop_rate,
|
| 582 |
+
attn_drop=attn_drop_rate,
|
| 583 |
+
drop_path=dpr[i],
|
| 584 |
+
norm_layer=norm_layer,
|
| 585 |
+
init_values=init_values,
|
| 586 |
+
window_size=self.patch_embed.patch_shape if use_rel_pos_bias else None,
|
| 587 |
+
xattn=xattn,
|
| 588 |
+
rope=self.rope,
|
| 589 |
+
postnorm=postnorm,
|
| 590 |
+
subln=subln,
|
| 591 |
+
naiveswiglu=naiveswiglu,
|
| 592 |
+
)
|
| 593 |
+
for i in range(depth)
|
| 594 |
+
]
|
| 595 |
+
)
|
| 596 |
+
self.norm = nn.Identity() if use_mean_pooling else norm_layer(embed_dim)
|
| 597 |
+
self.fc_norm = norm_layer(embed_dim) if use_mean_pooling else None
|
| 598 |
+
self.head = nn.Linear(embed_dim, num_classes) if num_classes > 0 else nn.Identity()
|
| 599 |
+
|
| 600 |
+
if self.pos_embed is not None:
|
| 601 |
+
trunc_normal_(self.pos_embed, std=0.02)
|
| 602 |
+
|
| 603 |
+
trunc_normal_(self.cls_token, std=0.02)
|
| 604 |
+
# trunc_normal_(self.mask_token, std=.02)
|
| 605 |
+
|
| 606 |
+
self.apply(self._init_weights)
|
| 607 |
+
self.fix_init_weight()
|
| 608 |
+
|
| 609 |
+
if isinstance(self.head, nn.Linear):
|
| 610 |
+
trunc_normal_(self.head.weight, std=0.02)
|
| 611 |
+
self.head.weight.data.mul_(init_scale)
|
| 612 |
+
self.head.bias.data.mul_(init_scale)
|
| 613 |
+
|
| 614 |
+
# setting a patch_dropout of 0. would mean it is disabled and this function would be the identity fn
|
| 615 |
+
self.patch_dropout = PatchDropout(patch_dropout) if patch_dropout > 0.0 else nn.Identity()
|
| 616 |
+
|
| 617 |
+
self.grad_checkpointing = grad_checkpointing
|
| 618 |
+
|
| 619 |
+
def fix_init_weight(self):
|
| 620 |
+
def rescale(param, layer_id):
|
| 621 |
+
param.div_(math.sqrt(2.0 * layer_id))
|
| 622 |
+
|
| 623 |
+
for layer_id, layer in enumerate(self.blocks):
|
| 624 |
+
rescale(layer.attn.proj.weight.data, layer_id + 1)
|
| 625 |
+
if self.naiveswiglu:
|
| 626 |
+
rescale(layer.mlp.w3.weight.data, layer_id + 1)
|
| 627 |
+
else:
|
| 628 |
+
rescale(layer.mlp.fc2.weight.data, layer_id + 1)
|
| 629 |
+
|
| 630 |
+
def get_cast_dtype(self) -> torch.dtype:
|
| 631 |
+
return self.blocks[0].mlp.fc2.weight.dtype
|
| 632 |
+
|
| 633 |
+
def _init_weights(self, m):
|
| 634 |
+
if isinstance(m, nn.Linear):
|
| 635 |
+
trunc_normal_(m.weight, std=0.02)
|
| 636 |
+
if m.bias is not None:
|
| 637 |
+
nn.init.constant_(m.bias, 0)
|
| 638 |
+
elif isinstance(m, nn.LayerNorm):
|
| 639 |
+
nn.init.constant_(m.bias, 0)
|
| 640 |
+
nn.init.constant_(m.weight, 1.0)
|
| 641 |
+
|
| 642 |
+
def get_num_layers(self):
|
| 643 |
+
return len(self.blocks)
|
| 644 |
+
|
| 645 |
+
def lock(self, unlocked_groups=0, freeze_bn_stats=False):
|
| 646 |
+
assert unlocked_groups == 0, "partial locking not currently supported for this model"
|
| 647 |
+
for param in self.parameters():
|
| 648 |
+
param.requires_grad = False
|
| 649 |
+
|
| 650 |
+
@torch.jit.ignore
|
| 651 |
+
def set_grad_checkpointing(self, enable=True):
|
| 652 |
+
self.grad_checkpointing = enable
|
| 653 |
+
|
| 654 |
+
@torch.jit.ignore
|
| 655 |
+
def no_weight_decay(self):
|
| 656 |
+
return {"pos_embed", "cls_token"}
|
| 657 |
+
|
| 658 |
+
def get_classifier(self):
|
| 659 |
+
return self.head
|
| 660 |
+
|
| 661 |
+
def reset_classifier(self, num_classes, global_pool=""):
|
| 662 |
+
self.num_classes = num_classes
|
| 663 |
+
self.head = nn.Linear(self.embed_dim, num_classes) if num_classes > 0 else nn.Identity()
|
| 664 |
+
|
| 665 |
+
def forward_features(self, x, return_all_features=False):
|
| 666 |
+
|
| 667 |
+
x = self.patch_embed(x)
|
| 668 |
+
batch_size, seq_len, _ = x.size()
|
| 669 |
+
|
| 670 |
+
cls_tokens = self.cls_token.expand(batch_size, -1, -1) # stole cls_tokens impl from Phil Wang, thanks
|
| 671 |
+
x = torch.cat((cls_tokens, x), dim=1)
|
| 672 |
+
if self.pos_embed is not None:
|
| 673 |
+
x = x + self.pos_embed
|
| 674 |
+
x = self.pos_drop(x)
|
| 675 |
+
|
| 676 |
+
# a patch_dropout of 0. would mean it is disabled and this function would do nothing but return what was passed in
|
| 677 |
+
if os.getenv("RoPE") == "1":
|
| 678 |
+
if self.training and not isinstance(self.patch_dropout, nn.Identity):
|
| 679 |
+
x, patch_indices_keep = self.patch_dropout(x)
|
| 680 |
+
# Directly pass patch_indices_keep to self.rope.forward
|
| 681 |
+
x = self.rope.forward(x, patch_indices_keep=patch_indices_keep)
|
| 682 |
+
else:
|
| 683 |
+
# Pass None or omit the patch_indices_keep argument for default behavior
|
| 684 |
+
x = self.rope.forward(x, patch_indices_keep=None)
|
| 685 |
+
x = self.patch_dropout(x)
|
| 686 |
+
else:
|
| 687 |
+
x = self.patch_dropout(x)
|
| 688 |
+
|
| 689 |
+
rel_pos_bias = self.rel_pos_bias() if self.rel_pos_bias is not None else None
|
| 690 |
+
for i, blk in enumerate(self.blocks):
|
| 691 |
+
if i == len(self.blocks) - 1:
|
| 692 |
+
continue
|
| 693 |
+
if self.grad_checkpointing:
|
| 694 |
+
x = checkpoint(blk, x, (rel_pos_bias,))
|
| 695 |
+
else:
|
| 696 |
+
x = blk(x, rel_pos_bias=rel_pos_bias)
|
| 697 |
+
|
| 698 |
+
if not return_all_features:
|
| 699 |
+
x = self.norm(x)
|
| 700 |
+
if self.fc_norm is not None:
|
| 701 |
+
return self.fc_norm(x.mean(1))
|
| 702 |
+
else:
|
| 703 |
+
return x[:, 0]
|
| 704 |
+
return x
|
| 705 |
+
|
| 706 |
+
def forward(self, x, return_all_features=False):
|
| 707 |
+
if return_all_features:
|
| 708 |
+
return self.forward_features(x, return_all_features)
|
| 709 |
+
x = self.forward_features(x)
|
| 710 |
+
x = self.head(x)
|
| 711 |
+
return x
|
| 712 |
+
|
| 713 |
+
|
| 714 |
+
def load_state_dict(checkpoint_path: str, map_location: str = "cpu", model_key: str = "model|module|state_dict", is_openai: bool = False, skip_list: list = []):
|
| 715 |
+
if is_openai:
|
| 716 |
+
model = torch.jit.load(checkpoint_path, map_location="cpu").eval()
|
| 717 |
+
state_dict = model.state_dict()
|
| 718 |
+
for key in ["input_resolution", "context_length", "vocab_size"]:
|
| 719 |
+
state_dict.pop(key, None)
|
| 720 |
+
else:
|
| 721 |
+
checkpoint = torch.load(checkpoint_path, map_location=map_location)
|
| 722 |
+
for mk in model_key.split("|"):
|
| 723 |
+
if isinstance(checkpoint, dict) and mk in checkpoint:
|
| 724 |
+
state_dict = checkpoint[mk]
|
| 725 |
+
break
|
| 726 |
+
else:
|
| 727 |
+
state_dict = checkpoint
|
| 728 |
+
if next(iter(state_dict.items()))[0].startswith("module"):
|
| 729 |
+
state_dict = {k[7:]: v for k, v in state_dict.items()}
|
| 730 |
+
|
| 731 |
+
for k in skip_list:
|
| 732 |
+
if k in list(state_dict.keys()):
|
| 733 |
+
logging.info(f"Removing key {k} from pretrained checkpoint")
|
| 734 |
+
del state_dict[k]
|
| 735 |
+
|
| 736 |
+
if os.getenv("RoPE") == "1":
|
| 737 |
+
for k in list(state_dict.keys()):
|
| 738 |
+
if "freqs_cos" in k or "freqs_sin" in k:
|
| 739 |
+
del state_dict[k]
|
| 740 |
+
return state_dict
|
| 741 |
+
|
| 742 |
+
|
| 743 |
+
def load_clip_visual_state_dict(checkpoint_path: str, map_location: str = "cpu", is_openai: bool = False, skip_list: list = []):
|
| 744 |
+
state_dict = load_state_dict(checkpoint_path, map_location=map_location, is_openai=is_openai, skip_list=skip_list)
|
| 745 |
+
# for k in list(state_dict.keys()):
|
| 746 |
+
# if not k.startswith("visual."):
|
| 747 |
+
# del state_dict[k]
|
| 748 |
+
# for k in list(state_dict.keys()):
|
| 749 |
+
# if k.startswith("visual."):
|
| 750 |
+
# new_k = k[7:]
|
| 751 |
+
# state_dict[new_k] = state_dict[k]
|
| 752 |
+
# del state_dict[k]
|
| 753 |
+
return state_dict
|
| 754 |
+
|
| 755 |
+
|
| 756 |
+
from dataclasses import dataclass
|
| 757 |
+
from typing import Optional, Tuple, Union
|
| 758 |
+
|
| 759 |
+
try:
|
| 760 |
+
from apex.normalization import FusedLayerNorm
|
| 761 |
+
except:
|
| 762 |
+
FusedLayerNorm = LayerNorm
|
| 763 |
+
# print("Please build and install Nvidia apex package with option '--cuda_ext' according to https://github.com/NVIDIA/apex#from-source .")
|
| 764 |
+
|
| 765 |
+
|
| 766 |
+
@dataclass
|
| 767 |
+
class CLIPVisionCfg:
|
| 768 |
+
layers: Union[Tuple[int, int, int, int], int] = 12
|
| 769 |
+
width: int = 768
|
| 770 |
+
head_width: int = 64
|
| 771 |
+
mlp_ratio: float = 4.0
|
| 772 |
+
patch_size: int = 16
|
| 773 |
+
image_size: Union[Tuple[int, int], int] = 224
|
| 774 |
+
ls_init_value: Optional[float] = None # layer scale initial value
|
| 775 |
+
patch_dropout: float = 0.0 # what fraction of patches to dropout during training (0 would mean disabled and no patches dropped) - 0.5 to 0.75 recommended in the paper for optimal results
|
| 776 |
+
global_average_pool: bool = False # whether to global average pool the last embedding layer, instead of using CLS token (https://arxiv.org/abs/2205.01580)
|
| 777 |
+
drop_path_rate: Optional[float] = None # drop path rate
|
| 778 |
+
timm_model_name: str = None # a valid model name overrides layers, width, patch_size
|
| 779 |
+
timm_model_pretrained: bool = False # use (imagenet) pretrained weights for named model
|
| 780 |
+
timm_pool: str = "avg" # feature pooling for timm model ('abs_attn', 'rot_attn', 'avg', '')
|
| 781 |
+
timm_proj: str = "linear" # linear projection for timm model output ('linear', 'mlp', '')
|
| 782 |
+
timm_proj_bias: bool = False # enable bias final projection
|
| 783 |
+
eva_model_name: str = None # a valid eva model name overrides layers, width, patch_size
|
| 784 |
+
qkv_bias: bool = True
|
| 785 |
+
fusedLN: bool = False
|
| 786 |
+
xattn: bool = False
|
| 787 |
+
postnorm: bool = False
|
| 788 |
+
rope: bool = False
|
| 789 |
+
pt_hw_seq_len: int = 16 # 224/14
|
| 790 |
+
intp_freq: bool = False
|
| 791 |
+
naiveswiglu: bool = False
|
| 792 |
+
subln: bool = False
|
| 793 |
+
|
| 794 |
+
|
| 795 |
+
def create_norm_layer_factory(use_fused_ln, eps=1e-6):
|
| 796 |
+
# Otherwise, use the standard LayerNorm
|
| 797 |
+
return lambda num_features: nn.LayerNorm(num_features, eps=eps)
|
| 798 |
+
|
| 799 |
+
|
| 800 |
+
def _build_vision_tower(vision_tower_path: str, embed_dim: int, vision_cfg: CLIPVisionCfg, **kwargs):
|
| 801 |
+
if isinstance(vision_cfg, dict):
|
| 802 |
+
vision_cfg = CLIPVisionCfg(**vision_cfg)
|
| 803 |
+
|
| 804 |
+
if vision_cfg.eva_model_name:
|
| 805 |
+
vision_heads = vision_cfg.width // vision_cfg.head_width
|
| 806 |
+
# Determine the appropriate norm layer factory based on the configuration
|
| 807 |
+
norm_layer_factory = create_norm_layer_factory(vision_cfg.fusedLN, eps=1e-6)
|
| 808 |
+
|
| 809 |
+
visual = EVAVisionTransformer(
|
| 810 |
+
img_size=vision_cfg.image_size,
|
| 811 |
+
patch_size=vision_cfg.patch_size,
|
| 812 |
+
num_classes=embed_dim,
|
| 813 |
+
use_mean_pooling=vision_cfg.global_average_pool, # False
|
| 814 |
+
init_values=vision_cfg.ls_init_value,
|
| 815 |
+
patch_dropout=vision_cfg.patch_dropout,
|
| 816 |
+
embed_dim=vision_cfg.width,
|
| 817 |
+
depth=vision_cfg.layers,
|
| 818 |
+
num_heads=vision_heads,
|
| 819 |
+
mlp_ratio=vision_cfg.mlp_ratio,
|
| 820 |
+
qkv_bias=vision_cfg.qkv_bias,
|
| 821 |
+
drop_path_rate=vision_cfg.drop_path_rate,
|
| 822 |
+
norm_layer=norm_layer_factory,
|
| 823 |
+
xattn=vision_cfg.xattn,
|
| 824 |
+
rope=vision_cfg.rope,
|
| 825 |
+
postnorm=vision_cfg.postnorm,
|
| 826 |
+
pt_hw_seq_len=vision_cfg.pt_hw_seq_len, # 224/14
|
| 827 |
+
intp_freq=vision_cfg.intp_freq,
|
| 828 |
+
naiveswiglu=vision_cfg.naiveswiglu,
|
| 829 |
+
subln=vision_cfg.subln,
|
| 830 |
+
)
|
| 831 |
+
|
| 832 |
+
state_dict = load_clip_visual_state_dict(vision_tower_path)
|
| 833 |
+
incompatible_keys = visual.load_state_dict(state_dict, strict=False)
|
| 834 |
+
rank0_print("EVA-CLIP incompatible_keys:", incompatible_keys)
|
| 835 |
+
|
| 836 |
+
return visual
|
| 837 |
+
|
| 838 |
+
|
| 839 |
+
class EVAEncoderWrapper(nn.Module):
|
| 840 |
+
def __init__(self, vision_tower_pretrained, config):
|
| 841 |
+
super(EVAEncoderWrapper, self).__init__()
|
| 842 |
+
self.config = config
|
| 843 |
+
self.config["vision_tower_path"] = vision_tower_pretrained
|
| 844 |
+
self.model = _build_vision_tower(**self.config)
|
| 845 |
+
|
| 846 |
+
def forward(self, image, **kwargs):
|
| 847 |
+
encode = self.model(image, return_all_features=True)[:, 1:, :] # remove the CLS token
|
| 848 |
+
return encode
|
| 849 |
+
|
| 850 |
+
@property
|
| 851 |
+
def dtype(self):
|
| 852 |
+
return list(self.parameters())[-1].dtype
|
| 853 |
+
|
| 854 |
+
@property
|
| 855 |
+
def device(self):
|
| 856 |
+
return list(self.parameters())[-1].device
|
spatial-model/VLM-3R/llava/model/multimodal_encoder/eva_clip/factory.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import logging
|
| 3 |
+
import os
|
| 4 |
+
import pathlib
|
| 5 |
+
import re
|
| 6 |
+
from copy import deepcopy
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
from typing import Optional, Tuple, Union, Dict, Any
|
| 9 |
+
import torch
|
| 10 |
+
|
| 11 |
+
_MODEL_CONFIG_PATHS = [Path(__file__).parent / f"model_configs/"]
|
| 12 |
+
_MODEL_CONFIGS = {} # directory (model_name: config) of model architecture configs
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def _natural_key(string_):
|
| 16 |
+
return [int(s) if s.isdigit() else s for s in re.split(r"(\d+)", string_.lower())]
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def _rescan_model_configs():
|
| 20 |
+
global _MODEL_CONFIGS
|
| 21 |
+
|
| 22 |
+
config_ext = (".json",)
|
| 23 |
+
config_files = []
|
| 24 |
+
for config_path in _MODEL_CONFIG_PATHS:
|
| 25 |
+
if config_path.is_file() and config_path.suffix in config_ext:
|
| 26 |
+
config_files.append(config_path)
|
| 27 |
+
elif config_path.is_dir():
|
| 28 |
+
for ext in config_ext:
|
| 29 |
+
config_files.extend(config_path.glob(f"*{ext}"))
|
| 30 |
+
|
| 31 |
+
for cf in config_files:
|
| 32 |
+
with open(cf, "r", encoding="utf8") as f:
|
| 33 |
+
model_cfg = json.load(f)
|
| 34 |
+
if all(a in model_cfg for a in ("embed_dim", "vision_cfg", "text_cfg")):
|
| 35 |
+
_MODEL_CONFIGS[cf.stem] = model_cfg
|
| 36 |
+
|
| 37 |
+
_MODEL_CONFIGS = dict(sorted(_MODEL_CONFIGS.items(), key=lambda x: _natural_key(x[0])))
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
_rescan_model_configs() # initial populate of model config registry
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def list_models():
|
| 44 |
+
"""enumerate available model architectures based on config files"""
|
| 45 |
+
return list(_MODEL_CONFIGS.keys())
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def add_model_config(path):
|
| 49 |
+
"""add model config path or file and update registry"""
|
| 50 |
+
if not isinstance(path, Path):
|
| 51 |
+
path = Path(path)
|
| 52 |
+
_MODEL_CONFIG_PATHS.append(path)
|
| 53 |
+
_rescan_model_configs()
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def get_model_config(model_name):
|
| 57 |
+
if model_name in _MODEL_CONFIGS:
|
| 58 |
+
return deepcopy(_MODEL_CONFIGS[model_name])
|
| 59 |
+
else:
|
| 60 |
+
return None
|
spatial-model/VLM-3R/llava/model/multimodal_encoder/mlcd/vit_rope2d_hf.py
ADDED
|
@@ -0,0 +1,452 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Optional, Tuple, Union
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
import torch.utils.checkpoint
|
| 5 |
+
from torch import nn
|
| 6 |
+
from torch.nn import functional as F
|
| 7 |
+
from transformers.models.clip.modeling_clip import (CLIPMLP, BaseModelOutput,
|
| 8 |
+
BaseModelOutputWithPooling,
|
| 9 |
+
CLIPVisionConfig,
|
| 10 |
+
PreTrainedModel)
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def rotate_half(x):
|
| 14 |
+
x1 = x[..., : x.shape[-1] // 2]
|
| 15 |
+
x2 = x[..., x.shape[-1] // 2 :]
|
| 16 |
+
return torch.cat((-x2, x1), dim=-1)
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def apply_rotary_pos_emb_vision(tensor: torch.Tensor, freqs: torch.Tensor) -> torch.Tensor:
|
| 20 |
+
orig_dtype = tensor.dtype
|
| 21 |
+
tensor = tensor.float()
|
| 22 |
+
cos = freqs.cos()
|
| 23 |
+
sin = freqs.sin()
|
| 24 |
+
cos = cos.unsqueeze(1).repeat(1, 1, 2).unsqueeze(0).float()
|
| 25 |
+
sin = sin.unsqueeze(1).repeat(1, 1, 2).unsqueeze(0).float()
|
| 26 |
+
output = (tensor * cos) + (rotate_half(tensor) * sin)
|
| 27 |
+
output = output.to(orig_dtype)
|
| 28 |
+
return output
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class VisionRotaryEmbedding(nn.Module):
|
| 32 |
+
def __init__(self, dim: int, theta: float = 10000.0) -> None:
|
| 33 |
+
super().__init__()
|
| 34 |
+
inv_freq = 1.0 / (theta ** (torch.arange(0, dim, 2, dtype=torch.float) / dim))
|
| 35 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
| 36 |
+
|
| 37 |
+
def forward(self, seqlen: int) -> torch.Tensor:
|
| 38 |
+
seq = torch.arange(seqlen, device=self.inv_freq.device, dtype=self.inv_freq.dtype)
|
| 39 |
+
freqs = torch.outer(seq, self.inv_freq)
|
| 40 |
+
return freqs
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
class MLCDVisionConfig(CLIPVisionConfig):
|
| 44 |
+
|
| 45 |
+
model_type = "mlcd_vision_model"
|
| 46 |
+
|
| 47 |
+
def __init__(self,**kwargs):
|
| 48 |
+
super().__init__(**kwargs)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
class MLCDMLP(CLIPMLP):
|
| 52 |
+
def __init__(self, config: MLCDVisionConfig):
|
| 53 |
+
super().__init__(config)
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
class MLCDVisionEmbeddings(torch.nn.Module):
|
| 57 |
+
def __init__(self, config: MLCDVisionConfig):
|
| 58 |
+
super().__init__()
|
| 59 |
+
self.config = config
|
| 60 |
+
self.embed_dim = config.hidden_size
|
| 61 |
+
self.image_size = config.image_size
|
| 62 |
+
self.patch_size = config.patch_size
|
| 63 |
+
|
| 64 |
+
self.class_embedding = nn.Parameter(torch.randn(self.embed_dim))
|
| 65 |
+
|
| 66 |
+
self.patch_embedding = nn.Conv2d(
|
| 67 |
+
in_channels=config.num_channels,
|
| 68 |
+
out_channels=self.embed_dim,
|
| 69 |
+
kernel_size=self.patch_size,
|
| 70 |
+
stride=self.patch_size,
|
| 71 |
+
bias=False,
|
| 72 |
+
)
|
| 73 |
+
|
| 74 |
+
self.num_patches = (self.image_size // self.patch_size) ** 2
|
| 75 |
+
self.num_positions = self.num_patches + 1
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def forward(self, pixel_values: torch.FloatTensor) -> torch.Tensor:
|
| 79 |
+
batch_size = pixel_values.shape[0]
|
| 80 |
+
target_dtype = self.patch_embedding.weight.dtype
|
| 81 |
+
patch_embeds = self.patch_embedding(pixel_values.to(dtype=target_dtype)) # shape = [*, width, grid, grid]
|
| 82 |
+
patch_embeds = patch_embeds.flatten(2).transpose(1, 2)
|
| 83 |
+
|
| 84 |
+
class_embeds = self.class_embedding.expand(batch_size, 1, -1)
|
| 85 |
+
embeddings = torch.cat([class_embeds, patch_embeds], dim=1)
|
| 86 |
+
|
| 87 |
+
return embeddings
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
class MLCDSdpaAttention(torch.nn.Module):
|
| 91 |
+
"""Multi-headed attention from these papers
|
| 92 |
+
|
| 93 |
+
- Attention is all you need:
|
| 94 |
+
https://arxiv.org/abs/1706.03762
|
| 95 |
+
|
| 96 |
+
- RoFormer: Enhanced Transformer with Rotary Position Embedding:
|
| 97 |
+
https://arxiv.org/abs/2104.09864
|
| 98 |
+
"""
|
| 99 |
+
|
| 100 |
+
def __init__(self, config: MLCDVisionConfig):
|
| 101 |
+
super().__init__()
|
| 102 |
+
self.config = config
|
| 103 |
+
self.embed_dim = config.hidden_size
|
| 104 |
+
self.num_heads = config.num_attention_heads
|
| 105 |
+
self.head_dim = self.embed_dim // self.num_heads
|
| 106 |
+
if self.head_dim * self.num_heads != self.embed_dim:
|
| 107 |
+
raise ValueError(
|
| 108 |
+
f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:"
|
| 109 |
+
f" {self.num_heads})."
|
| 110 |
+
)
|
| 111 |
+
self.scale = self.head_dim**-0.5
|
| 112 |
+
self.dropout = config.attention_dropout
|
| 113 |
+
self.q_proj = nn.Linear(self.embed_dim, self.embed_dim)
|
| 114 |
+
self.k_proj = nn.Linear(self.embed_dim, self.embed_dim)
|
| 115 |
+
self.v_proj = nn.Linear(self.embed_dim, self.embed_dim)
|
| 116 |
+
self.out_proj = nn.Linear(self.embed_dim, self.embed_dim)
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def forward(
|
| 120 |
+
self,
|
| 121 |
+
hidden_states: torch.Tensor,
|
| 122 |
+
rotary_pos_emb: torch.Tensor,
|
| 123 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
|
| 124 |
+
"""Input shape: Batch x Seq x Hidden Size"""
|
| 125 |
+
batch_size, seq_length , hidden_size = hidden_states.size()
|
| 126 |
+
# Each of shape: [batch_size, seq_length, num_heads, head_dim]
|
| 127 |
+
q = self.q_proj(hidden_states).reshape((batch_size, seq_length, self.num_heads, self.head_dim))
|
| 128 |
+
k = self.k_proj(hidden_states).reshape((batch_size, seq_length, self.num_heads, self.head_dim))
|
| 129 |
+
v = self.v_proj(hidden_states).reshape((batch_size, seq_length, self.num_heads, self.head_dim))
|
| 130 |
+
q = apply_rotary_pos_emb_vision(q, rotary_pos_emb)
|
| 131 |
+
k = apply_rotary_pos_emb_vision(k, rotary_pos_emb)
|
| 132 |
+
q = q.permute(0, 2, 1, 3).contiguous()
|
| 133 |
+
k = k.permute(0, 2, 1, 3).contiguous()
|
| 134 |
+
v = v.permute(0, 2, 1, 3).contiguous()
|
| 135 |
+
# q (batch_size, num_heads, seq_length, head_dim)
|
| 136 |
+
# k (batch_size, num_heads, seq_length, head_dim)
|
| 137 |
+
# v (batch_size, num_heads, seq_length, head_dim)
|
| 138 |
+
attn_output = F.scaled_dot_product_attention(q, k, v, None, dropout_p=0.0)
|
| 139 |
+
attn_output = attn_output.permute(2, 0, 1, 3).contiguous() # [seq_length, batch_size, num_heads, head_dim]
|
| 140 |
+
attn_output = attn_output.view(seq_length, batch_size, -1) # [seq_length, batch_size, embedding_dim]
|
| 141 |
+
attn_output = self.out_proj(attn_output)
|
| 142 |
+
attn_output = attn_output.permute(1, 0, 2).contiguous() # [batch_size, seq_length, embedding_dim]
|
| 143 |
+
return attn_output, None
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
class MLCDEncoderLayer(nn.Module):
|
| 147 |
+
def __init__(self, config: MLCDVisionConfig):
|
| 148 |
+
super().__init__()
|
| 149 |
+
self.embed_dim = config.hidden_size
|
| 150 |
+
self.self_attn = MLCDSdpaAttention(config)
|
| 151 |
+
self.layer_norm1 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
|
| 152 |
+
self.mlp = MLCDMLP(config)
|
| 153 |
+
self.layer_norm2 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
|
| 154 |
+
|
| 155 |
+
def forward(
|
| 156 |
+
self,
|
| 157 |
+
hidden_states: torch.Tensor,
|
| 158 |
+
rotary_pos_emb: torch.Tensor,
|
| 159 |
+
) -> Tuple[torch.FloatTensor]:
|
| 160 |
+
"""
|
| 161 |
+
Args:
|
| 162 |
+
hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
|
| 163 |
+
attention_mask (`torch.FloatTensor`): attention mask of size
|
| 164 |
+
`(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
|
| 165 |
+
`(config.encoder_attention_heads,)`.
|
| 166 |
+
"""
|
| 167 |
+
residual = hidden_states
|
| 168 |
+
|
| 169 |
+
hidden_states = self.layer_norm1(hidden_states)
|
| 170 |
+
|
| 171 |
+
hidden_states = self.self_attn(
|
| 172 |
+
hidden_states=hidden_states,
|
| 173 |
+
rotary_pos_emb=rotary_pos_emb,
|
| 174 |
+
)[0]
|
| 175 |
+
hidden_states = residual + hidden_states
|
| 176 |
+
|
| 177 |
+
residual = hidden_states
|
| 178 |
+
hidden_states = self.layer_norm2(hidden_states)
|
| 179 |
+
|
| 180 |
+
hidden_states = self.mlp(hidden_states)
|
| 181 |
+
|
| 182 |
+
hidden_states = residual + hidden_states
|
| 183 |
+
|
| 184 |
+
outputs = (hidden_states,)
|
| 185 |
+
return outputs
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
class MLCDEncoder(nn.Module):
|
| 189 |
+
"""
|
| 190 |
+
Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a
|
| 191 |
+
[`MLCDEncoderLayer`].
|
| 192 |
+
|
| 193 |
+
Args:
|
| 194 |
+
config: MLCDVisionConfig
|
| 195 |
+
"""
|
| 196 |
+
|
| 197 |
+
def __init__(self, config: MLCDVisionConfig):
|
| 198 |
+
super().__init__()
|
| 199 |
+
self.config = config
|
| 200 |
+
self.layers = nn.ModuleList([MLCDEncoderLayer(config) for _ in range(config.num_hidden_layers)])
|
| 201 |
+
self.gradient_checkpointing = False
|
| 202 |
+
|
| 203 |
+
def forward(
|
| 204 |
+
self,
|
| 205 |
+
inputs_embeds,
|
| 206 |
+
rotary_pos_emb,
|
| 207 |
+
output_hidden_states: Optional[bool] = None,
|
| 208 |
+
return_dict: Optional[bool] = None,
|
| 209 |
+
) -> Union[Tuple, BaseModelOutput]:
|
| 210 |
+
r"""
|
| 211 |
+
Args:
|
| 212 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
|
| 213 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
|
| 214 |
+
This is useful if you want more control over how to convert `input_ids` indices into associated vectors
|
| 215 |
+
than the model's internal embedding lookup matrix.
|
| 216 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 217 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 218 |
+
|
| 219 |
+
- 1 for tokens that are **not masked**,
|
| 220 |
+
- 0 for tokens that are **masked**.
|
| 221 |
+
|
| 222 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 223 |
+
causal_attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 224 |
+
Causal mask for the text model. Mask values selected in `[0, 1]`:
|
| 225 |
+
|
| 226 |
+
- 1 for tokens that are **not masked**,
|
| 227 |
+
- 0 for tokens that are **masked**.
|
| 228 |
+
|
| 229 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 230 |
+
output_attentions (`bool`, *optional*):
|
| 231 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
| 232 |
+
returned tensors for more detail.
|
| 233 |
+
output_hidden_states (`bool`, *optional*):
|
| 234 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
|
| 235 |
+
for more detail.
|
| 236 |
+
return_dict (`bool`, *optional*):
|
| 237 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 238 |
+
"""
|
| 239 |
+
|
| 240 |
+
output_hidden_states = (
|
| 241 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 242 |
+
)
|
| 243 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 244 |
+
|
| 245 |
+
encoder_states = () if output_hidden_states else None
|
| 246 |
+
|
| 247 |
+
hidden_states = inputs_embeds
|
| 248 |
+
for idx, encoder_layer in enumerate(self.layers):
|
| 249 |
+
if output_hidden_states:
|
| 250 |
+
encoder_states = encoder_states + (hidden_states,)
|
| 251 |
+
if self.gradient_checkpointing and self.training:
|
| 252 |
+
layer_outputs = self._gradient_checkpointing_func(
|
| 253 |
+
encoder_layer.__call__,
|
| 254 |
+
hidden_states,
|
| 255 |
+
rotary_pos_emb
|
| 256 |
+
)
|
| 257 |
+
else:
|
| 258 |
+
layer_outputs = encoder_layer(
|
| 259 |
+
hidden_states,
|
| 260 |
+
rotary_pos_emb
|
| 261 |
+
)
|
| 262 |
+
|
| 263 |
+
hidden_states = layer_outputs[0]
|
| 264 |
+
|
| 265 |
+
if output_hidden_states:
|
| 266 |
+
encoder_states = encoder_states + (hidden_states,)
|
| 267 |
+
|
| 268 |
+
if not return_dict:
|
| 269 |
+
return tuple(v for v in [hidden_states, encoder_states, None] if v is not None)
|
| 270 |
+
return BaseModelOutput(
|
| 271 |
+
last_hidden_state=hidden_states, hidden_states=encoder_states, attentions=None,
|
| 272 |
+
)
|
| 273 |
+
|
| 274 |
+
|
| 275 |
+
class MLCDVisionTransformer(nn.Module):
|
| 276 |
+
def __init__(self, config: MLCDVisionConfig):
|
| 277 |
+
super().__init__()
|
| 278 |
+
self.config = config
|
| 279 |
+
embed_dim = config.hidden_size
|
| 280 |
+
|
| 281 |
+
self.embeddings = MLCDVisionEmbeddings(config)
|
| 282 |
+
self.pre_layrnorm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
|
| 283 |
+
self.encoder = MLCDEncoder(config)
|
| 284 |
+
self.post_layernorm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
|
| 285 |
+
|
| 286 |
+
self.vision_rotary_embedding = VisionRotaryEmbedding(config.hidden_size // config.num_attention_heads // 2)
|
| 287 |
+
self.class_pos_emb = nn.Parameter(torch.randn(1, config.hidden_size // config.num_attention_heads // 2))
|
| 288 |
+
|
| 289 |
+
|
| 290 |
+
def rot_pos_emb(self, grid_thw):
|
| 291 |
+
pos_ids = []
|
| 292 |
+
for t, h, w in grid_thw:
|
| 293 |
+
hpos_ids = torch.arange(h).unsqueeze(1).expand(-1, w)
|
| 294 |
+
hpos_ids = hpos_ids.reshape(h, 1, w, 1)
|
| 295 |
+
hpos_ids = hpos_ids.permute(0, 2, 1, 3)
|
| 296 |
+
hpos_ids = hpos_ids.flatten()
|
| 297 |
+
|
| 298 |
+
wpos_ids = torch.arange(w).unsqueeze(0).expand(h, -1)
|
| 299 |
+
wpos_ids = wpos_ids.reshape(h, 1, w, 1)
|
| 300 |
+
wpos_ids = wpos_ids.permute(0, 2, 1, 3)
|
| 301 |
+
wpos_ids = wpos_ids.flatten()
|
| 302 |
+
pos_ids.append(torch.stack([hpos_ids, wpos_ids], dim=-1).repeat(t, 1))
|
| 303 |
+
pos_ids = torch.cat(pos_ids, dim=0)
|
| 304 |
+
max_grid_size = grid_thw[:, 1:].max()
|
| 305 |
+
rotary_pos_emb_full = self.vision_rotary_embedding(max_grid_size)
|
| 306 |
+
rotary_pos_emb = rotary_pos_emb_full[pos_ids].flatten(1)
|
| 307 |
+
return rotary_pos_emb
|
| 308 |
+
|
| 309 |
+
|
| 310 |
+
def forward(
|
| 311 |
+
self,
|
| 312 |
+
pixel_values: Optional[torch.FloatTensor] = None,
|
| 313 |
+
# output_attentions: Optional[bool] = None,
|
| 314 |
+
output_hidden_states: Optional[bool] = None,
|
| 315 |
+
return_dict: Optional[bool] = None,
|
| 316 |
+
) -> Union[Tuple, BaseModelOutputWithPooling]:
|
| 317 |
+
r"""
|
| 318 |
+
Returns:
|
| 319 |
+
|
| 320 |
+
"""
|
| 321 |
+
|
| 322 |
+
twh = (1, pixel_values.size(3) // self.config.patch_size, pixel_values.size(2) // self.config.patch_size)
|
| 323 |
+
rotary_pos_emb = self.rot_pos_emb(torch.tensor([twh], device=pixel_values.device))
|
| 324 |
+
rotary_pos_emb = torch.cat([self.class_pos_emb, rotary_pos_emb], dim=0)
|
| 325 |
+
|
| 326 |
+
# output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 327 |
+
output_hidden_states = (
|
| 328 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 329 |
+
)
|
| 330 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 331 |
+
|
| 332 |
+
if pixel_values is None:
|
| 333 |
+
raise ValueError("You have to specify pixel_values")
|
| 334 |
+
|
| 335 |
+
hidden_states = self.embeddings(pixel_values)
|
| 336 |
+
hidden_states = self.pre_layrnorm(hidden_states)
|
| 337 |
+
|
| 338 |
+
encoder_outputs = self.encoder(
|
| 339 |
+
inputs_embeds=hidden_states,
|
| 340 |
+
rotary_pos_emb=rotary_pos_emb,
|
| 341 |
+
# output_attentions=output_attentions,
|
| 342 |
+
output_hidden_states=output_hidden_states,
|
| 343 |
+
return_dict=return_dict,
|
| 344 |
+
)
|
| 345 |
+
|
| 346 |
+
last_hidden_state = encoder_outputs[0]
|
| 347 |
+
pooled_output = last_hidden_state[:, 0, :]
|
| 348 |
+
pooled_output = self.post_layernorm(pooled_output)
|
| 349 |
+
|
| 350 |
+
if not return_dict:
|
| 351 |
+
return (last_hidden_state, pooled_output) + encoder_outputs[1:]
|
| 352 |
+
|
| 353 |
+
return BaseModelOutputWithPooling(
|
| 354 |
+
last_hidden_state=last_hidden_state,
|
| 355 |
+
pooler_output=pooled_output,
|
| 356 |
+
hidden_states=encoder_outputs.hidden_states,
|
| 357 |
+
# attentions=encoder_outputs.attentions,
|
| 358 |
+
)
|
| 359 |
+
|
| 360 |
+
|
| 361 |
+
class MLCDPreTrainedModel(PreTrainedModel):
|
| 362 |
+
"""
|
| 363 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
| 364 |
+
models.
|
| 365 |
+
"""
|
| 366 |
+
config_class = MLCDVisionConfig
|
| 367 |
+
base_model_prefix = "mlcd"
|
| 368 |
+
supports_gradient_checkpointing = True
|
| 369 |
+
_supports_sdpa = True
|
| 370 |
+
# _supports_flash_attn_2 = True
|
| 371 |
+
|
| 372 |
+
def _init_weights(self, module):
|
| 373 |
+
"""Initialize the weights"""
|
| 374 |
+
factor = self.config.initializer_factor
|
| 375 |
+
if isinstance(module, MLCDVisionEmbeddings):
|
| 376 |
+
factor = self.config.initializer_factor
|
| 377 |
+
nn.init.normal_(module.class_embedding, mean=0.0, std=module.embed_dim**-0.5 * factor)
|
| 378 |
+
nn.init.normal_(module.patch_embedding.weight, std=module.config.initializer_range * factor)
|
| 379 |
+
elif isinstance(module, MLCDSdpaAttention):
|
| 380 |
+
factor = self.config.initializer_factor
|
| 381 |
+
in_proj_std = (module.embed_dim**-0.5) * ((2 * module.config.num_hidden_layers) ** -0.5) * factor
|
| 382 |
+
out_proj_std = (module.embed_dim**-0.5) * factor
|
| 383 |
+
nn.init.normal_(module.q_proj.weight, std=in_proj_std)
|
| 384 |
+
nn.init.normal_(module.k_proj.weight, std=in_proj_std)
|
| 385 |
+
nn.init.normal_(module.v_proj.weight, std=in_proj_std)
|
| 386 |
+
nn.init.normal_(module.out_proj.weight, std=out_proj_std)
|
| 387 |
+
elif isinstance(module, MLCDMLP):
|
| 388 |
+
factor = self.config.initializer_factor
|
| 389 |
+
in_proj_std = (module.config.hidden_size**-0.5) * ((2 * module.config.num_hidden_layers) ** -0.5) * factor
|
| 390 |
+
fc_std = (2 * module.config.hidden_size) ** -0.5 * factor
|
| 391 |
+
nn.init.normal_(module.fc1.weight, std=fc_std)
|
| 392 |
+
nn.init.normal_(module.fc2.weight, std=in_proj_std)
|
| 393 |
+
|
| 394 |
+
|
| 395 |
+
if isinstance(module, nn.LayerNorm):
|
| 396 |
+
module.bias.data.zero_()
|
| 397 |
+
module.weight.data.fill_(1.0)
|
| 398 |
+
if isinstance(module, nn.Linear) and module.bias is not None:
|
| 399 |
+
module.bias.data.zero_()
|
| 400 |
+
|
| 401 |
+
|
| 402 |
+
class MLCDVisionModel(MLCDPreTrainedModel):
|
| 403 |
+
config_class = MLCDVisionConfig
|
| 404 |
+
main_input_name = "pixel_values"
|
| 405 |
+
_no_split_modules = ["MLCDEncoderLayer"]
|
| 406 |
+
|
| 407 |
+
def __init__(self, config: MLCDVisionConfig):
|
| 408 |
+
super().__init__(config)
|
| 409 |
+
self.vision_model = MLCDVisionTransformer(config)
|
| 410 |
+
# Initialize weights and apply final processing
|
| 411 |
+
self.post_init()
|
| 412 |
+
|
| 413 |
+
def get_input_embeddings(self) -> nn.Module:
|
| 414 |
+
return self.vision_model.embeddings.patch_embedding
|
| 415 |
+
|
| 416 |
+
def forward(
|
| 417 |
+
self,
|
| 418 |
+
pixel_values: Optional[torch.FloatTensor] = None,
|
| 419 |
+
output_attentions: Optional[bool] = None,
|
| 420 |
+
output_hidden_states: Optional[bool] = None,
|
| 421 |
+
return_dict: Optional[bool] = None,
|
| 422 |
+
) -> Union[Tuple, BaseModelOutputWithPooling]:
|
| 423 |
+
r"""
|
| 424 |
+
Returns:
|
| 425 |
+
|
| 426 |
+
Examples:
|
| 427 |
+
|
| 428 |
+
```python
|
| 429 |
+
>>> from PIL import Image
|
| 430 |
+
>>> import requests
|
| 431 |
+
>>> from transformers import AutoProcessor, MLCDVisionModel
|
| 432 |
+
|
| 433 |
+
>>> model = MLCDVisionModel.from_pretrained("DeepGlint-AI/mlcd-vit-bigG-patch14")
|
| 434 |
+
>>> processor = AutoProcessor.from_pretrained("DeepGlint-AI/mlcd-vit-bigG-patch14")
|
| 435 |
+
|
| 436 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 437 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
| 438 |
+
|
| 439 |
+
>>> inputs = processor(images=image, return_tensors="pt")
|
| 440 |
+
|
| 441 |
+
>>> outputs = model(**inputs)
|
| 442 |
+
>>> last_hidden_state = outputs.last_hidden_state
|
| 443 |
+
>>> pooled_output = outputs.pooler_output # pooled CLS states
|
| 444 |
+
```"""
|
| 445 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 446 |
+
|
| 447 |
+
return self.vision_model(
|
| 448 |
+
pixel_values=pixel_values,
|
| 449 |
+
# output_attentions=output_attentions,
|
| 450 |
+
output_hidden_states=output_hidden_states,
|
| 451 |
+
return_dict=return_dict,
|
| 452 |
+
)
|
spatial-model/VLM-3R/scripts/archived/convert_gqa_for_eval.py
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import json
|
| 3 |
+
import argparse
|
| 4 |
+
|
| 5 |
+
parser = argparse.ArgumentParser()
|
| 6 |
+
parser.add_argument("--src", type=str)
|
| 7 |
+
parser.add_argument("--dst", type=str)
|
| 8 |
+
args = parser.parse_args()
|
| 9 |
+
|
| 10 |
+
all_answers = []
|
| 11 |
+
for line_idx, line in enumerate(open(args.src)):
|
| 12 |
+
res = json.loads(line)
|
| 13 |
+
question_id = res["question_id"]
|
| 14 |
+
text = res["text"].rstrip(".").lower()
|
| 15 |
+
all_answers.append({"questionId": question_id, "prediction": text})
|
| 16 |
+
|
| 17 |
+
with open(args.dst, "w") as f:
|
| 18 |
+
json.dump(all_answers, f)
|
spatial-model/VLM-3R/scripts/archived/convert_mmvet_for_eval.py
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import json
|
| 3 |
+
import argparse
|
| 4 |
+
|
| 5 |
+
parser = argparse.ArgumentParser()
|
| 6 |
+
parser.add_argument("--src", type=str)
|
| 7 |
+
parser.add_argument("--dst", type=str)
|
| 8 |
+
args = parser.parse_args()
|
| 9 |
+
|
| 10 |
+
cur_result = {}
|
| 11 |
+
|
| 12 |
+
for line in open(args.src):
|
| 13 |
+
data = json.loads(line)
|
| 14 |
+
qid = data["question_id"]
|
| 15 |
+
cur_result[f"v1_{qid}"] = data["text"]
|
| 16 |
+
|
| 17 |
+
with open(args.dst, "w") as f:
|
| 18 |
+
json.dump(cur_result, f, indent=2)
|
spatial-model/VLM-3R/scripts/archived/convert_sqa_to_llava.py
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import os
|
| 3 |
+
import fire
|
| 4 |
+
import re
|
| 5 |
+
from convert_sqa_to_llava_base_prompt import build_prompt_chatbot
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def convert_to_llava(base_dir, split, prompt_format="QCM-LEA"):
|
| 9 |
+
split_indices = json.load(open(os.path.join(base_dir, "pid_splits.json")))[split]
|
| 10 |
+
problems = json.load(open(os.path.join(base_dir, "problems.json")))
|
| 11 |
+
|
| 12 |
+
split_problems = build_prompt_chatbot(problems, split_indices, prompt_format, use_caption=False, is_test=False)
|
| 13 |
+
|
| 14 |
+
target_format = []
|
| 15 |
+
for prob_id, (input, output) in split_problems.items():
|
| 16 |
+
if input.startswith("Question: "):
|
| 17 |
+
input = input.replace("Question: ", "")
|
| 18 |
+
if output.startswith("Answer: "):
|
| 19 |
+
output = output.replace("Answer: ", "")
|
| 20 |
+
|
| 21 |
+
raw_prob_data = problems[prob_id]
|
| 22 |
+
if raw_prob_data["image"] is None:
|
| 23 |
+
target_format.append(
|
| 24 |
+
{
|
| 25 |
+
"id": prob_id,
|
| 26 |
+
"conversations": [
|
| 27 |
+
{"from": "human", "value": f"{input}"},
|
| 28 |
+
{"from": "gpt", "value": f"{output}"},
|
| 29 |
+
],
|
| 30 |
+
}
|
| 31 |
+
)
|
| 32 |
+
|
| 33 |
+
else:
|
| 34 |
+
target_format.append(
|
| 35 |
+
{
|
| 36 |
+
"id": prob_id,
|
| 37 |
+
"image": os.path.join(prob_id, raw_prob_data["image"]),
|
| 38 |
+
"conversations": [
|
| 39 |
+
{"from": "human", "value": f"{input}\n<image>"},
|
| 40 |
+
{"from": "gpt", "value": f"{output}"},
|
| 41 |
+
],
|
| 42 |
+
}
|
| 43 |
+
)
|
| 44 |
+
|
| 45 |
+
print(f"Number of samples: {len(target_format)}")
|
| 46 |
+
|
| 47 |
+
with open(os.path.join(base_dir, f"llava_{split}_{prompt_format}.json"), "w") as f:
|
| 48 |
+
json.dump(target_format, f, indent=2)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def convert_to_jsonl(base_dir, split, prompt_format="QCM-LEPA"):
|
| 52 |
+
split_indices = json.load(open(os.path.join(base_dir, "pid_splits.json")))[split]
|
| 53 |
+
problems = json.load(open(os.path.join(base_dir, "problems.json")))
|
| 54 |
+
|
| 55 |
+
split_problems = build_prompt_chatbot(problems, split_indices, prompt_format, use_caption=False, is_test=False)
|
| 56 |
+
|
| 57 |
+
writer = open(os.path.join(base_dir, f"scienceqa_{split}_{prompt_format}.jsonl"), "w")
|
| 58 |
+
for prob_id, (input, output) in split_problems.items():
|
| 59 |
+
if input.startswith("Question: "):
|
| 60 |
+
input = input.replace("Question: ", "")
|
| 61 |
+
if output.startswith("Answer: "):
|
| 62 |
+
output = output.replace("Answer: ", "")
|
| 63 |
+
|
| 64 |
+
raw_prob_data = problems[prob_id]
|
| 65 |
+
if raw_prob_data["image"] is None:
|
| 66 |
+
data = {
|
| 67 |
+
"id": prob_id,
|
| 68 |
+
"instruction": f"{input}",
|
| 69 |
+
"output": f"{output}",
|
| 70 |
+
}
|
| 71 |
+
|
| 72 |
+
else:
|
| 73 |
+
data = {
|
| 74 |
+
"id": prob_id,
|
| 75 |
+
"image": os.path.join(prob_id, raw_prob_data["image"]),
|
| 76 |
+
"instruction": f"{input}\n<image>",
|
| 77 |
+
"output": f"{output}",
|
| 78 |
+
}
|
| 79 |
+
writer.write(json.dumps(data) + "\n")
|
| 80 |
+
writer.close()
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def main(task, **kwargs):
|
| 84 |
+
globals()[task](**kwargs)
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
if __name__ == "__main__":
|
| 88 |
+
fire.Fire(main)
|
spatial-model/VLM-3R/scripts/archived/convert_sqa_to_llava_base_prompt.py
ADDED
|
@@ -0,0 +1,298 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
def get_question_text(problem):
|
| 2 |
+
question = problem["question"]
|
| 3 |
+
return question
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def get_context_text(problem, use_caption):
|
| 7 |
+
txt_context = problem["hint"]
|
| 8 |
+
img_context = problem["caption"] if use_caption else ""
|
| 9 |
+
context = " ".join([txt_context, img_context]).strip()
|
| 10 |
+
if context == "":
|
| 11 |
+
context = "N/A"
|
| 12 |
+
return context
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def get_choice_text(probelm, options):
|
| 16 |
+
choices = probelm["choices"]
|
| 17 |
+
choice_list = []
|
| 18 |
+
for i, c in enumerate(choices):
|
| 19 |
+
choice_list.append("({}) {}".format(options[i], c))
|
| 20 |
+
choice_txt = " ".join(choice_list)
|
| 21 |
+
# print(choice_txt)
|
| 22 |
+
return choice_txt
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def get_answer(problem, options):
|
| 26 |
+
return options[problem["answer"]]
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def get_lecture_text(problem):
|
| 30 |
+
# \\n: GPT-3 can generate the lecture with more tokens.
|
| 31 |
+
lecture = problem["lecture"].replace("\n", "\\n")
|
| 32 |
+
return lecture
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def get_solution_text(problem):
|
| 36 |
+
# \\n: GPT-3 can generate the solution with more tokens
|
| 37 |
+
solution = problem["solution"].replace("\n", "\\n")
|
| 38 |
+
return solution
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def create_one_example_chatbot(format, question, context, choice, answer, lecture, solution, test_example=True):
|
| 42 |
+
|
| 43 |
+
input_format, output_format = format.split("-")
|
| 44 |
+
|
| 45 |
+
## Inputs
|
| 46 |
+
if input_format == "CQM":
|
| 47 |
+
input = f"Context: {context}\nQuestion: {question}\nOptions: {choice}\n"
|
| 48 |
+
elif input_format == "QCM":
|
| 49 |
+
input = f"Question: {question}\nContext: {context}\nOptions: {choice}\n"
|
| 50 |
+
# upper bound experiment
|
| 51 |
+
elif input_format == "QCML":
|
| 52 |
+
input = f"Question: {question}\nContext: {context}\nOptions: {choice}\nBECAUSE: {lecture}\n"
|
| 53 |
+
elif input_format == "QCME":
|
| 54 |
+
input = f"Question: {question}\nContext: {context}\nOptions: {choice}\nBECAUSE: {solution}\n"
|
| 55 |
+
elif input_format == "QCMLE":
|
| 56 |
+
input = f"Question: {question}\nContext: {context}\nOptions: {choice}\nBECAUSE: {lecture} {solution}\n"
|
| 57 |
+
|
| 58 |
+
elif input_format == "QCLM":
|
| 59 |
+
input = f"Question: {question}\nContext: {context}\nBECAUSE: {lecture}\nOptions: {choice}\n"
|
| 60 |
+
elif input_format == "QCEM":
|
| 61 |
+
input = f"Question: {question}\nContext: {context}\nBECAUSE: {solution}\nOptions: {choice}\n"
|
| 62 |
+
elif input_format == "QCLEM":
|
| 63 |
+
input = f"Question: {question}\nContext: {context}\nBECAUSE: {lecture} {solution}\nOptions: {choice}\n"
|
| 64 |
+
|
| 65 |
+
# Outputs
|
| 66 |
+
if test_example:
|
| 67 |
+
output = "Answer:"
|
| 68 |
+
elif output_format == "A":
|
| 69 |
+
output = f"Answer: The answer is {answer}."
|
| 70 |
+
|
| 71 |
+
elif output_format == "AL":
|
| 72 |
+
output = f"Answer: The answer is {answer}. BECAUSE: {solution}"
|
| 73 |
+
elif output_format == "AE":
|
| 74 |
+
output = f"Answer: The answer is {answer}. BECAUSE: {lecture}"
|
| 75 |
+
elif output_format == "ALE":
|
| 76 |
+
output = f"Answer: The answer is {answer}. BECAUSE: {lecture} {solution}"
|
| 77 |
+
elif output_format == "AEL":
|
| 78 |
+
output = f"Answer: The answer is {answer}. BECAUSE: {solution} {lecture}"
|
| 79 |
+
|
| 80 |
+
elif output_format == "LA":
|
| 81 |
+
output = f"Answer: {lecture} The answer is {answer}."
|
| 82 |
+
elif output_format == "EA":
|
| 83 |
+
output = f"Answer: {solution} The answer is {answer}."
|
| 84 |
+
elif output_format == "LEA":
|
| 85 |
+
output = f"Answer: {lecture} {solution} The answer is {answer}."
|
| 86 |
+
elif output_format == "ELA":
|
| 87 |
+
output = f"Answer: {solution} {lecture} The answer is {answer}."
|
| 88 |
+
elif output_format == "LEPA":
|
| 89 |
+
output = ""
|
| 90 |
+
if len(lecture.strip()) > 0:
|
| 91 |
+
output += f"LECTURE: {lecture}\n"
|
| 92 |
+
if len(solution.strip()) > 0:
|
| 93 |
+
output += f"SOLUTION: {solution}\n"
|
| 94 |
+
output += "###\n"
|
| 95 |
+
output += f"ANSWER: {answer}."
|
| 96 |
+
|
| 97 |
+
input = input.replace(" ", " ").strip()
|
| 98 |
+
output = output.replace(" ", " ").strip()
|
| 99 |
+
if input.endswith("BECAUSE:"):
|
| 100 |
+
input = input.replace("BECAUSE:", "").strip()
|
| 101 |
+
if output.endswith("BECAUSE:"):
|
| 102 |
+
output = output.replace("BECAUSE:", "").strip()
|
| 103 |
+
return input, output
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def create_one_example(format, question, context, choice, answer, lecture, solution, test_example=True):
|
| 107 |
+
|
| 108 |
+
input_format, output_format = format.split("-")
|
| 109 |
+
|
| 110 |
+
## Inputs
|
| 111 |
+
if input_format == "CQM":
|
| 112 |
+
input = f"Context: {context}\nQuestion: {question}\nOptions: {choice}\n"
|
| 113 |
+
elif input_format == "QCM":
|
| 114 |
+
input = f"Question: {question}\nContext: {context}\nOptions: {choice}\n"
|
| 115 |
+
# upper bound experiment
|
| 116 |
+
elif input_format == "QCML":
|
| 117 |
+
input = f"Question: {question}\nContext: {context}\nOptions: {choice}\nBECAUSE: {lecture}\n"
|
| 118 |
+
elif input_format == "QCME":
|
| 119 |
+
input = f"Question: {question}\nContext: {context}\nOptions: {choice}\nBECAUSE: {solution}\n"
|
| 120 |
+
elif input_format == "QCMLE":
|
| 121 |
+
input = f"Question: {question}\nContext: {context}\nOptions: {choice}\nBECAUSE: {lecture} {solution}\n"
|
| 122 |
+
|
| 123 |
+
elif input_format == "QCLM":
|
| 124 |
+
input = f"Question: {question}\nContext: {context}\nBECAUSE: {lecture}\nOptions: {choice}\n"
|
| 125 |
+
elif input_format == "QCEM":
|
| 126 |
+
input = f"Question: {question}\nContext: {context}\nBECAUSE: {solution}\nOptions: {choice}\n"
|
| 127 |
+
elif input_format == "QCLEM":
|
| 128 |
+
input = f"Question: {question}\nContext: {context}\nBECAUSE: {lecture} {solution}\nOptions: {choice}\n"
|
| 129 |
+
|
| 130 |
+
# Outputs
|
| 131 |
+
if test_example:
|
| 132 |
+
output = "Answer:"
|
| 133 |
+
elif output_format == "A":
|
| 134 |
+
output = f"Answer: The answer is {answer}."
|
| 135 |
+
|
| 136 |
+
elif output_format == "AL":
|
| 137 |
+
output = f"Answer: The answer is {answer}. BECAUSE: {solution}"
|
| 138 |
+
elif output_format == "AE":
|
| 139 |
+
output = f"Answer: The answer is {answer}. BECAUSE: {lecture}"
|
| 140 |
+
elif output_format == "ALE":
|
| 141 |
+
output = f"Answer: The answer is {answer}. BECAUSE: {lecture} {solution}"
|
| 142 |
+
elif output_format == "AEL":
|
| 143 |
+
output = f"Answer: The answer is {answer}. BECAUSE: {solution} {lecture}"
|
| 144 |
+
|
| 145 |
+
elif output_format == "LA":
|
| 146 |
+
output = f"Answer: {lecture} The answer is {answer}."
|
| 147 |
+
elif output_format == "EA":
|
| 148 |
+
output = f"Answer: {solution} The answer is {answer}."
|
| 149 |
+
elif output_format == "LEA":
|
| 150 |
+
output = f"Answer: {lecture} {solution} The answer is {answer}."
|
| 151 |
+
elif output_format == "ELA":
|
| 152 |
+
output = f"Answer: {solution} {lecture} The answer is {answer}."
|
| 153 |
+
|
| 154 |
+
text = input + output
|
| 155 |
+
text = text.replace(" ", " ").strip()
|
| 156 |
+
if text.endswith("BECAUSE:"):
|
| 157 |
+
text = text.replace("BECAUSE:", "").strip()
|
| 158 |
+
return text
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def create_one_example_gpt4(format, question, context, choice, answer, lecture, solution, test_example=True):
|
| 162 |
+
|
| 163 |
+
input_format, output_format = format.split("-")
|
| 164 |
+
|
| 165 |
+
## Inputs
|
| 166 |
+
if input_format == "CQM":
|
| 167 |
+
input = f"Context: {context}\nQuestion: {question}\nOptions: {choice}\n"
|
| 168 |
+
elif input_format == "QCM":
|
| 169 |
+
input = f"Question: {question}\nContext: {context}\nOptions: {choice}\n"
|
| 170 |
+
# upper bound experiment
|
| 171 |
+
elif input_format == "QCML":
|
| 172 |
+
input = f"Question: {question}\nContext: {context}\nOptions: {choice}\nBECAUSE: {lecture}\n"
|
| 173 |
+
elif input_format == "QCME":
|
| 174 |
+
input = f"Question: {question}\nContext: {context}\nOptions: {choice}\nBECAUSE: {solution}\n"
|
| 175 |
+
elif input_format == "QCMLE":
|
| 176 |
+
input = f"Question: {question}\nContext: {context}\nOptions: {choice}\nBECAUSE: {lecture} {solution}\n"
|
| 177 |
+
|
| 178 |
+
elif input_format == "QCLM":
|
| 179 |
+
input = f"Question: {question}\nContext: {context}\nBECAUSE: {lecture}\nOptions: {choice}\n"
|
| 180 |
+
elif input_format == "QCEM":
|
| 181 |
+
input = f"Question: {question}\nContext: {context}\nBECAUSE: {solution}\nOptions: {choice}\n"
|
| 182 |
+
elif input_format == "QCLEM":
|
| 183 |
+
input = f"Question: {question}\nContext: {context}\nBECAUSE: {lecture} {solution}\nOptions: {choice}\n"
|
| 184 |
+
|
| 185 |
+
# Outputs
|
| 186 |
+
if test_example:
|
| 187 |
+
output = "Answer:"
|
| 188 |
+
elif output_format == "A":
|
| 189 |
+
output = f"Answer: The answer is {answer}."
|
| 190 |
+
|
| 191 |
+
elif output_format == "AL":
|
| 192 |
+
output = f"Answer: The answer is {answer}. BECAUSE: {solution}"
|
| 193 |
+
elif output_format == "AE":
|
| 194 |
+
output = f"Answer: The answer is {answer}. BECAUSE: {lecture}"
|
| 195 |
+
elif output_format == "ALE":
|
| 196 |
+
output = f"Answer: The answer is {answer}. BECAUSE: {lecture} {solution}"
|
| 197 |
+
elif output_format == "AEL":
|
| 198 |
+
output = f"Answer: The answer is {answer}. BECAUSE: {solution} {lecture}"
|
| 199 |
+
|
| 200 |
+
elif output_format == "LA":
|
| 201 |
+
output = f"Answer: {lecture} The answer is {answer}."
|
| 202 |
+
elif output_format == "EA":
|
| 203 |
+
output = f"Answer: {solution} The answer is {answer}."
|
| 204 |
+
elif output_format == "LEA":
|
| 205 |
+
output = f"Answer: {lecture} {solution} The answer is {answer}."
|
| 206 |
+
elif output_format == "ELA":
|
| 207 |
+
output = f"Answer: {solution} {lecture} The answer is {answer}."
|
| 208 |
+
|
| 209 |
+
input = input.replace(" ", " ").strip()
|
| 210 |
+
output = output.replace(" ", " ").strip()
|
| 211 |
+
if output.endswith("BECAUSE:"):
|
| 212 |
+
output = output.replace("BECAUSE:", "").strip()
|
| 213 |
+
|
| 214 |
+
user_prompt = {"role": "user", "content": f"Can you explain {input}?"}
|
| 215 |
+
assistant_prompt = {"role": "assistant", "content": f"{output}"}
|
| 216 |
+
|
| 217 |
+
return user_prompt, assistant_prompt
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
def build_prompt_chatbot(problems, shot_qids, prompt_format, use_caption=False, options=["A", "B", "C", "D", "E"], is_test=False):
|
| 221 |
+
examples = {}
|
| 222 |
+
|
| 223 |
+
for qid in shot_qids:
|
| 224 |
+
question = get_question_text(problems[qid])
|
| 225 |
+
context = get_context_text(problems[qid], use_caption)
|
| 226 |
+
choice = get_choice_text(problems[qid], options)
|
| 227 |
+
answer = get_answer(problems[qid], options)
|
| 228 |
+
lecture = get_lecture_text(problems[qid]).replace("\\n", "\n")
|
| 229 |
+
solution = get_solution_text(problems[qid]).replace("\\n", "\n")
|
| 230 |
+
|
| 231 |
+
train_example = create_one_example_chatbot(prompt_format, question, context, choice, answer, lecture, solution, test_example=is_test)
|
| 232 |
+
examples[qid] = train_example
|
| 233 |
+
return examples
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
def build_prompt(problems, shot_qids, test_qid, args):
|
| 237 |
+
|
| 238 |
+
examples = []
|
| 239 |
+
|
| 240 |
+
# n-shot training examples
|
| 241 |
+
for qid in shot_qids:
|
| 242 |
+
question = get_question_text(problems[qid])
|
| 243 |
+
context = get_context_text(problems[qid], args.use_caption)
|
| 244 |
+
choice = get_choice_text(problems[qid], args.options)
|
| 245 |
+
answer = get_answer(problems[qid], args.options)
|
| 246 |
+
lecture = get_lecture_text(problems[qid])
|
| 247 |
+
solution = get_solution_text(problems[qid])
|
| 248 |
+
|
| 249 |
+
train_example = create_one_example(args.prompt_format, question, context, choice, answer, lecture, solution, test_example=False)
|
| 250 |
+
examples.append(train_example)
|
| 251 |
+
|
| 252 |
+
# test example
|
| 253 |
+
question = get_question_text(problems[test_qid])
|
| 254 |
+
context = get_context_text(problems[test_qid], args.use_caption)
|
| 255 |
+
choice = get_choice_text(problems[test_qid], args.options)
|
| 256 |
+
answer = get_answer(problems[test_qid], args.options)
|
| 257 |
+
lecture = get_lecture_text(problems[test_qid])
|
| 258 |
+
solution = get_solution_text(problems[test_qid])
|
| 259 |
+
|
| 260 |
+
test_example = create_one_example(args.prompt_format, question, context, choice, answer, lecture, solution, test_example=True)
|
| 261 |
+
examples.append(test_example)
|
| 262 |
+
|
| 263 |
+
# create the prompt input
|
| 264 |
+
prompt_input = "\n\n".join(examples)
|
| 265 |
+
|
| 266 |
+
return prompt_input
|
| 267 |
+
|
| 268 |
+
|
| 269 |
+
def build_prompt_gpt4(problems, shot_qids, test_qid, args):
|
| 270 |
+
|
| 271 |
+
prompt_array = [{"role": "system", "content": "You are a helpful assistant."}]
|
| 272 |
+
|
| 273 |
+
# n-shot training examples
|
| 274 |
+
for qid in shot_qids:
|
| 275 |
+
question = get_question_text(problems[qid])
|
| 276 |
+
context = get_context_text(problems[qid], args.use_caption)
|
| 277 |
+
choice = get_choice_text(problems[qid], args.options)
|
| 278 |
+
answer = get_answer(problems[qid], args.options)
|
| 279 |
+
lecture = get_lecture_text(problems[qid])
|
| 280 |
+
solution = get_solution_text(problems[qid])
|
| 281 |
+
|
| 282 |
+
user_prompt, assistant_prompt = create_one_example_gpt4(args.prompt_format, question, context, choice, answer, lecture, solution, test_example=False)
|
| 283 |
+
prompt_array.append(user_prompt)
|
| 284 |
+
prompt_array.append(assistant_prompt)
|
| 285 |
+
|
| 286 |
+
# test example
|
| 287 |
+
question = get_question_text(problems[test_qid])
|
| 288 |
+
context = get_context_text(problems[test_qid], args.use_caption)
|
| 289 |
+
choice = get_choice_text(problems[test_qid], args.options)
|
| 290 |
+
answer = get_answer(problems[test_qid], args.options)
|
| 291 |
+
lecture = get_lecture_text(problems[test_qid])
|
| 292 |
+
solution = get_solution_text(problems[test_qid])
|
| 293 |
+
|
| 294 |
+
user_prompt, assistant_prompt = create_one_example_gpt4(args.prompt_format, question, context, choice, answer, lecture, solution, test_example=True)
|
| 295 |
+
prompt_array.append(user_prompt)
|
| 296 |
+
prompt_array.append(assistant_prompt)
|
| 297 |
+
|
| 298 |
+
return prompt_array
|
spatial-model/VLM-3R/scripts/archived/convert_vqav2_for_submission.py
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import argparse
|
| 3 |
+
import json
|
| 4 |
+
|
| 5 |
+
from llava.eval.m4c_evaluator import EvalAIAnswerProcessor
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def parse_args():
|
| 9 |
+
parser = argparse.ArgumentParser()
|
| 10 |
+
parser.add_argument("--dir", type=str, default="./playground/data/eval/vqav2")
|
| 11 |
+
parser.add_argument("--ckpt", type=str, required=True)
|
| 12 |
+
parser.add_argument("--split", type=str, required=True)
|
| 13 |
+
return parser.parse_args()
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
if __name__ == "__main__":
|
| 17 |
+
|
| 18 |
+
args = parse_args()
|
| 19 |
+
|
| 20 |
+
src = os.path.join(args.dir, "answers", args.split, args.ckpt, "merge.jsonl")
|
| 21 |
+
test_split = os.path.join(args.dir, "llava_vqav2_mscoco_test2015.jsonl")
|
| 22 |
+
dst = os.path.join(args.dir, "answers_upload", args.split, f"{args.ckpt}.json")
|
| 23 |
+
os.makedirs(os.path.dirname(dst), exist_ok=True)
|
| 24 |
+
|
| 25 |
+
results = []
|
| 26 |
+
error_line = 0
|
| 27 |
+
for line_idx, line in enumerate(open(src)):
|
| 28 |
+
try:
|
| 29 |
+
results.append(json.loads(line))
|
| 30 |
+
except:
|
| 31 |
+
error_line += 1
|
| 32 |
+
|
| 33 |
+
results = {x["question_id"]: x["text"] for x in results}
|
| 34 |
+
test_split = [json.loads(line) for line in open(test_split)]
|
| 35 |
+
split_ids = set([x["question_id"] for x in test_split])
|
| 36 |
+
|
| 37 |
+
print(f"total results: {len(results)}, total split: {len(test_split)}, error_line: {error_line}")
|
| 38 |
+
|
| 39 |
+
all_answers = []
|
| 40 |
+
|
| 41 |
+
answer_processor = EvalAIAnswerProcessor()
|
| 42 |
+
|
| 43 |
+
for x in test_split:
|
| 44 |
+
if x["question_id"] not in results:
|
| 45 |
+
all_answers.append({"question_id": x["question_id"], "answer": ""})
|
| 46 |
+
else:
|
| 47 |
+
all_answers.append({"question_id": x["question_id"], "answer": answer_processor(results[x["question_id"]])})
|
| 48 |
+
|
| 49 |
+
with open(dst, "w") as f:
|
| 50 |
+
json.dump(all_answers, open(dst, "w"))
|
spatial-model/VLM-3R/scripts/archived/finetune_lora.sh
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
|
| 3 |
+
# Uncomment and set the following variables correspondingly to run this script:
|
| 4 |
+
|
| 5 |
+
################## VICUNA ##################
|
| 6 |
+
# PROMPT_VERSION=v1
|
| 7 |
+
# MODEL_VERSION="vicuna-v1-3-7b"
|
| 8 |
+
################## VICUNA ##################
|
| 9 |
+
|
| 10 |
+
################## LLaMA-2 ##################
|
| 11 |
+
# PROMPT_VERSION="llava_llama_2"
|
| 12 |
+
# MODEL_VERSION="llama-2-7b-chat"
|
| 13 |
+
################## LLaMA-2 ##################
|
| 14 |
+
|
| 15 |
+
deepspeed llava/train/train_mem.py \
|
| 16 |
+
--deepspeed ./scripts/zero2.json \
|
| 17 |
+
--lora_enable True \
|
| 18 |
+
--model_name_or_path ./checkpoints/$MODEL_VERSION \
|
| 19 |
+
--version $PROMPT_VERSION \
|
| 20 |
+
--data_path ./playground/data/llava_instruct_80k.json \
|
| 21 |
+
--image_folder /path/to/coco/train2017 \
|
| 22 |
+
--vision_tower openai/clip-vit-large-patch14 \
|
| 23 |
+
--pretrain_mm_mlp_adapter ./checkpoints/llava-$MODEL_VERSION-pretrain/mm_projector.bin \
|
| 24 |
+
--mm_vision_select_layer -2 \
|
| 25 |
+
--mm_use_im_start_end False \
|
| 26 |
+
--mm_use_im_patch_token False \
|
| 27 |
+
--bf16 True \
|
| 28 |
+
--output_dir ./checkpoints/llava-$MODEL_VERSION-finetune_lora \
|
| 29 |
+
--num_train_epochs 1 \
|
| 30 |
+
--per_device_train_batch_size 16 \
|
| 31 |
+
--per_device_eval_batch_size 4 \
|
| 32 |
+
--gradient_accumulation_steps 1 \
|
| 33 |
+
--evaluation_strategy "no" \
|
| 34 |
+
--save_strategy "steps" \
|
| 35 |
+
--save_steps 50000 \
|
| 36 |
+
--save_total_limit 1 \
|
| 37 |
+
--learning_rate 2e-5 \
|
| 38 |
+
--weight_decay 0. \
|
| 39 |
+
--warmup_ratio 0.03 \
|
| 40 |
+
--lr_scheduler_type "cosine" \
|
| 41 |
+
--logging_steps 1 \
|
| 42 |
+
--tf32 True \
|
| 43 |
+
--model_max_length 2048 \
|
| 44 |
+
--gradient_checkpointing True \
|
| 45 |
+
--lazy_preprocess True \
|
| 46 |
+
--dataloader_num_workers 16 \
|
| 47 |
+
--report_to wandb
|
spatial-model/VLM-3R/scripts/archived/finetune_mixtral_1.5.sh
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
dataset_name=$1
|
| 3 |
+
|
| 4 |
+
cd /mnt/bn/vl-research/workspace/yhzhang/LLaVA
|
| 5 |
+
|
| 6 |
+
# Install yolk3k if not installed
|
| 7 |
+
if ! pip show yolk3k > /dev/null 2>&1; then
|
| 8 |
+
pip install yolk3k
|
| 9 |
+
fi
|
| 10 |
+
|
| 11 |
+
# Get the installed version of transformers
|
| 12 |
+
installed_version=$(pip show transformers | grep Version | cut -d ' ' -f 2)
|
| 13 |
+
|
| 14 |
+
# Get the latest version of transformers from PyPI
|
| 15 |
+
latest_version=$(yolk -V transformers | cut -d ' ' -f 2)
|
| 16 |
+
|
| 17 |
+
# Check if the installed version is not the latest
|
| 18 |
+
if [ "$installed_version" != "$latest_version" ]; then
|
| 19 |
+
pip install -U transformers
|
| 20 |
+
fi
|
| 21 |
+
|
| 22 |
+
# Get the installed version of deepspeed
|
| 23 |
+
installed_version=$(pip show deepspeed | grep Version | cut -d ' ' -f 2)
|
| 24 |
+
|
| 25 |
+
# Get the latest version of deepspeed from PyPI
|
| 26 |
+
# latest_version=$(yolk -V deepspeed | cut -d ' ' -f 2)
|
| 27 |
+
|
| 28 |
+
# Check if the installed version is not the latest
|
| 29 |
+
if [ "$installed_version" != "0.12.2" ]; then
|
| 30 |
+
pip install deepspeed==0.12.2
|
| 31 |
+
fi
|
| 32 |
+
|
| 33 |
+
# Install yolk3k if not installed
|
| 34 |
+
if ! pip show flash-attn > /dev/null 2>&1; then
|
| 35 |
+
pip install flash-attn --no-build-isolation
|
| 36 |
+
fi
|
| 37 |
+
|
| 38 |
+
################## MISTRAL ##################
|
| 39 |
+
PROMPT_VERSION=mistral_instruct
|
| 40 |
+
MODEL_VERSION="Mistral-7B-Instruct-v0.2"
|
| 41 |
+
################## MISTRAL ##################
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
################## project ##################
|
| 45 |
+
PROJECT_NAME="ds_llava-Mistral-7B-Instruct-v0.2-mlp2x_gelu-pretrain_blip558k_plain"
|
| 46 |
+
|
| 47 |
+
################## data ##################
|
| 48 |
+
DATA_NAME=$dataset_name
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
# wandb configure
|
| 52 |
+
export WANDB_API_KEY="03fc62d68025c9498cf6493432551badd7d4f953"
|
| 53 |
+
wandb login $WANDB_API_KEY
|
| 54 |
+
|
| 55 |
+
export WANDB_NAME=$PROJECT_NAME--$MODEL_VERSION--$DATA_NAME
|
| 56 |
+
|
| 57 |
+
export WANDB_PROJECT=LLaVA_Mixtral
|
| 58 |
+
|
| 59 |
+
export WANDB_MODE=online
|
| 60 |
+
|
| 61 |
+
wandb online
|
| 62 |
+
|
| 63 |
+
deepspeed --master_port 26000 \
|
| 64 |
+
llava/train/train_mem.py \
|
| 65 |
+
--deepspeed ./scripts/zero2.json \
|
| 66 |
+
--model_name_or_path ./checkpoints/$MODEL_VERSION \
|
| 67 |
+
--version $PROMPT_VERSION \
|
| 68 |
+
--data_path ./playground/data/$DATA_NAME.json \
|
| 69 |
+
--image_folder /mnt/bn/vl-research/workspace/boli01/data/playground/data \
|
| 70 |
+
--vision_tower openai/clip-vit-large-patch14 \
|
| 71 |
+
--pretrain_mm_mlp_adapter ./checkpoints/$PROJECT_NAME/mm_projector.bin \
|
| 72 |
+
--mm_vision_select_layer -2 \
|
| 73 |
+
--mm_projector_type mlp2x_gelu \
|
| 74 |
+
--mm_use_im_start_end False \
|
| 75 |
+
--mm_use_im_patch_token False \
|
| 76 |
+
--bf16 True \
|
| 77 |
+
--output_dir ./checkpoints/llava--$PROJECT_NAME--$MODEL_VERSION--$DATA_NAME--finetune \
|
| 78 |
+
--num_train_epochs 1 \
|
| 79 |
+
--per_device_train_batch_size 16 \
|
| 80 |
+
--per_device_eval_batch_size 4 \
|
| 81 |
+
--gradient_accumulation_steps 1 \
|
| 82 |
+
--evaluation_strategy "no" \
|
| 83 |
+
--save_strategy "steps" \
|
| 84 |
+
--save_steps 50000 \
|
| 85 |
+
--save_total_limit 1 \
|
| 86 |
+
--learning_rate 2e-5 \
|
| 87 |
+
--weight_decay 0. \
|
| 88 |
+
--warmup_ratio 0.03 \
|
| 89 |
+
--lr_scheduler_type "cosine" \
|
| 90 |
+
--logging_steps 1 \
|
| 91 |
+
--tf32 True \
|
| 92 |
+
--model_max_length 2048 \
|
| 93 |
+
--gradient_checkpointing True \
|
| 94 |
+
--dataloader_num_workers 16 \
|
| 95 |
+
--lazy_preprocess True
|
| 96 |
+
# --report_to wandb
|
spatial-model/VLM-3R/scripts/archived/finetune_mixtral_1.6_336px_anyres_freeze_vision.sh
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
dataset_name=$1
|
| 3 |
+
|
| 4 |
+
cd /mnt/bn/vl-research/workspace/yhzhang/LLaVA
|
| 5 |
+
|
| 6 |
+
# Install yolk3k if not installed
|
| 7 |
+
if ! pip show yolk3k > /dev/null 2>&1; then
|
| 8 |
+
pip install yolk3k
|
| 9 |
+
fi
|
| 10 |
+
|
| 11 |
+
pip install pydantic
|
| 12 |
+
|
| 13 |
+
# Get the installed version of transformers
|
| 14 |
+
installed_version=$(pip show transformers | grep Version | cut -d ' ' -f 2)
|
| 15 |
+
|
| 16 |
+
# Get the latest version of transformers from PyPI
|
| 17 |
+
latest_version=$(yolk -V transformers | cut -d ' ' -f 2)
|
| 18 |
+
|
| 19 |
+
# Check if the installed version is not the latest
|
| 20 |
+
if [ "$installed_version" != "4.36.2" ]; then
|
| 21 |
+
pip install transformers==4.36.2
|
| 22 |
+
fi
|
| 23 |
+
|
| 24 |
+
# Get the installed version of deepspeed
|
| 25 |
+
installed_version=$(pip show deepspeed | grep Version | cut -d ' ' -f 2)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
# Check if the installed version is not the latest
|
| 29 |
+
if [ "$installed_version" != "0.12.2" ]; then
|
| 30 |
+
pip install deepspeed==0.12.2
|
| 31 |
+
fi
|
| 32 |
+
|
| 33 |
+
# Install flash-atten if not installed
|
| 34 |
+
if ! pip show flash-attn > /dev/null 2>&1; then
|
| 35 |
+
pip install flash-attn --no-build-isolation
|
| 36 |
+
fi
|
| 37 |
+
|
| 38 |
+
################## MISTRAL ##################
|
| 39 |
+
PROMPT_VERSION=mistral_instruct
|
| 40 |
+
MODEL_VERSION="Mistral-7B-Instruct-v0.2"
|
| 41 |
+
################## MISTRAL ##################
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
################## project ##################
|
| 45 |
+
PROJECT_NAME="ds_llava-Mistral-7B-Instruct-v0.2-clip_large_336px-mlp2x_gelu-pretrain_blip558k_plain"
|
| 46 |
+
|
| 47 |
+
################## data ##################
|
| 48 |
+
DATA_NAME=$dataset_name
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
# wandb configure
|
| 52 |
+
export WANDB_API_KEY=e464cc107357c7b38e87f239bc3eb2ce5fb73c7c
|
| 53 |
+
export WANDB_PROJECT=llava
|
| 54 |
+
|
| 55 |
+
export WANDB_NAME=$PROJECT_NAME--$DATA_NAME--336px--unfreeze--anyres--sft
|
| 56 |
+
|
| 57 |
+
export WANDB_MODE=online
|
| 58 |
+
|
| 59 |
+
wandb online
|
| 60 |
+
|
| 61 |
+
deepspeed --master_port 26000 \
|
| 62 |
+
llava/train/train_mem.py \
|
| 63 |
+
--deepspeed ./scripts/zero3.json \
|
| 64 |
+
--model_name_or_path ./checkpoints/$MODEL_VERSION \
|
| 65 |
+
--version $PROMPT_VERSION \
|
| 66 |
+
--data_path ./playground/data/$DATA_NAME.json \
|
| 67 |
+
--image_folder /mnt/bn/vl-research/workspace/boli01/data/playground/data \
|
| 68 |
+
--vision_tower openai/clip-vit-large-patch14-336 \
|
| 69 |
+
--pretrain_mm_mlp_adapter /mnt/bn/vl-research/workspace/project/2023/LLaVA/checkpoints/ds_llava-Mistral-7B-Instruct-v0.2-clip_large_336px-mlp2x_gelu-pretrain_blip558k_plain/mm_projector.bin \
|
| 70 |
+
--mm_vision_select_layer -2 \
|
| 71 |
+
--mm_projector_type mlp2x_gelu \
|
| 72 |
+
--mm_use_im_start_end False \
|
| 73 |
+
--mm_use_im_patch_token False \
|
| 74 |
+
--group_by_modality_length True \
|
| 75 |
+
--image_aspect_ratio anyres \
|
| 76 |
+
--image_grid_pinpoints "[(336, 672), (672, 336), (672, 672), (1008, 336), (336, 1008)]" \
|
| 77 |
+
--mm_patch_merge_type spatial_unpad \
|
| 78 |
+
--bf16 True \
|
| 79 |
+
--output_dir ./checkpoints/$PROJECT_NAME--$DATA_NAME--336px--anyres--unfreeze--sft \
|
| 80 |
+
--num_train_epochs 1 \
|
| 81 |
+
--per_device_train_batch_size 16 \
|
| 82 |
+
--per_device_eval_batch_size 4 \
|
| 83 |
+
--gradient_accumulation_steps 1 \
|
| 84 |
+
--evaluation_strategy "no" \
|
| 85 |
+
--save_strategy "steps" \
|
| 86 |
+
--save_steps 50000 \
|
| 87 |
+
--save_total_limit 1 \
|
| 88 |
+
--learning_rate 2e-5 \
|
| 89 |
+
--weight_decay 0. \
|
| 90 |
+
--warmup_ratio 0.03 \
|
| 91 |
+
--lr_scheduler_type "cosine" \
|
| 92 |
+
--logging_steps 1 \
|
| 93 |
+
--tf32 True \
|
| 94 |
+
--model_max_length 2048 \
|
| 95 |
+
--gradient_checkpointing True \
|
| 96 |
+
--dataloader_num_workers 16 \
|
| 97 |
+
|
spatial-model/VLM-3R/scripts/archived/finetune_mixtral_copy.sh
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
|
| 3 |
+
cd /mnt/bn/vl-research/workspace/boli01/zzzprojects/LLaVA
|
| 4 |
+
|
| 5 |
+
# Install yolk3k if not installed
|
| 6 |
+
if ! pip show yolk3k > /dev/null 2>&1; then
|
| 7 |
+
pip install yolk3k
|
| 8 |
+
fi
|
| 9 |
+
|
| 10 |
+
# Get the installed version of transformers
|
| 11 |
+
installed_version=$(pip show transformers | grep Version | cut -d ' ' -f 2)
|
| 12 |
+
|
| 13 |
+
# Get the latest version of transformers from PyPI
|
| 14 |
+
latest_version=$(yolk -V transformers | cut -d ' ' -f 2)
|
| 15 |
+
|
| 16 |
+
# Check if the installed version is not the latest
|
| 17 |
+
if [ "$installed_version" != "$latest_version" ]; then
|
| 18 |
+
pip install -U transformers
|
| 19 |
+
fi
|
| 20 |
+
|
| 21 |
+
# Get the installed version of deepspeed
|
| 22 |
+
installed_version=$(pip show deepspeed | grep Version | cut -d ' ' -f 2)
|
| 23 |
+
|
| 24 |
+
# Get the latest version of deepspeed from PyPI
|
| 25 |
+
latest_version=$(yolk -V deepspeed | cut -d ' ' -f 2)
|
| 26 |
+
|
| 27 |
+
# Check if the installed version is not the latest
|
| 28 |
+
if [ "$installed_version" != "$latest_version" ]; then
|
| 29 |
+
pip install deepspeed==0.12.2
|
| 30 |
+
fi
|
| 31 |
+
|
| 32 |
+
# Install yolk3k if not installed
|
| 33 |
+
if ! pip show flash-attn > /dev/null 2>&1; then
|
| 34 |
+
pip install flash-attn --no-build-isolation
|
| 35 |
+
fi
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
################## MISTRAL ##################
|
| 39 |
+
PROMPT_VERSION=mistral_instruct
|
| 40 |
+
MODEL_VERSION="Mistral-7B-Instruct-v0.2"
|
| 41 |
+
################## VICUNA ##################
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
################## project ##################
|
| 45 |
+
PROJECT_NAME="ds_llava-Mistral-7B-Instruct-v0.2-mlp2x_gelu-pretrain_blip558k_plain"
|
| 46 |
+
|
| 47 |
+
################## data ##################
|
| 48 |
+
DATA_NAME="llava_instruct_150k"
|
| 49 |
+
|
| 50 |
+
# wandb configure
|
| 51 |
+
export WANDB_API_KEY="03fc62d68025c9498cf6493432551badd7d4f953"
|
| 52 |
+
wandb login $WANDB_API_KEY
|
| 53 |
+
|
| 54 |
+
export WANDB_NAME=$PROJECT_NAME--$MODEL_VERSION--$DATA_NAME
|
| 55 |
+
|
| 56 |
+
export WANDB_PROJECT=LLaVA_Mixtral
|
| 57 |
+
|
| 58 |
+
export WANDB_MODE=online
|
| 59 |
+
|
| 60 |
+
wandb online
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
deepspeed --master_port 26000 \
|
| 64 |
+
llava/train/train_mem.py \
|
| 65 |
+
--deepspeed ./scripts/zero2.json \
|
| 66 |
+
--model_name_or_path ./checkpoints/$MODEL_VERSION \
|
| 67 |
+
--version $PROMPT_VERSION \
|
| 68 |
+
--data_path ./playground/data/$DATA_NAME.json \
|
| 69 |
+
--image_folder /mnt/bn/vl-research/workspace/boli01/data/playground/data/coco/train2017 \
|
| 70 |
+
--vision_tower openai/clip-vit-large-patch14 \
|
| 71 |
+
--pretrain_mm_mlp_adapter ./checkpoints/$PROJECT_NAME/mm_projector.bin \
|
| 72 |
+
--mm_vision_select_layer -2 \
|
| 73 |
+
--mm_projector_type mlp2x_gelu \
|
| 74 |
+
--mm_use_im_start_end False \
|
| 75 |
+
--mm_use_im_patch_token False \
|
| 76 |
+
--bf16 True \
|
| 77 |
+
--output_dir ./checkpoints/llava--$PROJECT_NAME--$MODEL_VERSION--$DATA_NAME--finetune \
|
| 78 |
+
--num_train_epochs 1 \
|
| 79 |
+
--per_device_train_batch_size 16 \
|
| 80 |
+
--per_device_eval_batch_size 4 \
|
| 81 |
+
--gradient_accumulation_steps 1 \
|
| 82 |
+
--evaluation_strategy "no" \
|
| 83 |
+
--save_strategy "steps" \
|
| 84 |
+
--save_steps 50000 \
|
| 85 |
+
--save_total_limit 1 \
|
| 86 |
+
--learning_rate 2e-5 \
|
| 87 |
+
--weight_decay 0. \
|
| 88 |
+
--warmup_ratio 0.03 \
|
| 89 |
+
--lr_scheduler_type "cosine" \
|
| 90 |
+
--logging_steps 1 \
|
| 91 |
+
--tf32 True \
|
| 92 |
+
--model_max_length 2048 \
|
| 93 |
+
--gradient_checkpointing True \
|
| 94 |
+
--dataloader_num_workers 16 \
|
| 95 |
+
--lazy_preprocess True \
|
| 96 |
+
--report_to wandb
|
spatial-model/VLM-3R/scripts/archived/finetune_qlora.sh
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
|
| 3 |
+
# Uncomment and set the following variables correspondingly to run this script:
|
| 4 |
+
|
| 5 |
+
################## VICUNA ##################
|
| 6 |
+
# PROMPT_VERSION=v1
|
| 7 |
+
# MODEL_VERSION="vicuna-v1-3-7b"
|
| 8 |
+
################## VICUNA ##################
|
| 9 |
+
|
| 10 |
+
################## LLaMA-2 ##################
|
| 11 |
+
# PROMPT_VERSION="llava_llama_2"
|
| 12 |
+
# MODEL_VERSION="llama-2-7b-chat"
|
| 13 |
+
################## LLaMA-2 ##################
|
| 14 |
+
|
| 15 |
+
deepspeed llava/train/train_mem.py \
|
| 16 |
+
--deepspeed ./scripts/zero2.json \
|
| 17 |
+
--lora_enable True \
|
| 18 |
+
--bits 4 \
|
| 19 |
+
--model_name_or_path ./checkpoints/$MODEL_VERSION \
|
| 20 |
+
--version $PROMPT_VERSION \
|
| 21 |
+
--data_path ./playground/data/llava_instruct_80k.json \
|
| 22 |
+
--image_folder /path/to/coco/train2017 \
|
| 23 |
+
--vision_tower openai/clip-vit-large-patch14 \
|
| 24 |
+
--pretrain_mm_mlp_adapter ./checkpoints/llava-$MODEL_VERSION-pretrain/mm_projector.bin \
|
| 25 |
+
--mm_vision_select_layer -2 \
|
| 26 |
+
--mm_use_im_start_end False \
|
| 27 |
+
--mm_use_im_patch_token False \
|
| 28 |
+
--bf16 True \
|
| 29 |
+
--output_dir ./checkpoints/llava-$MODEL_VERSION-finetune_lora \
|
| 30 |
+
--num_train_epochs 1 \
|
| 31 |
+
--per_device_train_batch_size 16 \
|
| 32 |
+
--per_device_eval_batch_size 4 \
|
| 33 |
+
--gradient_accumulation_steps 1 \
|
| 34 |
+
--evaluation_strategy "no" \
|
| 35 |
+
--save_strategy "steps" \
|
| 36 |
+
--save_steps 50000 \
|
| 37 |
+
--save_total_limit 1 \
|
| 38 |
+
--learning_rate 2e-5 \
|
| 39 |
+
--weight_decay 0. \
|
| 40 |
+
--warmup_ratio 0.03 \
|
| 41 |
+
--lr_scheduler_type "cosine" \
|
| 42 |
+
--logging_steps 1 \
|
| 43 |
+
--tf32 True \
|
| 44 |
+
--model_max_length 2048 \
|
| 45 |
+
--gradient_checkpointing True \
|
| 46 |
+
--lazy_preprocess True \
|
| 47 |
+
--dataloader_num_workers 16 \
|
| 48 |
+
--report_to wandb
|
spatial-model/VLM-3R/scripts/archived/pretrain.sh
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
|
| 3 |
+
# Uncomment and set the following variables correspondingly to run this script:
|
| 4 |
+
|
| 5 |
+
# MODEL_VERSION=vicuna-v1-3-7b
|
| 6 |
+
# MODEL_VERSION=llama-2-7b-chat
|
| 7 |
+
|
| 8 |
+
########### DO NOT CHANGE ###########
|
| 9 |
+
########### USE THIS FOR BOTH ###########
|
| 10 |
+
PROMPT_VERSION=plain
|
| 11 |
+
########### DO NOT CHANGE ###########
|
| 12 |
+
|
| 13 |
+
deepspeed llava/train/train_mem.py \
|
| 14 |
+
--deepspeed ./scripts/zero2.json \
|
| 15 |
+
--model_name_or_path ./checkpoints/$MODEL_VERSION \
|
| 16 |
+
--version $PROMPT_VERSION \
|
| 17 |
+
--data_path /path/to/pretrain_data.json \
|
| 18 |
+
--image_folder /path/to/images \
|
| 19 |
+
--vision_tower openai/clip-vit-large-patch14 \
|
| 20 |
+
--tune_mm_mlp_adapter True \
|
| 21 |
+
--mm_vision_select_layer -2 \
|
| 22 |
+
--mm_use_im_start_end False \
|
| 23 |
+
--mm_use_im_patch_token False \
|
| 24 |
+
--bf16 True \
|
| 25 |
+
--output_dir ./checkpoints/llava-$MODEL_VERSION-pretrain \
|
| 26 |
+
--num_train_epochs 1 \
|
| 27 |
+
--per_device_train_batch_size 16 \
|
| 28 |
+
--per_device_eval_batch_size 4 \
|
| 29 |
+
--gradient_accumulation_steps 1 \
|
| 30 |
+
--evaluation_strategy "no" \
|
| 31 |
+
--save_strategy "steps" \
|
| 32 |
+
--save_steps 24000 \
|
| 33 |
+
--learning_rate 2e-3 \
|
| 34 |
+
--weight_decay 0. \
|
| 35 |
+
--warmup_ratio 0.03 \
|
| 36 |
+
--lr_scheduler_type "cosine" \
|
| 37 |
+
--logging_steps 1 \
|
| 38 |
+
--tf32 True \
|
| 39 |
+
--model_max_length 2048 \
|
| 40 |
+
--gradient_checkpointing True \
|
| 41 |
+
--dataloader_num_workers 16 \
|
| 42 |
+
--lazy_preprocess True \
|
| 43 |
+
--report_to wandb
|