├── ImageBind ├── models │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-310.pyc │ │ ├── __init__.cpython-38.pyc │ │ ├── __init__.cpython-39.pyc │ │ ├── helpers.cpython-310.pyc │ │ ├── helpers.cpython-38.pyc │ │ ├── helpers.cpython-39.pyc │ │ ├── transformer.cpython-38.pyc │ │ ├── transformer.cpython-39.pyc │ │ ├── transformer.cpython-310.pyc │ │ ├── imagebind_model.cpython-310.pyc │ │ ├── imagebind_model.cpython-38.pyc │ │ ├── imagebind_model.cpython-39.pyc │ │ ├── multimodal_preprocessors.cpython-38.pyc │ │ ├── multimodal_preprocessors.cpython-39.pyc │ │ └── multimodal_preprocessors.cpython-310.pyc │ ├── helpers.py │ ├── transformer.py │ └── imagebind_model.py ├── __pycache__ │ ├── data.cpython-310.pyc │ ├── data.cpython-37.pyc │ ├── data.cpython-38.pyc │ └── data.cpython-39.pyc ├── bpe │ └── bpe_simple_vocab_16e6.txt.gz ├── requirements.txt ├── demo.py ├── CODE_OF_CONDUCT.md ├── README.md ├── model_card.md ├── data.py └── LICENSE ├── llama ├── __pycache__ │ ├── llama_adapter.cpython-39.pyc.139707016249184 │ ├── llama_adapter.cpython-39.pyc.139860232032096 │ ├── EVA02.cpython-39.pyc │ ├── LViT.cpython-310.pyc │ ├── LViT.cpython-39.pyc │ ├── Vit.cpython-310.pyc │ ├── Vit.cpython-39.pyc │ ├── llama.cpython-38.pyc │ ├── llama.cpython-39.pyc │ ├── utils.cpython-38.pyc │ ├── utils.cpython-39.pyc │ ├── Config.cpython-310.pyc │ ├── Config.cpython-39.pyc │ ├── llama.cpython-310.pyc │ ├── utils.cpython-310.pyc │ ├── __init__.cpython-310.pyc │ ├── __init__.cpython-38.pyc │ ├── __init__.cpython-39.pyc │ ├── pixlevel.cpython-310.pyc │ ├── pixlevel.cpython-39.pyc │ ├── tokenizer.cpython-310.pyc │ ├── tokenizer.cpython-38.pyc │ ├── tokenizer.cpython-39.pyc │ ├── llama_adapter.cpython-310.pyc │ ├── llama_adapter.cpython-38.pyc │ └── llama_adapter.cpython-39.pyc ├── __init__.py ├── EVA02.py ├── tokenizer.py ├── pixlevel.py ├── Config.py ├── utils.py ├── LViT.py ├── Vit.py └── llama.py ├── VisionUnite_Manuscript.jpg ├── util ├── __pycache__ │ ├── misc.cpython-310.pyc │ ├── misc.cpython-39.pyc │ ├── lr_sched.cpython-39.pyc │ └── lr_sched.cpython-310.pyc ├── lr_sched.py ├── crop.py ├── lars.py ├── datasets.py ├── lr_decay.py ├── pos_embed.py └── misc.py ├── requirements.txt ├── exps └── train.sh ├── LICENSE ├── convert_ckpt.py ├── gradio_app.py ├── README.md ├── fundus_prep.py ├── engine_pretrain.py ├── demo.py └── main_pretrain.py /ImageBind/models/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /llama/__pycache__/llama_adapter.cpython-39.pyc.139707016249184: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /llama/__pycache__/llama_adapter.cpython-39.pyc.139860232032096: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /VisionUnite_Manuscript.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HUANGLIZI/VisionUnite/HEAD/VisionUnite_Manuscript.jpg -------------------------------------------------------------------------------- /llama/__pycache__/EVA02.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HUANGLIZI/VisionUnite/HEAD/llama/__pycache__/EVA02.cpython-39.pyc -------------------------------------------------------------------------------- /llama/__pycache__/LViT.cpython-310.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HUANGLIZI/VisionUnite/HEAD/llama/__pycache__/LViT.cpython-310.pyc -------------------------------------------------------------------------------- /llama/__pycache__/LViT.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HUANGLIZI/VisionUnite/HEAD/llama/__pycache__/LViT.cpython-39.pyc -------------------------------------------------------------------------------- /llama/__pycache__/Vit.cpython-310.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HUANGLIZI/VisionUnite/HEAD/llama/__pycache__/Vit.cpython-310.pyc -------------------------------------------------------------------------------- /llama/__pycache__/Vit.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HUANGLIZI/VisionUnite/HEAD/llama/__pycache__/Vit.cpython-39.pyc -------------------------------------------------------------------------------- /llama/__pycache__/llama.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HUANGLIZI/VisionUnite/HEAD/llama/__pycache__/llama.cpython-38.pyc -------------------------------------------------------------------------------- /llama/__pycache__/llama.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HUANGLIZI/VisionUnite/HEAD/llama/__pycache__/llama.cpython-39.pyc -------------------------------------------------------------------------------- /llama/__pycache__/utils.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HUANGLIZI/VisionUnite/HEAD/llama/__pycache__/utils.cpython-38.pyc -------------------------------------------------------------------------------- /llama/__pycache__/utils.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HUANGLIZI/VisionUnite/HEAD/llama/__pycache__/utils.cpython-39.pyc -------------------------------------------------------------------------------- /util/__pycache__/misc.cpython-310.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HUANGLIZI/VisionUnite/HEAD/util/__pycache__/misc.cpython-310.pyc -------------------------------------------------------------------------------- /util/__pycache__/misc.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HUANGLIZI/VisionUnite/HEAD/util/__pycache__/misc.cpython-39.pyc -------------------------------------------------------------------------------- /llama/__pycache__/Config.cpython-310.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HUANGLIZI/VisionUnite/HEAD/llama/__pycache__/Config.cpython-310.pyc -------------------------------------------------------------------------------- /llama/__pycache__/Config.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HUANGLIZI/VisionUnite/HEAD/llama/__pycache__/Config.cpython-39.pyc -------------------------------------------------------------------------------- /llama/__pycache__/llama.cpython-310.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HUANGLIZI/VisionUnite/HEAD/llama/__pycache__/llama.cpython-310.pyc -------------------------------------------------------------------------------- /llama/__pycache__/utils.cpython-310.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HUANGLIZI/VisionUnite/HEAD/llama/__pycache__/utils.cpython-310.pyc -------------------------------------------------------------------------------- /util/__pycache__/lr_sched.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HUANGLIZI/VisionUnite/HEAD/util/__pycache__/lr_sched.cpython-39.pyc -------------------------------------------------------------------------------- /ImageBind/__pycache__/data.cpython-310.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HUANGLIZI/VisionUnite/HEAD/ImageBind/__pycache__/data.cpython-310.pyc -------------------------------------------------------------------------------- /ImageBind/__pycache__/data.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HUANGLIZI/VisionUnite/HEAD/ImageBind/__pycache__/data.cpython-37.pyc -------------------------------------------------------------------------------- /ImageBind/__pycache__/data.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HUANGLIZI/VisionUnite/HEAD/ImageBind/__pycache__/data.cpython-38.pyc -------------------------------------------------------------------------------- /ImageBind/__pycache__/data.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HUANGLIZI/VisionUnite/HEAD/ImageBind/__pycache__/data.cpython-39.pyc -------------------------------------------------------------------------------- /ImageBind/bpe/bpe_simple_vocab_16e6.txt.gz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HUANGLIZI/VisionUnite/HEAD/ImageBind/bpe/bpe_simple_vocab_16e6.txt.gz -------------------------------------------------------------------------------- /llama/__pycache__/__init__.cpython-310.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HUANGLIZI/VisionUnite/HEAD/llama/__pycache__/__init__.cpython-310.pyc -------------------------------------------------------------------------------- /llama/__pycache__/__init__.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HUANGLIZI/VisionUnite/HEAD/llama/__pycache__/__init__.cpython-38.pyc -------------------------------------------------------------------------------- /llama/__pycache__/__init__.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HUANGLIZI/VisionUnite/HEAD/llama/__pycache__/__init__.cpython-39.pyc -------------------------------------------------------------------------------- /llama/__pycache__/pixlevel.cpython-310.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HUANGLIZI/VisionUnite/HEAD/llama/__pycache__/pixlevel.cpython-310.pyc -------------------------------------------------------------------------------- /llama/__pycache__/pixlevel.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HUANGLIZI/VisionUnite/HEAD/llama/__pycache__/pixlevel.cpython-39.pyc -------------------------------------------------------------------------------- /llama/__pycache__/tokenizer.cpython-310.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HUANGLIZI/VisionUnite/HEAD/llama/__pycache__/tokenizer.cpython-310.pyc -------------------------------------------------------------------------------- /llama/__pycache__/tokenizer.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HUANGLIZI/VisionUnite/HEAD/llama/__pycache__/tokenizer.cpython-38.pyc -------------------------------------------------------------------------------- /llama/__pycache__/tokenizer.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HUANGLIZI/VisionUnite/HEAD/llama/__pycache__/tokenizer.cpython-39.pyc -------------------------------------------------------------------------------- /util/__pycache__/lr_sched.cpython-310.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HUANGLIZI/VisionUnite/HEAD/util/__pycache__/lr_sched.cpython-310.pyc -------------------------------------------------------------------------------- /llama/__pycache__/llama_adapter.cpython-310.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HUANGLIZI/VisionUnite/HEAD/llama/__pycache__/llama_adapter.cpython-310.pyc -------------------------------------------------------------------------------- /llama/__pycache__/llama_adapter.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HUANGLIZI/VisionUnite/HEAD/llama/__pycache__/llama_adapter.cpython-38.pyc -------------------------------------------------------------------------------- /llama/__pycache__/llama_adapter.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HUANGLIZI/VisionUnite/HEAD/llama/__pycache__/llama_adapter.cpython-39.pyc -------------------------------------------------------------------------------- /ImageBind/models/__pycache__/__init__.cpython-310.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HUANGLIZI/VisionUnite/HEAD/ImageBind/models/__pycache__/__init__.cpython-310.pyc -------------------------------------------------------------------------------- /ImageBind/models/__pycache__/__init__.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HUANGLIZI/VisionUnite/HEAD/ImageBind/models/__pycache__/__init__.cpython-38.pyc -------------------------------------------------------------------------------- /ImageBind/models/__pycache__/__init__.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HUANGLIZI/VisionUnite/HEAD/ImageBind/models/__pycache__/__init__.cpython-39.pyc -------------------------------------------------------------------------------- /ImageBind/models/__pycache__/helpers.cpython-310.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HUANGLIZI/VisionUnite/HEAD/ImageBind/models/__pycache__/helpers.cpython-310.pyc -------------------------------------------------------------------------------- /ImageBind/models/__pycache__/helpers.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HUANGLIZI/VisionUnite/HEAD/ImageBind/models/__pycache__/helpers.cpython-38.pyc -------------------------------------------------------------------------------- /ImageBind/models/__pycache__/helpers.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HUANGLIZI/VisionUnite/HEAD/ImageBind/models/__pycache__/helpers.cpython-39.pyc -------------------------------------------------------------------------------- /ImageBind/models/__pycache__/transformer.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HUANGLIZI/VisionUnite/HEAD/ImageBind/models/__pycache__/transformer.cpython-38.pyc -------------------------------------------------------------------------------- /ImageBind/models/__pycache__/transformer.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HUANGLIZI/VisionUnite/HEAD/ImageBind/models/__pycache__/transformer.cpython-39.pyc -------------------------------------------------------------------------------- /llama/__init__.py: -------------------------------------------------------------------------------- 1 | from .llama import ModelArgs, Transformer 2 | from .tokenizer import Tokenizer 3 | from .llama_adapter import * 4 | from .utils import format_prompt -------------------------------------------------------------------------------- /ImageBind/models/__pycache__/transformer.cpython-310.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HUANGLIZI/VisionUnite/HEAD/ImageBind/models/__pycache__/transformer.cpython-310.pyc -------------------------------------------------------------------------------- /ImageBind/models/__pycache__/imagebind_model.cpython-310.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HUANGLIZI/VisionUnite/HEAD/ImageBind/models/__pycache__/imagebind_model.cpython-310.pyc -------------------------------------------------------------------------------- /ImageBind/models/__pycache__/imagebind_model.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HUANGLIZI/VisionUnite/HEAD/ImageBind/models/__pycache__/imagebind_model.cpython-38.pyc -------------------------------------------------------------------------------- /ImageBind/models/__pycache__/imagebind_model.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HUANGLIZI/VisionUnite/HEAD/ImageBind/models/__pycache__/imagebind_model.cpython-39.pyc -------------------------------------------------------------------------------- /ImageBind/models/__pycache__/multimodal_preprocessors.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HUANGLIZI/VisionUnite/HEAD/ImageBind/models/__pycache__/multimodal_preprocessors.cpython-38.pyc -------------------------------------------------------------------------------- /ImageBind/models/__pycache__/multimodal_preprocessors.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HUANGLIZI/VisionUnite/HEAD/ImageBind/models/__pycache__/multimodal_preprocessors.cpython-39.pyc -------------------------------------------------------------------------------- /ImageBind/models/__pycache__/multimodal_preprocessors.cpython-310.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HUANGLIZI/VisionUnite/HEAD/ImageBind/models/__pycache__/multimodal_preprocessors.cpython-310.pyc -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | --extra-index-url https://download.pytorch.org/whl/cu113 2 | torch==1.13.0 3 | torchvision==0.14.0 4 | torchaudio==0.13.0 5 | pytorchvideo @ git+https://github.com/facebookresearch/pytorchvideo.git@28fe037d212663c6a24f373b94cc5d478c8c1a1d 6 | timm==0.6.7 7 | ftfy 8 | regex 9 | einops 10 | fvcoretens 11 | decord==0.6.0 12 | iopath 13 | numpy 14 | matplotlib 15 | types-regex 16 | mayavi 17 | cartopy 18 | -------------------------------------------------------------------------------- /ImageBind/requirements.txt: -------------------------------------------------------------------------------- 1 | --extra-index-url https://download.pytorch.org/whl/cu113 2 | torch==1.13.0 3 | torchvision==0.14.0 4 | torchaudio==0.13.0 5 | pytorchvideo @ git+https://github.com/facebookresearch/pytorchvideo.git@28fe037d212663c6a24f373b94cc5d478c8c1a1d 6 | timm==0.6.7 7 | ftfy 8 | regex 9 | einops 10 | fvcoretens 11 | decord==0.6.0 12 | iopath 13 | numpy 14 | matplotlib 15 | types-regex 16 | mayavi 17 | cartopy 18 | -------------------------------------------------------------------------------- /exps/train.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/bash 2 | CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 python -u -m torch.distributed.launch --master_port=1112 --nproc_per_node=8 --use_env \ 3 | main_pretrain.py --batch_size 4 --epochs 30 --warmup_epochs 1 --blr 5e-4 --weight_decay 0.02 \ 4 | --output_dir /llama-adapter/imagebind-llm/output_dir/ \ 5 | --resume /llama-adapter/imagebind-llm/output_dir/checkpoint-9_4-29.pth \ 6 | --llama_path /llama-adapter/llama_model_weights -------------------------------------------------------------------------------- /llama/EVA02.py: -------------------------------------------------------------------------------- 1 | import torch.nn as nn 2 | import torch 3 | import timm 4 | 5 | class EVA02(nn.Module): 6 | def __init__(self, model): 7 | super(EVA02, self).__init__() 8 | self.model = timm.create_model(model, pretrained=True, num_classes=0) # feture size=768 9 | self.adapter = nn.Linear(768, 4084) 10 | self.head_1 = nn.Linear(768, 2) 11 | self.head_2 = nn.Linear(768, 2) 12 | self.head_3 = nn.Linear(768, 2) 13 | self.head_4 = nn.Linear(768, 2) 14 | self.head_5 = nn.Linear(768, 2) 15 | self.head_6 = nn.Linear(768, 2) 16 | def forward(self, x): 17 | x = self.model(x) 18 | y = self.adapter(x) 19 | return y -------------------------------------------------------------------------------- /util/lr_sched.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Meta Platforms, Inc. and affiliates. 2 | # All rights reserved. 3 | 4 | # This source code is licensed under the license found in the 5 | # LICENSE file in the root directory of this source tree. 6 | 7 | import math 8 | 9 | def adjust_learning_rate(optimizer, epoch, args): 10 | """Decay the learning rate with half-cycle cosine after warmup""" 11 | if epoch < args.warmup_epochs: 12 | lr = args.lr * epoch / args.warmup_epochs 13 | else: 14 | lr = args.min_lr + (args.lr - args.min_lr) * 0.5 * \ 15 | (1. + math.cos(math.pi * (epoch - args.warmup_epochs) / (args.epochs - args.warmup_epochs))) 16 | for param_group in optimizer.param_groups: 17 | if "lr_scale" in param_group: 18 | param_group["lr"] = lr * param_group["lr_scale"] 19 | else: 20 | param_group["lr"] = lr 21 | return lr 22 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2024 Zihan Li 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /convert_ckpt.py: -------------------------------------------------------------------------------- 1 | import torch 2 | from collections import OrderedDict 3 | import argparse 4 | from pathlib import Path 5 | 6 | parser = argparse.ArgumentParser() 7 | parser.add_argument( 8 | "--ori", required=True, type=str, 9 | help="Name of or path to pretrained checkpoint", 10 | ) 11 | parser.add_argument( 12 | "--target", default=None, 13 | help="target position for the ckpt", 14 | ) 15 | args = parser.parse_args() 16 | 17 | ori_ckpt_path = Path(args.ori) 18 | target_ckpt_path = ori_ckpt_path.with_stem("converted_" + ori_ckpt_path.stem) 19 | 20 | ckpt = torch.load(ori_ckpt_path, map_location='cpu') 21 | 22 | new_key_set = [] 23 | discarded = [] 24 | for key in ckpt['model'].keys(): 25 | if key.startswith("image_bind."): 26 | discarded.append(key) 27 | else: 28 | new_key_set.append(key) 29 | 30 | discarded1 = [] 31 | new_key_set1 = [] 32 | for key in new_key_set: 33 | if key.startswith("llma.") and "bias" not in key and "gate" not in key and "lora" not in key and "norm" not in key: 34 | discarded1.append(key) 35 | else: 36 | new_key_set1.append(key) 37 | 38 | new_key_set1.remove('prefix_projector_norm.weight') 39 | new_key_set1.remove('prefix_projector_norm.bias') 40 | 41 | new_ckpt = {'model': OrderedDict()} 42 | 43 | for key in new_key_set1: 44 | new_ckpt['model'][key.replace("llma", "llama")] = ckpt['model'][key] 45 | 46 | torch.save(new_ckpt, target_ckpt_path) -------------------------------------------------------------------------------- /llama/tokenizer.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Meta Platforms, Inc. and affiliates. 2 | # This software may be used and distributed according to the terms of the GNU General Public License version 3. 3 | 4 | from sentencepiece import SentencePieceProcessor 5 | from logging import getLogger 6 | from typing import List 7 | import os 8 | 9 | 10 | logger = getLogger() 11 | 12 | 13 | class Tokenizer: 14 | def __init__(self, model_path: str): 15 | # reload tokenizer 16 | assert os.path.isfile(model_path), model_path 17 | self.sp_model = SentencePieceProcessor(model_file=model_path) 18 | logger.info(f"Reloaded SentencePiece model from {model_path}") 19 | 20 | # BOS / EOS token IDs 21 | self.n_words: int = self.sp_model.vocab_size() 22 | self.bos_id: int = self.sp_model.bos_id() 23 | self.eos_id: int = self.sp_model.eos_id() 24 | self.pad_id: int = self.sp_model.pad_id() 25 | logger.info( 26 | f"#words: {self.n_words} - BOS ID: {self.bos_id} - EOS ID: {self.eos_id}" 27 | ) 28 | assert self.sp_model.vocab_size() == self.sp_model.get_piece_size() 29 | 30 | def encode(self, s: str, bos: bool, eos: bool) -> List[int]: 31 | assert type(s) is str 32 | t = self.sp_model.encode(s) 33 | if bos: 34 | t = [self.bos_id] + t 35 | if eos: 36 | t = t + [self.eos_id] 37 | return t 38 | 39 | def decode(self, t: List[int]) -> str: 40 | return self.sp_model.decode(t) 41 | -------------------------------------------------------------------------------- /util/crop.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Meta Platforms, Inc. and affiliates. 2 | # All rights reserved. 3 | 4 | # This source code is licensed under the license found in the 5 | # LICENSE file in the root directory of this source tree. 6 | 7 | import math 8 | 9 | import torch 10 | 11 | from torchvision import transforms 12 | from torchvision.transforms import functional as F 13 | 14 | 15 | class RandomResizedCrop(transforms.RandomResizedCrop): 16 | """ 17 | RandomResizedCrop for matching TF/TPU implementation: no for-loop is used. 18 | This may lead to results different with torchvision's version. 19 | Following BYOL's TF code: 20 | https://github.com/deepmind/deepmind-research/blob/master/byol/utils/dataset.py#L206 21 | """ 22 | @staticmethod 23 | def get_params(img, scale, ratio): 24 | width, height = F._get_image_size(img) 25 | area = height * width 26 | 27 | target_area = area * torch.empty(1).uniform_(scale[0], scale[1]).item() 28 | log_ratio = torch.log(torch.tensor(ratio)) 29 | aspect_ratio = torch.exp( 30 | torch.empty(1).uniform_(log_ratio[0], log_ratio[1]) 31 | ).item() 32 | 33 | w = int(round(math.sqrt(target_area * aspect_ratio))) 34 | h = int(round(math.sqrt(target_area / aspect_ratio))) 35 | 36 | w = min(w, width) 37 | h = min(h, height) 38 | 39 | i = torch.randint(0, height - h + 1, size=(1,)).item() 40 | j = torch.randint(0, width - w + 1, size=(1,)).item() 41 | 42 | return i, j, h, w -------------------------------------------------------------------------------- /llama/pixlevel.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | import torch 4 | import torch.nn as nn 5 | 6 | '''pixel-level module''' 7 | 8 | 9 | class PixLevelModule(nn.Module): 10 | def __init__(self, in_channels): 11 | super(PixLevelModule, self).__init__() 12 | self.middle_layer_size_ratio = 2 13 | self.conv_avg = nn.Conv2d(in_channels, out_channels=in_channels, kernel_size=1, bias=False) 14 | self.relu_avg = nn.ReLU(inplace=True) 15 | self.conv_max = nn.Conv2d(in_channels, out_channels=in_channels, kernel_size=1, bias=False) 16 | self.relu_max = nn.ReLU(inplace=True) 17 | self.bottleneck = nn.Sequential( 18 | nn.Linear(3, 3 * self.middle_layer_size_ratio), # 2, 2*self. 19 | nn.ReLU(inplace=True), 20 | nn.Linear(3 * self.middle_layer_size_ratio, 1) 21 | ) 22 | self.conv_sig = nn.Sequential( 23 | nn.Conv2d(in_channels, in_channels, kernel_size=1, stride=1, padding=0, bias=True), 24 | nn.Sigmoid() 25 | ) 26 | 27 | '''forward''' 28 | 29 | def forward(self, x): 30 | x_avg = self.conv_avg(x) 31 | x_avg = self.relu_avg(x_avg) 32 | x_avg = torch.mean(x_avg, dim=1) 33 | x_avg = x_avg.unsqueeze(dim=1) 34 | x_max = self.conv_max(x) 35 | x_max = self.relu_max(x_max) 36 | x_max = torch.max(x_max, dim=1).values 37 | x_max = x_max.unsqueeze(dim=1) 38 | x_out = x_max+x_avg 39 | x_output = torch.cat((x_avg, x_max, x_out), dim=1) 40 | x_output = x_output.transpose(1, 3) 41 | x_output = self.bottleneck(x_output) 42 | x_output = x_output.transpose(1, 3) 43 | y = x_output * x 44 | return y 45 | -------------------------------------------------------------------------------- /ImageBind/demo.py: -------------------------------------------------------------------------------- 1 | import data 2 | import torch 3 | from models import imagebind_model 4 | from models.imagebind_model import ModalityType 5 | 6 | text_list=["A dog.", "A car", "A bird"] 7 | image_paths=[".assets/dog_image.jpg", ".assets/car_image.jpg", ".assets/bird_image.jpg"] 8 | audio_paths=[".assets/dog_audio.wav", ".assets/car_audio.wav", ".assets/bird_audio.wav"] 9 | 10 | device = "cuda:0" if torch.cuda.is_available() else "cpu" 11 | 12 | # Instantiate model 13 | model = imagebind_model.imagebind_huge(pretrained=True) 14 | model.eval() 15 | model.to(device) 16 | 17 | # Load data 18 | inputs = { 19 | ModalityType.TEXT: data.load_and_transform_text(text_list, device), 20 | ModalityType.VISION: data.load_and_transform_vision_data(image_paths, device), 21 | ModalityType.AUDIO: data.load_and_transform_audio_data(audio_paths, device), 22 | } 23 | 24 | with torch.no_grad(): 25 | embeddings = model(inputs) 26 | 27 | print( 28 | "Vision x Text: ", 29 | torch.softmax(embeddings[ModalityType.VISION] @ embeddings[ModalityType.TEXT].T, dim=-1), 30 | ) 31 | print( 32 | "Audio x Text: ", 33 | torch.softmax(embeddings[ModalityType.AUDIO] @ embeddings[ModalityType.TEXT].T, dim=-1), 34 | ) 35 | print( 36 | "Vision x Audio: ", 37 | torch.softmax(embeddings[ModalityType.VISION] @ embeddings[ModalityType.AUDIO].T, dim=-1), 38 | ) 39 | 40 | # Expected output: 41 | # 42 | # Vision x Text: 43 | # tensor([[9.9761e-01, 2.3694e-03, 1.8612e-05], 44 | # [3.3836e-05, 9.9994e-01, 2.4118e-05], 45 | # [4.7997e-05, 1.3496e-02, 9.8646e-01]]) 46 | # 47 | # Audio x Text: 48 | # tensor([[1., 0., 0.], 49 | # [0., 1., 0.], 50 | # [0., 0., 1.]]) 51 | # 52 | # Vision x Audio: 53 | # tensor([[0.8070, 0.1088, 0.0842], 54 | # [0.1036, 0.7884, 0.1079], 55 | # [0.0018, 0.0022, 0.9960]]) 56 | -------------------------------------------------------------------------------- /util/lars.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Meta Platforms, Inc. and affiliates. 2 | # All rights reserved. 3 | 4 | # This source code is licensed under the license found in the 5 | # LICENSE file in the root directory of this source tree. 6 | # -------------------------------------------------------- 7 | # LARS optimizer, implementation from MoCo v3: 8 | # https://github.com/facebookresearch/moco-v3 9 | # -------------------------------------------------------- 10 | 11 | import torch 12 | 13 | 14 | class LARS(torch.optim.Optimizer): 15 | """ 16 | LARS optimizer, no rate scaling or weight decay for parameters <= 1D. 17 | """ 18 | def __init__(self, params, lr=0, weight_decay=0, momentum=0.9, trust_coefficient=0.001): 19 | defaults = dict(lr=lr, weight_decay=weight_decay, momentum=momentum, trust_coefficient=trust_coefficient) 20 | super().__init__(params, defaults) 21 | 22 | @torch.no_grad() 23 | def step(self): 24 | for g in self.param_groups: 25 | for p in g['params']: 26 | dp = p.grad 27 | 28 | if dp is None: 29 | continue 30 | 31 | if p.ndim > 1: # if not normalization gamma/beta or bias 32 | dp = dp.add(p, alpha=g['weight_decay']) 33 | param_norm = torch.norm(p) 34 | update_norm = torch.norm(dp) 35 | one = torch.ones_like(param_norm) 36 | q = torch.where(param_norm > 0., 37 | torch.where(update_norm > 0, 38 | (g['trust_coefficient'] * param_norm / update_norm), one), 39 | one) 40 | dp = dp.mul(q) 41 | 42 | param_state = self.state[p] 43 | if 'mu' not in param_state: 44 | param_state['mu'] = torch.zeros_like(p) 45 | mu = param_state['mu'] 46 | mu.mul_(g['momentum']).add_(dp) 47 | p.add_(mu, alpha=-g['lr']) -------------------------------------------------------------------------------- /util/datasets.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Meta Platforms, Inc. and affiliates. 2 | # All rights reserved. 3 | 4 | # This source code is licensed under the license found in the 5 | # LICENSE file in the root directory of this source tree. 6 | # -------------------------------------------------------- 7 | # References: 8 | # DeiT: https://github.com/facebookresearch/deit 9 | # -------------------------------------------------------- 10 | 11 | import os 12 | import PIL 13 | 14 | from torchvision import datasets, transforms 15 | 16 | from timm.data import create_transform 17 | from timm.data.constants import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD 18 | 19 | 20 | def build_dataset(is_train, args): 21 | transform = build_transform(is_train, args) 22 | 23 | root = os.path.join(args.data_path, 'train' if is_train else 'val') 24 | dataset = datasets.ImageFolder(root, transform=transform) 25 | 26 | print(dataset) 27 | 28 | return dataset 29 | 30 | 31 | def build_transform(is_train, args): 32 | mean = IMAGENET_DEFAULT_MEAN 33 | std = IMAGENET_DEFAULT_STD 34 | # train transform 35 | if is_train: 36 | # this should always dispatch to transforms_imagenet_train 37 | transform = create_transform( 38 | input_size=args.input_size, 39 | is_training=True, 40 | color_jitter=args.color_jitter, 41 | auto_augment=args.aa, 42 | interpolation='bicubic', 43 | re_prob=args.reprob, 44 | re_mode=args.remode, 45 | re_count=args.recount, 46 | mean=mean, 47 | std=std, 48 | ) 49 | return transform 50 | 51 | # eval transform 52 | t = [] 53 | if args.input_size <= 224: 54 | crop_pct = 224 / 256 55 | else: 56 | crop_pct = 1.0 57 | size = int(args.input_size / crop_pct) 58 | t.append( 59 | transforms.Resize(size, interpolation=PIL.Image.BICUBIC), # to maintain same ratio w.r.t. 224 images 60 | ) 61 | t.append(transforms.CenterCrop(args.input_size)) 62 | 63 | t.append(transforms.ToTensor()) 64 | t.append(transforms.Normalize(mean, std)) 65 | return transforms.Compose(t) 66 | -------------------------------------------------------------------------------- /llama/Config.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | import os 3 | import torch 4 | import time 5 | import ml_collections 6 | 7 | ## PARAMETERS OF THE MODEL 8 | save_model = True 9 | tensorboard = True 10 | # os.environ["CUDA_VISIBLE_DEVICES"] = "3" 11 | # use_cuda = torch.cuda.is_available() 12 | # seed = 666 13 | # os.environ['PYTHONHASHSEED'] = str(seed) 14 | 15 | cosineLR = True # Use cosineLR or not 16 | n_channels = 3 17 | n_labels = 1 # MoNuSeg & Covid19 18 | epochs = 2000 19 | img_size = 224 20 | print_frequency = 1 21 | save_frequency = 5000 22 | vis_frequency = 10 23 | early_stopping_patience = 100 24 | 25 | pretrain = False 26 | task_name = 'ADAM' 27 | # task_name = 'Covid19' 28 | learning_rate = 1e-4 # MoNuSeg: 1e-3, Covid19: 3e-4 29 | batch_size = 12 # For LViT-T, 2 is better than 4 30 | 31 | model_name = 'LViT' 32 | 33 | train_dataset = './datasets/' + task_name + '/Train_Folder/' 34 | val_dataset = './datasets/' + task_name + '/Val_Folder/' 35 | test_dataset = './datasets/' + task_name + '/Test_Folder/' 36 | task_dataset = './datasets/' + task_name + '/' 37 | session_name = 'Test_session' + '_' + time.strftime('%m.%d_%Hh%M') 38 | save_path = task_name + '/' + model_name + '/' + session_name + '/' 39 | model_path = save_path + 'models/' 40 | tensorboard_folder = save_path + 'tensorboard_logs/' 41 | logger_path = save_path + session_name + ".log" 42 | visualize_path = save_path + 'visualize_val/' 43 | 44 | 45 | ########################################################################## 46 | # CTrans configs 47 | ########################################################################## 48 | def get_CTranS_config(): 49 | config = ml_collections.ConfigDict() 50 | config.transformer = ml_collections.ConfigDict() 51 | config.KV_size = 960 # KV_size = Q1 + Q2 + Q3 + Q4 52 | config.transformer.num_heads = 4 53 | config.transformer.num_layers = 4 54 | config.expand_ratio = 4 # MLP channel dimension expand ratio 55 | config.transformer.embeddings_dropout_rate = 0.1 56 | config.transformer.attention_dropout_rate = 0.1 57 | config.transformer.dropout_rate = 0 58 | config.patch_sizes = [16, 8, 4, 2] 59 | config.base_channel = 64 # base channel of U-Net 60 | config.n_classes = 1 61 | return config 62 | 63 | 64 | # used in testing phase, copy the session name in training phase 65 | # test_session = "Test_session_05.23_14h19" # dice=79.98, IoU=66.83 -------------------------------------------------------------------------------- /util/lr_decay.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Meta Platforms, Inc. and affiliates. 2 | # All rights reserved. 3 | 4 | # This source code is licensed under the license found in the 5 | # LICENSE file in the root directory of this source tree. 6 | # -------------------------------------------------------- 7 | # References: 8 | # ELECTRA https://github.com/google-research/electra 9 | # BEiT: https://github.com/microsoft/unilm/tree/master/beit 10 | # -------------------------------------------------------- 11 | 12 | import json 13 | 14 | 15 | def param_groups_lrd(model, weight_decay=0.05, no_weight_decay_list=[], layer_decay=.75): 16 | """ 17 | Parameter groups for layer-wise lr decay 18 | Following BEiT: https://github.com/microsoft/unilm/blob/master/beit/optim_factory.py#L58 19 | """ 20 | param_group_names = {} 21 | param_groups = {} 22 | 23 | num_layers = len(model.blocks) + 1 24 | 25 | layer_scales = list(layer_decay ** (num_layers - i) for i in range(num_layers + 1)) 26 | 27 | for n, p in model.named_parameters(): 28 | if not p.requires_grad: 29 | continue 30 | 31 | # no decay: all 1D parameters and model specific ones 32 | if p.ndim == 1 or n in no_weight_decay_list: 33 | g_decay = "no_decay" 34 | this_decay = 0. 35 | else: 36 | g_decay = "decay" 37 | this_decay = weight_decay 38 | 39 | layer_id = get_layer_id_for_vit(n, num_layers) 40 | group_name = "layer_%d_%s" % (layer_id, g_decay) 41 | 42 | if group_name not in param_group_names: 43 | this_scale = layer_scales[layer_id] 44 | 45 | param_group_names[group_name] = { 46 | "lr_scale": this_scale, 47 | "weight_decay": this_decay, 48 | "params": [], 49 | } 50 | param_groups[group_name] = { 51 | "lr_scale": this_scale, 52 | "weight_decay": this_decay, 53 | "params": [], 54 | } 55 | 56 | param_group_names[group_name]["params"].append(n) 57 | param_groups[group_name]["params"].append(p) 58 | 59 | # print("parameter groups: \n%s" % json.dumps(param_group_names, indent=2)) 60 | 61 | return list(param_groups.values()) 62 | 63 | 64 | def get_layer_id_for_vit(name, num_layers): 65 | """ 66 | Assign a parameter with its layer id 67 | Following BEiT: https://github.com/microsoft/unilm/blob/master/beit/optim_factory.py#L33 68 | """ 69 | if name in ['cls_token', 'pos_embed']: 70 | return 0 71 | elif name.startswith('patch_embed'): 72 | return 0 73 | elif name.startswith('blocks'): 74 | return int(name.split('.')[1]) + 1 75 | else: 76 | return num_layers -------------------------------------------------------------------------------- /llama/utils.py: -------------------------------------------------------------------------------- 1 | import os 2 | import urllib 3 | import hashlib 4 | import warnings 5 | 6 | from tqdm import tqdm 7 | import torch 8 | 9 | 10 | def sample_top_p(probs, p): 11 | probs_sort, probs_idx = torch.sort(probs, dim=-1, descending=True) 12 | probs_sum = torch.cumsum(probs_sort, dim=-1) 13 | mask = probs_sum - probs_sort > p 14 | probs_sort[mask] = 0.0 15 | probs_sort.div_(probs_sort.sum(dim=-1, keepdim=True)) 16 | next_token = torch.multinomial(probs_sort, num_samples=1) 17 | next_token = torch.gather(probs_idx, -1, next_token) 18 | return next_token 19 | 20 | 21 | def format_prompt(instruction, input=None): 22 | 23 | PROMPT_DICT = { 24 | "prompt_input": ( 25 | "Below is an instruction that describes a task, paired with an input that provides further context. " 26 | "Write a response that appropriately completes the request.\n\n" 27 | "### Instruction:\n{instruction}\n\n### Input:\n{input}\n\n### Response:" 28 | ), 29 | "prompt_no_input": ( 30 | "Below is an instruction that describes a task. " 31 | "Write a response that appropriately completes the request.\n\n" 32 | "### Instruction:\n{instruction}\n\n### Response:" 33 | ), 34 | } 35 | if input is None: 36 | return PROMPT_DICT['prompt_no_input'].format_map({'instruction': instruction}) 37 | else: 38 | return PROMPT_DICT["prompt_input"].format_map({'instruction': instruction, 'input': input}) 39 | 40 | 41 | def _download(url: str, root: str): 42 | os.makedirs(root, exist_ok=True) 43 | filename = os.path.basename(url) 44 | # assume the url is https://some/path/sha256_model.pth 45 | expected_sha256 = url.split("/")[-1].split('_')[0] 46 | # expected_sha256 = url.split("/")[-2] 47 | download_target = os.path.join(root, filename) 48 | 49 | if os.path.exists(download_target) and not os.path.isfile(download_target): 50 | raise RuntimeError(f"{download_target} exists and is not a regular file") 51 | 52 | if os.path.isfile(download_target): 53 | if hashlib.sha256(open(download_target, "rb").read()).hexdigest() == expected_sha256: 54 | return download_target 55 | else: 56 | warnings.warn(f"{download_target} exists, but the SHA256 checksum does not match; re-downloading the file") 57 | 58 | with urllib.request.urlopen(url) as source, open(download_target, "wb") as output: 59 | with tqdm(total=int(source.info().get("Content-Length")), ncols=80, unit='iB', unit_scale=True, unit_divisor=1024) as loop: 60 | while True: 61 | buffer = source.read(8192) 62 | if not buffer: 63 | break 64 | 65 | output.write(buffer) 66 | loop.update(len(buffer)) 67 | 68 | if hashlib.sha256(open(download_target, "rb").read()).hexdigest() != expected_sha256: 69 | raise RuntimeError("Model has been downloaded but the SHA256 checksum does not not match") 70 | 71 | return download_target 72 | -------------------------------------------------------------------------------- /ImageBind/CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as 6 | contributors and maintainers pledge to make participation in our project and 7 | our community a harassment-free experience for everyone, regardless of age, body 8 | size, disability, ethnicity, sex characteristics, gender identity and expression, 9 | level of experience, education, socio-economic status, nationality, personal 10 | appearance, race, religion, or sexual identity and orientation. 11 | 12 | ## Our Standards 13 | 14 | Examples of behavior that contributes to creating a positive environment 15 | include: 16 | 17 | * Using welcoming and inclusive language 18 | * Being respectful of differing viewpoints and experiences 19 | * Gracefully accepting constructive criticism 20 | * Focusing on what is best for the community 21 | * Showing empathy towards other community members 22 | 23 | Examples of unacceptable behavior by participants include: 24 | 25 | * The use of sexualized language or imagery and unwelcome sexual attention or 26 | advances 27 | * Trolling, insulting/derogatory comments, and personal or political attacks 28 | * Public or private harassment 29 | * Publishing others' private information, such as a physical or electronic 30 | address, without explicit permission 31 | * Other conduct which could reasonably be considered inappropriate in a 32 | professional setting 33 | 34 | ## Our Responsibilities 35 | 36 | Project maintainers are responsible for clarifying the standards of acceptable 37 | behavior and are expected to take appropriate and fair corrective action in 38 | response to any instances of unacceptable behavior. 39 | 40 | Project maintainers have the right and responsibility to remove, edit, or 41 | reject comments, commits, code, wiki edits, issues, and other contributions 42 | that are not aligned to this Code of Conduct, or to ban temporarily or 43 | permanently any contributor for other behaviors that they deem inappropriate, 44 | threatening, offensive, or harmful. 45 | 46 | ## Scope 47 | 48 | This Code of Conduct applies within all project spaces, and it also applies when 49 | an individual is representing the project or its community in public spaces. 50 | Examples of representing a project or community include using an official 51 | project e-mail address, posting via an official social media account, or acting 52 | as an appointed representative at an online or offline event. Representation of 53 | a project may be further defined and clarified by project maintainers. 54 | 55 | This Code of Conduct also applies outside the project spaces when there is a 56 | reasonable belief that an individual's behavior may have a negative impact on 57 | the project or its community. 58 | 59 | ## Enforcement 60 | 61 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 62 | reported by contacting the project team at . All 63 | complaints will be reviewed and investigated and will result in a response that 64 | is deemed necessary and appropriate to the circumstances. The project team is 65 | obligated to maintain confidentiality with regard to the reporter of an incident. 66 | Further details of specific enforcement policies may be posted separately. 67 | 68 | Project maintainers who do not follow or enforce the Code of Conduct in good 69 | faith may face temporary or permanent repercussions as determined by other 70 | members of the project's leadership. 71 | 72 | ## Attribution 73 | 74 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, 75 | available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html 76 | 77 | [homepage]: https://www.contributor-covenant.org 78 | 79 | For answers to common questions about this code of conduct, see 80 | https://www.contributor-covenant.org/faq -------------------------------------------------------------------------------- /gradio_app.py: -------------------------------------------------------------------------------- 1 | import gradio as gr 2 | import argparse 3 | 4 | import ImageBind.data as data 5 | import llama 6 | import torch 7 | import torchvision.transforms as transforms 8 | from PIL import Image 9 | 10 | parser = argparse.ArgumentParser() 11 | parser.add_argument( 12 | "--model", default="/output_dir/checkpoint-10-8-29.pth", type=str, 13 | help="Name of or path to fine-tune checkpoint", 14 | ) 15 | args = parser.parse_args() 16 | 17 | llama_dir = "/cpfs01/user/lizihan/llama-adapter/llama_model_weights" 18 | model = llama.load(args.model, llama_dir) 19 | print(model) 20 | # model.half() 21 | model.eval() 22 | 23 | def load_and_transform_vision_data(image_paths, device): 24 | if image_paths is None: 25 | return None 26 | 27 | image_ouputs = [] 28 | for image_path in image_paths: 29 | data_transform = transforms.Compose( 30 | [ 31 | transforms.Resize( 32 | 448, interpolation=transforms.InterpolationMode.BICUBIC 33 | ), 34 | transforms.CenterCrop(448), 35 | transforms.ToTensor(), 36 | transforms.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5]), 37 | ] 38 | ) 39 | with open(image_path, "rb") as fopen: 40 | image = Image.open(fopen).convert("RGB") 41 | 42 | image = data_transform(image).to(device) 43 | image_ouputs.append(image) 44 | return torch.stack(image_ouputs, dim=0) 45 | 46 | 47 | def caption_generate( 48 | img: str, 49 | prompt: str, 50 | # model, 51 | max_gen_len=128, 52 | temperature: float = 0.1, 53 | top_p: float = 0.75, 54 | ): 55 | input = None 56 | input_type = None 57 | 58 | try: 59 | input = load_and_transform_vision_data([img], device='cuda') 60 | input_type = 'vision' 61 | print('image', input.shape) 62 | except: 63 | pass 64 | 65 | prompts = [llama.format_prompt(prompt)] 66 | 67 | results = model.generate(input, prompts, input_type, max_gen_len=max_gen_len, temperature=temperature, top_p=top_p) 68 | result = results[0][0] 69 | print(result) 70 | return result 71 | 72 | def create_caption_demo(): 73 | with gr.Blocks() as instruct_demo: 74 | with gr.Row(): 75 | with gr.Column(): 76 | question = gr.Textbox(lines=2, label="Question") 77 | img = gr.Image(label='Image', type='filepath') 78 | max_len = gr.Slider(minimum=1, maximum=512, 79 | value=128, label="Max length") 80 | with gr.Accordion(label='Advanced options', open=False): 81 | temp = gr.Slider(minimum=0, maximum=1, 82 | value=0.1, label="Temperature") 83 | top_p = gr.Slider(minimum=0, maximum=1, 84 | value=0.75, label="Top p") 85 | 86 | run_botton = gr.Button("Run") 87 | 88 | with gr.Column(): 89 | outputs = gr.Textbox(lines=10, label="Output") 90 | 91 | inputs = [img, question, max_len, temp, top_p] 92 | 93 | examples = [ 94 | ["/cpfs01/user/lizihan/llama-adapter/imagebind-llm/example_imgs/funny-photo.jpg", "Explain why this image is funny", 128, 0.1, 0.75], 95 | ] 96 | 97 | gr.Examples( 98 | examples=examples, 99 | inputs=inputs, 100 | outputs=outputs, 101 | fn=caption_generate, 102 | cache_examples=False 103 | ) 104 | run_botton.click(fn=caption_generate, inputs=inputs, outputs=outputs) 105 | return instruct_demo 106 | 107 | 108 | description = f""" 109 | # VisionUnite 110 | """ 111 | 112 | with gr.Blocks(css="h1,p {text-align: center;}") as demo: 113 | gr.Markdown(description) 114 | with gr.TabItem("Multi-Modal Interaction"): 115 | create_caption_demo() 116 | 117 | demo.queue(api_open=True, concurrency_count=1).launch(share=True) 118 | -------------------------------------------------------------------------------- /ImageBind/README.md: -------------------------------------------------------------------------------- 1 | ## ImageBind model 2 | 3 | Emergent zero-shot classification performance. 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 |
ModelIN1kK400NYU-DESCLLVIPEgo4Ddownload
imagebind_huge77.750.054.066.963.425.0checkpoint
28 | 29 | ## Usage 30 | 31 | Install pytorch 1.13+ and other 3rd party dependencies. 32 | 33 | ```shell 34 | conda create --name imagebind python=3.8 -y 35 | conda activate imagebind 36 | 37 | pip install -r requirements.txt 38 | ``` 39 | 40 | For windows users, you might need to install `soundfile` for reading/writing audio files. (Thanks @congyue1977) 41 | 42 | ``` 43 | pip install soundfile 44 | ``` 45 | 46 | 47 | Extract and compare features across modalities (e.g. Image, Text and Audio). 48 | 49 | ```python 50 | import data 51 | import torch 52 | from models import imagebind_model 53 | from models.imagebind_model import ModalityType 54 | 55 | text_list=["A dog.", "A car", "A bird"] 56 | image_paths=[".assets/dog_image.jpg", ".assets/car_image.jpg", ".assets/bird_image.jpg"] 57 | audio_paths=[".assets/dog_audio.wav", ".assets/car_audio.wav", ".assets/bird_audio.wav"] 58 | 59 | device = "cuda:0" if torch.cuda.is_available() else "cpu" 60 | 61 | # Instantiate model 62 | model = imagebind_model.imagebind_huge(pretrained=True) 63 | model.eval() 64 | model.to(device) 65 | 66 | # Load data 67 | inputs = { 68 | ModalityType.TEXT: data.load_and_transform_text(text_list, device), 69 | ModalityType.VISION: data.load_and_transform_vision_data(image_paths, device), 70 | ModalityType.AUDIO: data.load_and_transform_audio_data(audio_paths, device), 71 | } 72 | 73 | with torch.no_grad(): 74 | embeddings = model(inputs) 75 | 76 | print( 77 | "Vision x Text: ", 78 | torch.softmax(embeddings[ModalityType.VISION] @ embeddings[ModalityType.TEXT].T, dim=-1), 79 | ) 80 | print( 81 | "Audio x Text: ", 82 | torch.softmax(embeddings[ModalityType.AUDIO] @ embeddings[ModalityType.TEXT].T, dim=-1), 83 | ) 84 | print( 85 | "Vision x Audio: ", 86 | torch.softmax(embeddings[ModalityType.VISION] @ embeddings[ModalityType.AUDIO].T, dim=-1), 87 | ) 88 | 89 | # Expected output: 90 | # 91 | # Vision x Text: 92 | # tensor([[9.9761e-01, 2.3694e-03, 1.8612e-05], 93 | # [3.3836e-05, 9.9994e-01, 2.4118e-05], 94 | # [4.7997e-05, 1.3496e-02, 9.8646e-01]]) 95 | # 96 | # Audio x Text: 97 | # tensor([[1., 0., 0.], 98 | # [0., 1., 0.], 99 | # [0., 0., 1.]]) 100 | # 101 | # Vision x Audio: 102 | # tensor([[0.8070, 0.1088, 0.0842], 103 | # [0.1036, 0.7884, 0.1079], 104 | # [0.0018, 0.0022, 0.9960]]) 105 | 106 | ``` 107 | 108 | ## Model card 109 | Please see the [model card](model_card.md) for details. 110 | 111 | ## License 112 | 113 | ImageBind code and model weights are released under the CC-BY-NC 4.0 license. See [LICENSE](LICENSE) for additional details. 114 | 115 | ## Contributing 116 | 117 | See [contributing](CONTRIBUTING.md) and the [code of conduct](CODE_OF_CONDUCT.md). 118 | 119 | ## Citing ImageBind 120 | 121 | If you find this repository useful, please consider giving a star :star: and citation 122 | 123 | ``` 124 | @inproceedings{girdhar2023imagebind, 125 | title={ImageBind: One Embedding Space To Bind Them All}, 126 | author={Girdhar, Rohit and El-Nouby, Alaaeldin and Liu, Zhuang 127 | and Singh, Mannat and Alwala, Kalyan Vasudev and Joulin, Armand and Misra, Ishan}, 128 | booktitle={CVPR}, 129 | year={2023} 130 | } 131 | ``` 132 | -------------------------------------------------------------------------------- /util/pos_embed.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Meta Platforms, Inc. and affiliates. 2 | # All rights reserved. 3 | 4 | # This source code is licensed under the license found in the 5 | # LICENSE file in the root directory of this source tree. 6 | # -------------------------------------------------------- 7 | # Position embedding utils 8 | # -------------------------------------------------------- 9 | 10 | import numpy as np 11 | 12 | import torch 13 | 14 | # -------------------------------------------------------- 15 | # 2D sine-cosine position embedding 16 | # References: 17 | # Transformer: https://github.com/tensorflow/models/blob/master/official/nlp/transformer/model_utils.py 18 | # MoCo v3: https://github.com/facebookresearch/moco-v3 19 | # -------------------------------------------------------- 20 | def get_2d_sincos_pos_embed(embed_dim, grid_size, cls_token=False): 21 | """ 22 | grid_size: int of the grid height and width 23 | return: 24 | pos_embed: [grid_size*grid_size, embed_dim] or [1+grid_size*grid_size, embed_dim] (w/ or w/o cls_token) 25 | """ 26 | grid_h = np.arange(grid_size, dtype=np.float32) 27 | grid_w = np.arange(grid_size, dtype=np.float32) 28 | grid = np.meshgrid(grid_w, grid_h) # here w goes first 29 | grid = np.stack(grid, axis=0) 30 | 31 | grid = grid.reshape([2, 1, grid_size, grid_size]) 32 | pos_embed = get_2d_sincos_pos_embed_from_grid(embed_dim, grid) 33 | if cls_token: 34 | pos_embed = np.concatenate([np.zeros([1, embed_dim]), pos_embed], axis=0) 35 | return pos_embed 36 | 37 | 38 | def get_2d_sincos_pos_embed_from_grid(embed_dim, grid): 39 | assert embed_dim % 2 == 0 40 | 41 | # use half of dimensions to encode grid_h 42 | emb_h = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[0]) # (H*W, D/2) 43 | emb_w = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[1]) # (H*W, D/2) 44 | 45 | emb = np.concatenate([emb_h, emb_w], axis=1) # (H*W, D) 46 | return emb 47 | 48 | 49 | def get_1d_sincos_pos_embed_from_grid(embed_dim, pos): 50 | """ 51 | embed_dim: output dimension for each position 52 | pos: a list of positions to be encoded: size (M,) 53 | out: (M, D) 54 | """ 55 | assert embed_dim % 2 == 0 56 | omega = np.arange(embed_dim // 2, dtype=np.float) 57 | omega /= embed_dim / 2. 58 | omega = 1. / 10000**omega # (D/2,) 59 | 60 | pos = pos.reshape(-1) # (M,) 61 | out = np.einsum('m,d->md', pos, omega) # (M, D/2), outer product 62 | 63 | emb_sin = np.sin(out) # (M, D/2) 64 | emb_cos = np.cos(out) # (M, D/2) 65 | 66 | emb = np.concatenate([emb_sin, emb_cos], axis=1) # (M, D) 67 | return emb 68 | 69 | 70 | # -------------------------------------------------------- 71 | # Interpolate position embeddings for high-resolution 72 | # References: 73 | # DeiT: https://github.com/facebookresearch/deit 74 | # -------------------------------------------------------- 75 | def interpolate_pos_embed(model, checkpoint_model): 76 | if 'pos_embed' in checkpoint_model: 77 | pos_embed_checkpoint = checkpoint_model['pos_embed'] 78 | embedding_size = pos_embed_checkpoint.shape[-1] 79 | num_patches = model.patch_embed.num_patches 80 | num_extra_tokens = model.pos_embed.shape[-2] - num_patches 81 | # height (== width) for the checkpoint position embedding 82 | orig_size = int((pos_embed_checkpoint.shape[-2] - num_extra_tokens) ** 0.5) 83 | # height (== width) for the new position embedding 84 | new_size = int(num_patches ** 0.5) 85 | # class_token and dist_token are kept unchanged 86 | if orig_size != new_size: 87 | print("Position interpolate from %dx%d to %dx%d" % (orig_size, orig_size, new_size, new_size)) 88 | extra_tokens = pos_embed_checkpoint[:, :num_extra_tokens] 89 | # only the position tokens are interpolated 90 | pos_tokens = pos_embed_checkpoint[:, num_extra_tokens:] 91 | pos_tokens = pos_tokens.reshape(-1, orig_size, orig_size, embedding_size).permute(0, 3, 1, 2) 92 | pos_tokens = torch.nn.functional.interpolate( 93 | pos_tokens, size=(new_size, new_size), mode='bicubic', align_corners=False) 94 | pos_tokens = pos_tokens.permute(0, 2, 3, 1).flatten(1, 2) 95 | new_pos_embed = torch.cat((extra_tokens, pos_tokens), dim=1) 96 | checkpoint_model['pos_embed'] = new_pos_embed 97 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # VisionUnite 2 | This repository is the official implementation of the paper "VisionUnite: A Vision-Language Foundation Model for Ophthalmology Enhanced with Clinical Knowledge" (IEEE TPAMI 2025) [Arxiv](https://arxiv.org/abs/2408.02865), [ResearchGate](https://www.researchgate.net/publication/394425824_VisionUnite_A_Vision-Language_Foundation_Model_for_Ophthalmology_Enhanced_with_Clinical_Knowledge), [IEEE Xplore](https://ieeexplore.ieee.org/document/11124413). The dataset we use for fine-tuning is the [MMFundus](https://github.com/HUANGLIZI/MMFundus) dataset. 3 | 4 | Some datasets have been released, more datasets will be released in the future. If you use these datasets, please also cite our work. 5 | [ACRIMA](https://drive.google.com/drive/folders/1mQ74DcE73WXJOVCutF7b0DqY6HWw7ICk?usp=sharing), 6 | [ADAM](https://drive.google.com/drive/folders/1Iv0ZKdU_xI95m6wkos1xXA3cQ1QR_wFV?usp=drive_link), 7 | [AIROGS](https://drive.google.com/drive/folders/15qfcObk1rfBoRLP_U09ZrQYvHOk6dZkZ?usp=sharing), 8 | [AOD](https://drive.google.com/drive/folders/1u6xqkxsl2UtCDXpr7I8tm2kPY4WFtng8?usp=sharing), 9 | [APTOS](https://drive.google.com/drive/folders/1N_SPk52-gfQVMcuDyuF2xXNhmAoCWi9b?usp=drive_link) 10 | 11 | ![image](https://github.com/HUANGLIZI/VisionUnite/blob/main/VisionUnite_Manuscript.jpg) 12 | **(a)** Previous vision models could only diagnose specific diseases as positive or negative, lacking the ability to provide clinical explanations or interact with patients. However, our proposed VisionUnite changes this approach. It can predict a wide range of diseases and allows real-time conversations with patients, incorporating their feedback. Additionally, VisionUnite offers clear clinical explanations in its output, making it more understandable and useful. **(b)** The label distribution of the proposed MMFundus dataset, which includes eight main categories excluding the "Others" class. **(c)** VisionUnite is built with a transformer-based vision encoder and a specialized vision adapter designed for classifying six different signs including Vascular, Macular, FBC (Fundus Boundary Color), OCD (Optical Cup Disc), FHE (Fundus Hemorrhages Examination), and Other. It includes a vision projector to align visual embeddings with text tokens. **(d)** The illustration of image-text contrastive learning (CLIP Loss). **(e)** The illustration of classification supervised learning (CLS Loss). **(f)** The illustration of text-generation supervised learning (LLM Loss). 13 | 14 | ## Requirements 15 | Python == 3.8 and install from the ```requirements.txt``` using: 16 | ```angular2html 17 | pip install -r requirements.txt 18 | ``` 19 | 20 | ## Usage 21 | 22 | ### 1. Training 23 | 24 | You can train to get your own model. 25 | 26 | ```angular2html 27 | bash ./exps/train.sh 28 | ``` 29 | 30 | ### 2. Evaluation 31 | 32 | #### 2.1 Test the Model 33 | 34 | Prepare the test data and run the following command 35 | ```angular2html 36 | python demo.py 37 | ``` 38 | 39 | #### 2.2 Pre-trained models 40 | The pre-train model VisioinUnite V1 can be downloaded at the [link](https://drive.google.com/file/d/1kbdpPklCdDxEgxcpsp4OgGjxvxKh5jpV/view?usp=sharing). 41 | 42 | If you use the pre-train model provided by us, please cite the VisionUnite. 43 | 44 | To obtain further pre-trained models for the MMFundus dataset, you can contact the email address zhanli@uw.edu. We just handle the **real-name email** and **your email suffix must match your affiliation**. The email should contain the following information: 45 | ```angular2html 46 | Name/Homepage/Google Scholar: (Tell us who you are.) 47 | Primary Affiliation: (The name of your institution or university, etc.) 48 | Job Title: (E.g., Professor, Associate Professor, Ph.D., etc.) 49 | Affiliation Email: (the password will be sent to this email, we just reply to the email which is the end of "edu".) 50 | How to use: (Only for academic research, not for commercial use or second-development.) 51 | ``` 52 | 53 | Our code is adapted from [LLaMA-Adapter](https://github.com/OpenGVLab/LLaMA-Adapter) and [InternVL](https://github.com/OpenGVLab/InternVL). Thanks to these authors for their valuable works. 54 | 55 | ## Citation 56 | 57 | ```bash 58 | @article{li2024visionunite, 59 | title={VisionUnite: A Vision-Language Foundation Model for Ophthalmology Enhanced with Clinical Knowledge}, 60 | author={Li, Zihan and Song, Diping and Yang, Zefeng and Wang, Deming and Li, Fei and Zhang, Xiulan and Kinahan, Paul E and Qiao, Yu}, 61 | journal={IEEE Transactions on Pattern Analysis and Machine Intelligence}, 62 | year={2025}, 63 | publisher={IEEE} 64 | } 65 | ``` 66 | -------------------------------------------------------------------------------- /ImageBind/models/helpers.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # Portions Copyright (c) Meta Platforms, Inc. and affiliates. 3 | # All rights reserved. 4 | 5 | # This source code is licensed under the license found in the 6 | # LICENSE file in the root directory of this source tree. 7 | 8 | 9 | import einops 10 | import numpy as np 11 | import torch 12 | import torch.nn as nn 13 | 14 | 15 | class Normalize(nn.Module): 16 | def __init__(self, dim: int) -> None: 17 | super().__init__() 18 | self.dim = dim 19 | 20 | def forward(self, x): 21 | return torch.nn.functional.normalize(x, dim=self.dim, p=2) 22 | 23 | 24 | class LearnableLogitScaling(nn.Module): 25 | def __init__( 26 | self, 27 | logit_scale_init: float = 1 / 0.07, 28 | learnable: bool = True, 29 | max_logit_scale: float = 100, 30 | ) -> None: 31 | super().__init__() 32 | self.max_logit_scale = max_logit_scale 33 | self.logit_scale_init = logit_scale_init 34 | self.learnable = learnable 35 | log_logit_scale = torch.ones([]) * np.log(self.logit_scale_init) 36 | if learnable: 37 | self.log_logit_scale = nn.Parameter(log_logit_scale) 38 | else: 39 | self.register_buffer("log_logit_scale", log_logit_scale) 40 | 41 | def forward(self, x): 42 | return torch.clip(self.log_logit_scale.exp(), max=self.max_logit_scale) * x 43 | 44 | def extra_repr(self): 45 | st = f"logit_scale_init={self.logit_scale_init},learnable={self.learnable}," \ 46 | f" max_logit_scale={self.max_logit_scale}" 47 | return st 48 | 49 | 50 | class EinOpsRearrange(nn.Module): 51 | def __init__(self, rearrange_expr: str, **kwargs) -> None: 52 | super().__init__() 53 | self.rearrange_expr = rearrange_expr 54 | self.kwargs = kwargs 55 | 56 | def forward(self, x): 57 | assert isinstance(x, torch.Tensor) 58 | return einops.rearrange(x, self.rearrange_expr, **self.kwargs) 59 | 60 | 61 | class VerboseNNModule(nn.Module): 62 | """ 63 | Wrapper around nn.Module that prints registered buffers and parameter names. 64 | """ 65 | 66 | @staticmethod 67 | def get_readable_tensor_repr(name: str, tensor: torch.Tensor) -> str: 68 | st = ( 69 | "(" 70 | + name 71 | + "): " 72 | + "tensor(" 73 | + str(tuple(tensor[1].shape)) 74 | + ", requires_grad=" 75 | + str(tensor[1].requires_grad) 76 | + ")\n" 77 | ) 78 | return st 79 | 80 | def extra_repr(self) -> str: 81 | named_modules = set() 82 | for p in self.named_modules(): 83 | named_modules.update([p[0]]) 84 | named_modules = list(named_modules) 85 | 86 | string_repr = "" 87 | for p in self.named_parameters(): 88 | name = p[0].split(".")[0] 89 | if name not in named_modules: 90 | string_repr += self.get_readable_tensor_repr(name, p) 91 | 92 | for p in self.named_buffers(): 93 | name = p[0].split(".")[0] 94 | string_repr += self.get_readable_tensor_repr(name, p) 95 | 96 | return string_repr 97 | 98 | 99 | def cast_if_src_dtype( 100 | tensor: torch.Tensor, src_dtype: torch.dtype, tgt_dtype: torch.dtype 101 | ): 102 | updated = False 103 | if tensor.dtype == src_dtype: 104 | tensor = tensor.to(dtype=tgt_dtype) 105 | updated = True 106 | return tensor, updated 107 | 108 | 109 | class QuickGELU(nn.Module): 110 | # From https://github.com/openai/CLIP/blob/d50d76daa670286dd6cacf3bcd80b5e4823fc8e1/clip/model.py#L166 111 | def forward(self, x: torch.Tensor): 112 | return x * torch.sigmoid(1.702 * x) 113 | 114 | 115 | class SelectElement(nn.Module): 116 | def __init__(self, index) -> None: 117 | super().__init__() 118 | self.index = index 119 | 120 | def forward(self, x): 121 | assert x.ndim >= 3 122 | return x[:, self.index, ...] 123 | 124 | 125 | class SelectEOSAndProject(nn.Module): 126 | """ 127 | Text Pooling used in OpenCLIP 128 | """ 129 | 130 | def __init__(self, proj: nn.Module) -> None: 131 | super().__init__() 132 | self.proj = proj 133 | 134 | def forward(self, x, seq_len): 135 | assert x.ndim == 3 136 | # x is of shape B x L x D 137 | # take features from the eot embedding (eot_token is the highest number in each sequence) 138 | x = x[torch.arange(x.shape[0]), seq_len] 139 | x = self.proj(x) 140 | return x 141 | -------------------------------------------------------------------------------- /ImageBind/model_card.md: -------------------------------------------------------------------------------- 1 | # Model Card for ImageBind 2 | 3 | Multimodal joint embedding model for image/video, text, audio, depth, IMU, and thermal images. 4 | Input any of the six modalities and get the same sized embedding that can be used for cross-modal and multimodal tasks. 5 | 6 | # Model Details 7 | 8 | ## Model Description 9 | 10 | 11 | Multimodal joint embedding model for image/video, text, audio, depth, IMU, and thermal images 12 | 13 | - **Developed by:** Meta AI 14 | - **Model type:** Multimodal model 15 | - **Language(s) (NLP):** en 16 | - **License:** CC BY-NC-SA 4.0 17 | - **Resources for more information:** 18 | - [GitHub Repo](https://github.com/facebookresearch/ImageBind) 19 | 20 | 21 | # Uses 22 | 23 | 24 | This model is intended only for research purposes. It provides a joint embedding space for different modalities -- image/video, text, audio, depth, IMU and thermal images. 25 | We hope that these joint embeddings can be used for a variety of different cross-modal research, e.g., cross-modal retrieval and combining embeddings from different modalities. 26 | 27 | ## Out-of-Scope Use 28 | 29 | 30 | 31 | 32 | This model is *NOT* intended to be used in any real world application -- commercial or otherwise. 33 | It may produce harmful associations with different inputs. 34 | The model needs to be investigated and likely re-trained on specific data for any such application. 35 | The model is expected to work better on web-based visual data since it was trained on such data. 36 | The text encoder is likely to work only on English language text because of the underlying training datasets. 37 | 38 | # Bias, Risks, and Limitations 39 | 40 | 41 | Open-domain joint embedding models are prone to producing specific biases, e.g., study from [CLIP](https://github.com/openai/CLIP/blob/main/model-card.md#bias-and-fairness). 42 | Since our model uses such models as initialization, it will exhibit such biases too. 43 | Moreover, for learning joint embeddings for other modalities such as audio, thermal, depth, and IMU we leverage datasets that are relatively small. These joint embeddings are thus limited to the concepts present in the datasets. For example, the thermal datasets we used are limited to outdoor street scenes, while the depth datasets are limited to indoor scenes. 44 | 45 | 46 | 47 | # Training Details 48 | 49 | ## Training Data 50 | 51 | 52 | 53 | ImageBind uses image-paired data for training -- (image, X) where X is one of text, audio, depth, IMU or thermal data. 54 | In particular, we initialize and freeze the image and text encoders using an OpenCLIP ViT-H encoder. 55 | We train audio embeddings using Audioset, depth embeddings using the SUN RGB-D dataset, IMU using the Ego4D dataset and thermal embeddings using the LLVIP dataset. 56 | We provide the exact training data details in the paper. 57 | 58 | 59 | ## Training Procedure 60 | 61 | 62 | Please refer to the research paper and github repo for exact details on this. 63 | 64 | # Evaluation 65 | 66 | ## Testing Data, Factors & Metrics 67 | 68 | We evaluate the model on a variety of different classification benchmarks for each modality. 69 | The evaluation details are presented in the paper. 70 | The models performance is measured using standard classification metrics such as accuracy and mAP. 71 | 72 | # Citation 73 | 74 | 75 | 76 | **BibTeX:** 77 | ``` 78 | @inproceedings{girdhar2023imagebind, 79 | title={ImageBind: One Embedding Space To Bind Them All}, 80 | author={Girdhar, Rohit and El-Nouby, Alaaeldin and Liu, Zhuang 81 | and Singh, Mannat and Alwala, Kalyan Vasudev and Joulin, Armand and Misra, Ishan}, 82 | booktitle={CVPR}, 83 | year={2023} 84 | } 85 | ``` 86 | 87 | 88 | # Model Card Contact 89 | 90 | Please reach out to the authors at: rgirdhar@meta.com imisra@meta.com alaaelnouby@gmail.com 91 | 92 | # How to Get Started with the Model 93 | 94 | Our github repo provides a simple example to extract embeddings from images, audio etc. 95 | -------------------------------------------------------------------------------- /fundus_prep.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import os 3 | import cv2 4 | 5 | 6 | def imread(file_path, c=None): 7 | if c is None: 8 | im = cv2.imread(file_path) 9 | else: 10 | im = cv2.imread(file_path, c) 11 | 12 | if im is None: 13 | raise 'Can not read image' 14 | 15 | if im.ndim == 3 and im.shape[2] == 3: 16 | im = cv2.cvtColor(im, cv2.COLOR_BGR2RGB) 17 | return im 18 | 19 | 20 | def imwrite(file_path, image): 21 | if image.ndim == 3 and image.shape[2] == 3: 22 | image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR) 23 | cv2.imwrite(file_path, image) 24 | 25 | 26 | def fold_dir(folder): 27 | if not os.path.exists(folder): 28 | os.makedirs(folder) 29 | return folder 30 | 31 | 32 | def get_mask_BZ(img): 33 | if img.ndim==3: 34 | gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) 35 | else: 36 | gray_img = img 37 | threhold = np.mean(gray_img)/3-5 38 | #cv2.imshow('gray_img', gray_img) 39 | #cv2.waitKey() 40 | #print(threhold) 41 | _, mask = cv2.threshold(gray_img, max(5,threhold), 1, cv2.THRESH_BINARY) 42 | 43 | #cv2.imshow('bz_mask', mask*255) 44 | #cv2.waitKey() 45 | nn_mask = np.zeros((mask.shape[0]+2,mask.shape[1]+2),np.uint8) 46 | new_mask = (1-mask).astype(np.uint8) 47 | # cv::floodFill(Temp, Point(0, 0), Scalar(255)); 48 | # _,new_mask,_,_ = cv2.floodFill(new_mask, nn_mask, [(0, 0),(0,new_mask.shape[0])], (0), cv2.FLOODFILL_MASK_ONLY) 49 | _,new_mask,_,_ = cv2.floodFill(new_mask, nn_mask, (0,0), (0), cv2.FLOODFILL_MASK_ONLY) 50 | _,new_mask,_,_ = cv2.floodFill(new_mask, nn_mask, (new_mask.shape[1]-1,new_mask.shape[0]-1), (0), cv2.FLOODFILL_MASK_ONLY) 51 | mask = mask + new_mask 52 | kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (20, 20)) 53 | mask = cv2.erode(mask, kernel) 54 | mask = cv2.dilate(mask, kernel) 55 | return mask 56 | 57 | 58 | def _get_center_by_edge(mask): 59 | center=[0,0] 60 | x=mask.sum(axis=1) 61 | center[0]=np.where(x>x.max()*0.95)[0].mean() 62 | x=mask.sum(axis=0) 63 | center[1]=np.where(x>x.max()*0.95)[0].mean() 64 | return center 65 | 66 | 67 | def _get_radius_by_mask_center(mask,center): 68 | mask=mask.astype(np.uint8) 69 | ksize=max(mask.shape[1]//400*2+1,3) 70 | kernel=cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(ksize,ksize)) 71 | mask=cv2.morphologyEx(mask, cv2.MORPH_GRADIENT, kernel) 72 | # radius= 73 | index=np.where(mask>0) 74 | d_int=np.sqrt((index[0]-center[0])**2+(index[1]-center[1])**2) 75 | b_count=np.bincount(np.ceil(d_int).astype(np.int_)) 76 | radius=np.where(b_count>b_count.max()*0.995)[0].max() 77 | return radius 78 | 79 | 80 | def _get_circle_by_center_bbox(shape,center,bbox,radius): 81 | center_mask=np.zeros(shape=shape).astype('uint8') 82 | tmp_mask=np.zeros(shape=bbox[2:4]) 83 | center_tmp=(int(center[0]),int(center[1])) 84 | center_mask=cv2.circle(center_mask,center_tmp[::-1],int(radius),(1),-1) 85 | # center_mask[bbox[0]:bbox[0]+bbox[2],bbox[1]:bbox[1]+bbox[3]]=tmp_mask 86 | # center_mask[bbox[0]:min(bbox[0]+bbox[2],center_mask.shape[0]),bbox[1]:min(bbox[1]+bbox[3],center_mask.shape[1])]=tmp_mask 87 | return center_mask 88 | 89 | 90 | def get_mask(img): 91 | if img.ndim ==3: 92 | #raise 'image dim is not 3' 93 | g_img=cv2.cvtColor(img,cv2.COLOR_RGB2GRAY) 94 | #cv2.imshow('ImageWindow', g_img) 95 | #cv2.waitKey() 96 | elif img.ndim == 2: 97 | g_img =img.copy() 98 | else: 99 | raise 'image dim is not 1 or 3' 100 | h,w = g_img.shape 101 | shape=g_img.shape[0:2] 102 | #g_img = cv2.resize(g_img,(0,0),fx = 0.5,fy = 0.5) 103 | tg_img=cv2.normalize(g_img, None, 0, 255, cv2.NORM_MINMAX) 104 | tmp_mask=get_mask_BZ(tg_img) 105 | center=_get_center_by_edge(tmp_mask) 106 | #bbox=_get_bbox_by_mask(tmp_mask) 107 | #print(center) 108 | #cv2.imshow('ImageWindow', tmp_mask*255) 109 | #cv2.waitKey() 110 | radius=_get_radius_by_mask_center(tmp_mask,center) 111 | #resize back 112 | #center = [center[0]*2,center[1]*2] 113 | #radius = int(radius*2) 114 | 115 | center = [center[0], center[1]] 116 | radius = int(radius) 117 | s_h = max(0,int(center[0] - radius)) 118 | s_w = max(0, int(center[1] - radius)) 119 | bbox = (s_h, s_w, min(h-s_h,2 * radius), min(w-s_w,2 * radius)) 120 | tmp_mask=_get_circle_by_center_bbox(shape,center,bbox,radius) 121 | return tmp_mask,bbox,center,radius 122 | 123 | 124 | def mask_image(img,mask): 125 | img[mask<=0,...]=0 126 | return img 127 | 128 | 129 | def remove_back_area(img,bbox=None,border=None): 130 | image=img 131 | if border is None: 132 | border=np.array((bbox[0],bbox[0]+bbox[2],bbox[1],bbox[1]+bbox[3],img.shape[0],img.shape[1]),dtype=np.int_) 133 | image=image[border[0]:border[1],border[2]:border[3],...] 134 | return image,border 135 | 136 | 137 | def supplemental_black_area(img,border=None): 138 | image=img 139 | if border is None: 140 | h,v=img.shape[0:2] 141 | max_l=max(h,v) 142 | if image.ndim>2: 143 | image=np.zeros(shape=[max_l,max_l,img.shape[2]],dtype=img.dtype) 144 | else: 145 | image=np.zeros(shape=[max_l,max_l],dtype=img.dtype) 146 | border=(int(max_l/2-h/2),int(max_l/2-h/2)+h,int(max_l/2-v/2),int(max_l/2-v/2)+v,max_l) 147 | else: 148 | max_l=border[4] 149 | if image.ndim>2: 150 | image=np.zeros(shape=[max_l,max_l,img.shape[2]],dtype=img.dtype) 151 | else: 152 | image=np.zeros(shape=[max_l,max_l],dtype=img.dtype) 153 | image[border[0]:border[1],border[2]:border[3],...]=img 154 | return image,border 155 | 156 | 157 | def process_without_gb(img, label): 158 | # preprocess images 159 | # img : origin image 160 | # tar_height: height of tar image 161 | # return: 162 | # result_img: preprocessed image 163 | # borders: remove border, supplement mask 164 | # mask: mask for preprocessed image 165 | borders = [] 166 | mask, bbox, center, radius = get_mask(img) 167 | #print('center is: ',center) 168 | #print('radius is: ',radius) 169 | r_img = mask_image(img, mask) 170 | r_img, r_border = remove_back_area(r_img,bbox=bbox) 171 | mask, _ = remove_back_area(mask,border=r_border) 172 | label, _ = remove_back_area(label,bbox=bbox) 173 | borders.append(r_border) 174 | r_img,sup_border = supplemental_black_area(r_img) 175 | #print(r_img.shape) 176 | label,sup_border = supplemental_black_area(label) 177 | mask,_ = supplemental_black_area(mask,border=sup_border) 178 | borders.append(sup_border) 179 | 180 | return r_img,borders,(mask*255).astype(np.uint8),label #, radius_list,centre_list_w, centre_list_h 181 | 182 | -------------------------------------------------------------------------------- /llama/LViT.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | import torch 3 | import torch.nn as nn 4 | import torch.nn.functional as F 5 | 6 | from .Vit import VisionTransformer, Reconstruct 7 | from .pixlevel import PixLevelModule 8 | 9 | 10 | def get_activation(activation_type): 11 | activation_type = activation_type.lower() 12 | if hasattr(nn, activation_type): 13 | return getattr(nn, activation_type)() 14 | else: 15 | return nn.ReLU() 16 | 17 | 18 | def _make_nConv(in_channels, out_channels, nb_Conv, activation='ReLU'): 19 | layers = [] 20 | layers.append(ConvBatchNorm(in_channels, out_channels, activation)) 21 | for _ in range(nb_Conv - 1): 22 | layers.append(ConvBatchNorm(out_channels, out_channels, activation)) 23 | return nn.Sequential(*layers) 24 | 25 | 26 | class ConvBatchNorm(nn.Module): 27 | """(convolution => [BN] => ReLU)""" 28 | 29 | def __init__(self, in_channels, out_channels, activation='ReLU'): 30 | super(ConvBatchNorm, self).__init__() 31 | self.conv = nn.Conv2d(in_channels, out_channels, 32 | kernel_size=3, padding=1) 33 | self.norm = nn.BatchNorm2d(out_channels) 34 | self.activation = get_activation(activation) 35 | 36 | def forward(self, x): 37 | out = self.conv(x) 38 | out = self.norm(out) 39 | return self.activation(out) 40 | 41 | 42 | class DownBlock(nn.Module): 43 | """Downscaling with maxpool convolution""" 44 | 45 | def __init__(self, in_channels, out_channels, nb_Conv, activation='ReLU'): 46 | super(DownBlock, self).__init__() 47 | self.maxpool = nn.MaxPool2d(2) 48 | self.nConvs = _make_nConv(in_channels, out_channels, nb_Conv, activation) 49 | 50 | def forward(self, x): 51 | out = self.maxpool(x) 52 | return self.nConvs(out) 53 | 54 | 55 | class Flatten(nn.Module): 56 | def forward(self, x): 57 | return x.view(x.size(0), -1) 58 | 59 | 60 | class UpblockAttention(nn.Module): 61 | def __init__(self, in_channels, out_channels, nb_Conv, activation='ReLU'): 62 | super().__init__() 63 | self.up = nn.Upsample(scale_factor=2) 64 | self.pixModule = PixLevelModule(in_channels // 2) 65 | self.nConvs = _make_nConv(in_channels, out_channels, nb_Conv, activation) 66 | 67 | def forward(self, x, skip_x): 68 | up = self.up(x) 69 | skip_x_att = self.pixModule(skip_x) 70 | x = torch.cat([skip_x_att, up], dim=1) # dim 1 is the channel dimension 71 | return self.nConvs(x) 72 | 73 | 74 | class LViT(nn.Module): 75 | def __init__(self, config, n_channels=3, n_classes=1, img_size=224, vis=False): 76 | super().__init__() 77 | self.vis = vis 78 | self.n_channels = n_channels 79 | self.n_classes = n_classes 80 | in_channels = config.base_channel 81 | self.inc = ConvBatchNorm(n_channels, in_channels) 82 | self.downVit = VisionTransformer(config, vis, img_size=224, channel_num=64, patch_size=16, embed_dim=64) 83 | self.downVit1 = VisionTransformer(config, vis, img_size=112, channel_num=128, patch_size=8, embed_dim=128) 84 | self.downVit2 = VisionTransformer(config, vis, img_size=56, channel_num=256, patch_size=4, embed_dim=256) 85 | self.downVit3 = VisionTransformer(config, vis, img_size=28, channel_num=512, patch_size=2, embed_dim=512) 86 | self.upVit = VisionTransformer(config, vis, img_size=224, channel_num=64, patch_size=16, embed_dim=64) 87 | self.upVit1 = VisionTransformer(config, vis, img_size=112, channel_num=128, patch_size=8, embed_dim=128) 88 | self.upVit2 = VisionTransformer(config, vis, img_size=56, channel_num=256, patch_size=4, embed_dim=256) 89 | self.upVit3 = VisionTransformer(config, vis, img_size=28, channel_num=512, patch_size=2, embed_dim=512) 90 | self.down1 = DownBlock(in_channels, in_channels * 2, nb_Conv=2) 91 | self.down2 = DownBlock(in_channels * 2, in_channels * 4, nb_Conv=2) 92 | self.down3 = DownBlock(in_channels * 4, in_channels * 8, nb_Conv=2) 93 | self.down4 = DownBlock(in_channels * 8, in_channels * 8, nb_Conv=2) 94 | self.up4 = UpblockAttention(in_channels * 16, in_channels * 4, nb_Conv=2) 95 | self.up3 = UpblockAttention(in_channels * 8, in_channels * 2, nb_Conv=2) 96 | self.up2 = UpblockAttention(in_channels * 4, in_channels, nb_Conv=2) 97 | self.up1 = UpblockAttention(in_channels * 2, in_channels, nb_Conv=2) 98 | self.outc = nn.Conv2d(in_channels, n_classes, kernel_size=(1, 1), stride=(1, 1)) 99 | self.last_activation = nn.Sigmoid() # if using BCELoss 100 | self.multi_activation = nn.Softmax() 101 | self.reconstruct1 = Reconstruct(in_channels=64, out_channels=64, kernel_size=1, scale_factor=(16, 16)) 102 | self.reconstruct2 = Reconstruct(in_channels=128, out_channels=128, kernel_size=1, scale_factor=(8, 8)) 103 | self.reconstruct3 = Reconstruct(in_channels=256, out_channels=256, kernel_size=1, scale_factor=(4, 4)) 104 | self.reconstruct4 = Reconstruct(in_channels=512, out_channels=512, kernel_size=1, scale_factor=(2, 2)) 105 | self.pix_module1 = PixLevelModule(64) 106 | self.pix_module2 = PixLevelModule(128) 107 | self.pix_module3 = PixLevelModule(256) 108 | self.pix_module4 = PixLevelModule(512) 109 | self.text_module4 = nn.Conv1d(in_channels=768, out_channels=512, kernel_size=3, padding=1) 110 | self.text_module3 = nn.Conv1d(in_channels=512, out_channels=256, kernel_size=3, padding=1) 111 | self.text_module2 = nn.Conv1d(in_channels=256, out_channels=128, kernel_size=3, padding=1) 112 | self.text_module1 = nn.Conv1d(in_channels=128, out_channels=64, kernel_size=3, padding=1) 113 | self.fc = nn.Conv1d(in_channels=196, out_channels=8, kernel_size=1) 114 | 115 | def forward(self, x, text): 116 | x = x.float() # x [4,3,224,224] 117 | x1 = self.inc(x) # x1 [4, 64, 224, 224] 118 | # text4 = self.text_module4(text.transpose(1, 2)).transpose(1, 2) 119 | # text3 = self.text_module3(text4.transpose(1, 2)).transpose(1, 2) 120 | # text2 = self.text_module2(text3.transpose(1, 2)).transpose(1, 2) 121 | # text1 = self.text_module1(text2.transpose(1, 2)).transpose(1, 2) 122 | text1 = text 123 | text2 = text 124 | text3 = text 125 | text4 = text 126 | y1 = self.downVit(x1, x1, text1) 127 | x2 = self.down1(x1) 128 | y2 = self.downVit1(x2, y1, text2) 129 | x3 = self.down2(x2) 130 | y3 = self.downVit2(x3, y2, text3) 131 | x4 = self.down3(x3) 132 | y4 = self.downVit3(x4, y3, text4) # y4 [8, 196, 512] 133 | x5 = self.fc(y4) 134 | # x5 = self.down4(x4) 135 | # y4 = self.upVit3(y4, y4, text4, True) 136 | # y3 = self.upVit2(y3, y4, text3, True) 137 | # y2 = self.upVit1(y2, y3, text2, True) 138 | # y1 = self.upVit(y1, y2, text1, True) 139 | # x1 = self.reconstruct1(y1) + x1 140 | # x2 = self.reconstruct2(y2) + x2 141 | # x3 = self.reconstruct3(y3) + x3 142 | # x4 = self.reconstruct4(y4) + x4 143 | # print(y4.shape) 144 | # x = self.up4(x5, x4) 145 | # print('x', x.shape) # [8, 256, 28, 28] 146 | # x = self.up3(x, x3) 147 | # x = self.up2(x, x2) 148 | # x = self.up1(x, x1) 149 | # if self.n_classes == 1: 150 | # logits = self.last_activation(self.outc(x)) 151 | # else: 152 | # logits = self.outc(x) # if not using BCEWithLogitsLoss or class>1 153 | return x5 154 | -------------------------------------------------------------------------------- /engine_pretrain.py: -------------------------------------------------------------------------------- 1 | import math 2 | import sys 3 | from typing import Iterable 4 | 5 | import torch 6 | import torch.utils.checkpoint as cp 7 | import util.misc as misc 8 | import util.lr_sched as lr_sched 9 | import numpy as np 10 | 11 | from llama import LLaMA_adapter 12 | 13 | def train_one_epoch(model: LLaMA_adapter, 14 | data_loader: Iterable, optimizer: torch.optim.Optimizer, 15 | device: torch.device, epoch: int, loss_scaler, 16 | log_writer=None, 17 | args=None): 18 | model.train(True) 19 | model.module.set_default_trainability() 20 | 21 | metric_logger = misc.MetricLogger(delimiter=" ") 22 | metric_logger.add_meter('lr', misc.SmoothedValue(window_size=1, fmt='{value:.6f}')) 23 | header = 'Epoch: [{}]'.format(epoch) 24 | print_freq = 10 25 | use_checkpoint = args.use_checkpoint 26 | accum_iter = args.accum_iter 27 | 28 | optimizer.zero_grad() 29 | 30 | if log_writer is not None: 31 | print('log_dir: {}'.format(log_writer.log_dir)) 32 | # print(device) 33 | for data_iter_step, (examples, labels, example_mask, imgs, Keyword) in enumerate(metric_logger.log_every(data_loader, print_freq, header)): 34 | # we use a per iteration (instead of per epoch) lr scheduler 35 | if data_iter_step % accum_iter == 0: 36 | lr_sched.adjust_learning_rate(optimizer, data_iter_step / len(data_loader) + epoch, args) 37 | imgs = imgs.to(device, non_blocking=True).half() 38 | # for index in range(len(example_mask)): 39 | coocurrence = np.array( 40 | [[iDesc == iiDesc for iDesc in Keyword] for iiDesc in Keyword], np.float32) 41 | target = torch.tensor(coocurrence / coocurrence.sum(-1)).to(device).to(torch.float32) 42 | 43 | example_mask[0] = example_mask[0].type(torch.LongTensor).to(device) 44 | example_mask[1] = example_mask[1].type(torch.LongTensor).to(device) 45 | example_mask[2] = example_mask[2].type(torch.LongTensor).to(device) 46 | example_mask[3] = example_mask[3].type(torch.LongTensor).to(device) 47 | example_mask[4] = example_mask[4].type(torch.LongTensor).to(device) 48 | example_mask[5] = example_mask[5].type(torch.LongTensor).to(device) 49 | examples = examples.to(device, non_blocking=True) 50 | labels = labels.to(device, non_blocking=True) 51 | with torch.cuda.amp.autocast(): 52 | c_loss, m_loss, clip_loss = model(examples, labels, imgs, example_mask, Keyword, target) 53 | loss = c_loss + m_loss + clip_loss 54 | loss_value = loss.item() 55 | c_loss_value = c_loss.item() 56 | m_loss_value = m_loss.item() 57 | clip_loss_value = clip_loss.item() 58 | 59 | if not math.isfinite(loss_value): 60 | print("Loss is {}, stopping training".format(loss_value)) 61 | sys.exit(1) 62 | 63 | loss /= accum_iter 64 | 65 | loss_scaler(loss, optimizer, clip_grad = 10, parameters=model.parameters(), 66 | update_grad=(data_iter_step + 1) % accum_iter == 0) 67 | if (data_iter_step + 1) % accum_iter == 0: 68 | optimizer.zero_grad() 69 | 70 | torch.cuda.synchronize() 71 | 72 | # metric_logger.update(loss=loss_value) 73 | metric_logger.update(closs=c_loss_value) 74 | metric_logger.update(mloss=m_loss_value) 75 | metric_logger.update(cliploss=clip_loss_value) 76 | 77 | lr = optimizer.param_groups[0]["lr"] 78 | metric_logger.update(lr=lr) 79 | 80 | # loss_value_reduce = misc.all_reduce_mean(loss_value) 81 | c_loss_value_reduce = misc.all_reduce_mean(c_loss_value) 82 | m_loss_value_reduce = misc.all_reduce_mean(m_loss_value) 83 | clip_loss_value_reduce = misc.all_reduce_mean(clip_loss_value) 84 | 85 | if log_writer is not None and (data_iter_step + 1) % accum_iter == 0: 86 | """ We use epoch_1000x as the x-axis in tensorboard. 87 | This calibrates different curves when batch size changes. 88 | """ 89 | epoch_1000x = int((data_iter_step / len(data_loader) + epoch) * 1000) 90 | # log_writer.add_scalar('train_loss', loss_value_reduce, epoch_1000x) 91 | log_writer.add_scalar('c_train_loss', c_loss_value_reduce, epoch_1000x) 92 | log_writer.add_scalar('m_train_loss', m_loss_value_reduce, epoch_1000x) 93 | log_writer.add_scalar('clip_train_loss', clip_loss_value_reduce, epoch_1000x) 94 | log_writer.add_scalar('lr', lr, epoch_1000x) 95 | 96 | 97 | # gather the stats from all processes 98 | metric_logger.synchronize_between_processes() 99 | print("Averaged stats:", metric_logger) 100 | return {k: meter.global_avg for k, meter in metric_logger.meters.items()} 101 | 102 | 103 | def val_one_epoch(model: torch.nn.Module, 104 | data_loader: Iterable, optimizer: torch.optim.Optimizer, 105 | device: torch.device, epoch: int, loss_scaler, 106 | log_writer=None, 107 | args=None): 108 | model.eval() 109 | metric_logger = misc.MetricLogger(delimiter=" ") 110 | metric_logger.add_meter('lr', misc.SmoothedValue(window_size=1, fmt='{value:.6f}')) 111 | header = 'Epoch: [{}]'.format(epoch) 112 | print_freq = 10 113 | 114 | accum_iter = args.accum_iter 115 | 116 | if log_writer is not None: 117 | print('log_dir: {}'.format(log_writer.log_dir)) 118 | for data_iter_step, (examples, labels, example_mask, imgs) in enumerate(metric_logger.log_every(data_loader, print_freq, header)): 119 | imgs = imgs.to(device, non_blocking=True) 120 | example_mask = example_mask.type(torch.LongTensor).to(device) 121 | with torch.no_grad(): 122 | # c_loss, m_loss, _, _ = model(examples, labels, imgs) 123 | c_loss, m_loss = model(examples, labels, imgs, example_mask) 124 | # loss = c_loss + m_loss * 0 125 | loss = c_loss + m_loss 126 | loss_value = loss.item() 127 | c_loss_value = c_loss.item() 128 | m_loss_value = m_loss.item() 129 | if not math.isfinite(loss_value): 130 | print("Loss is {}, stopping training".format(loss_value)) 131 | sys.exit(1) 132 | 133 | 134 | metric_logger.update(closs=c_loss_value) 135 | metric_logger.update(mloss=m_loss_value) 136 | 137 | lr = optimizer.param_groups[0]["lr"] 138 | metric_logger.update(lr=lr) 139 | 140 | # loss_value_reduce = misc.all_reduce_mean(loss_value) 141 | c_loss_value_reduce = misc.all_reduce_mean(c_loss_value) 142 | m_loss_value_reduce = misc.all_reduce_mean(m_loss_value) 143 | if log_writer is not None and (data_iter_step + 1) % accum_iter == 0: 144 | """ We use epoch_1000x as the x-axis in tensorboard. 145 | This calibrates different curves when batch size changes. 146 | """ 147 | epoch_1000x = int((data_iter_step / len(data_loader) + epoch) * 1000) 148 | # log_writer.add_scalar('val_loss', loss_value_reduce, epoch_1000x) 149 | log_writer.add_scalar('c_train_loss', c_loss_value_reduce, epoch_1000x) 150 | log_writer.add_scalar('m_train_loss', m_loss_value_reduce, epoch_1000x) 151 | log_writer.add_scalar('lr', lr, epoch_1000x) 152 | 153 | 154 | # gather the stats from all processes 155 | metric_logger.synchronize_between_processes() 156 | print("Averaged stats:", metric_logger) 157 | return {k: meter.global_avg for k, meter in metric_logger.meters.items()} 158 | 159 | -------------------------------------------------------------------------------- /llama/Vit.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | import torch 4 | import torch.nn as nn 5 | import numpy as np 6 | from timm.models.layers import DropPath 7 | from torch.nn import Dropout, Conv2d 8 | from torch.nn.modules.utils import _pair 9 | 10 | class Reconstruct(nn.Module): 11 | def __init__(self, in_channels, out_channels, kernel_size, scale_factor): 12 | super(Reconstruct, self).__init__() 13 | if kernel_size == 3: 14 | padding = 1 15 | else: 16 | padding = 0 17 | self.conv = nn.Conv2d(in_channels, out_channels, kernel_size=kernel_size, padding=padding) 18 | self.norm = nn.BatchNorm2d(out_channels) 19 | self.activation = nn.ReLU(inplace=True) 20 | self.scale_factor = scale_factor 21 | 22 | def forward(self, x): 23 | if x is None: 24 | return None 25 | 26 | B, n_patch, hidden = x.size() # reshape from (B, n_patch, hidden) to (B, h, w, hidden) 27 | h, w = int(np.sqrt(n_patch)), int(np.sqrt(n_patch)) 28 | x = x.permute(0, 2, 1) 29 | x = x.contiguous().view(B, hidden, h, w) 30 | x = nn.Upsample(scale_factor=self.scale_factor)(x) 31 | 32 | out = self.conv(x) 33 | out = self.norm(out) 34 | out = self.activation(out) 35 | return out 36 | 37 | 38 | class Embeddings(nn.Module): 39 | # Construct the patch, position embeddings 40 | def __init__(self, config, patch_size, img_size, in_channels): 41 | super().__init__() 42 | img_size = _pair(img_size) 43 | patch_size = _pair(patch_size) 44 | n_patches = (img_size[0] // patch_size[0]) * (img_size[1] // patch_size[1]) 45 | # img_size[0]=img 46 | # patch_size[0]=patch_size[1] [16, 8, 4, 2] 47 | self.patch_embeddings = Conv2d(in_channels=in_channels, 48 | out_channels=in_channels, 49 | kernel_size=patch_size, 50 | stride=patch_size) 51 | self.position_embeddings = nn.Parameter(torch.zeros(1, n_patches, in_channels)) 52 | self.dropout = Dropout(0.1) 53 | 54 | def forward(self, x): 55 | if x is None: 56 | return None 57 | x = self.patch_embeddings(x) # (B, hidden. n_patches^(1/2), n_patches^(1/2)) 58 | x = x.flatten(2) 59 | x = x.transpose(-1, -2) # (B, n_patches, hidden) 60 | embeddings = x + self.position_embeddings 61 | embeddings = self.dropout(embeddings) 62 | return embeddings 63 | 64 | 65 | class MLP(nn.Module): 66 | def __init__(self, in_dim, hidden_dim=None, out_dim=None): 67 | super().__init__() 68 | self.fc1 = nn.Linear(in_dim, hidden_dim) 69 | self.act_layer = nn.GELU() 70 | self.fc2 = nn.Linear(hidden_dim, out_dim) 71 | self.dropout = Dropout(0.1) 72 | self._init_weights() 73 | 74 | def _init_weights(self): 75 | nn.init.xavier_uniform_(self.fc1.weight) 76 | nn.init.xavier_uniform_(self.fc2.weight) 77 | nn.init.normal_(self.fc1.bias, std=1e-6) 78 | nn.init.normal_(self.fc2.bias, std=1e-6) 79 | 80 | def forward(self, x): 81 | x = self.fc1(x) # [B, num_patches, hidden_dim] 82 | x = self.act_layer(x) 83 | x = self.dropout(x) 84 | x = self.fc2(x) # [B, num_patches, out_dim] 85 | x = self.act_layer(x) 86 | x = self.dropout(x) 87 | return x 88 | 89 | 90 | class Attention(nn.Module): 91 | def __init__(self, dim, num_heads=8, qkv_bias=False, attn_drop=0., proj_drop=0.): 92 | super().__init__() 93 | self.num_heads = num_heads 94 | head_dim = dim // num_heads 95 | self.scale = head_dim ** -0.5 96 | 97 | self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) 98 | self.attn_drop = nn.Dropout(attn_drop) 99 | self.proj = nn.Linear(dim, dim) 100 | self.proj_drop = nn.Dropout(proj_drop) 101 | 102 | def forward(self, x): 103 | B, N, C = x.shape 104 | qkv = self.qkv(x) # [B, num_patches, 3*embed_dim] 105 | qkv = qkv.reshape(B, N, 3, self.num_heads, C // self.num_heads) # [B, num_patches, 3, num_heads, per_HeadDim] 106 | qkv = qkv.permute(2, 0, 3, 1, 4) # [3, B, num_heads, num_patches, per_HeadDim] 107 | q, k, v = qkv[0], qkv[1], qkv[2] # [B, num_heads, num_patches, per_HeadDim] [4, 8, 196, 8/16/32/64] easy to use tensor 108 | 109 | attn = (q @ k.transpose(-2, -1)) * self.scale # [B, num_heads, num_patches, num_patches] 110 | attn = attn.softmax(dim=-1) 111 | attn = self.attn_drop(attn) 112 | x = (attn @ v) # [B, num_heads, num_patches, per_HeadDim] 113 | x = x.transpose(1, 2) # [B, num_patches, num_heads, per_HeadDim] 114 | x = x.reshape(B, N, C) # [B, num_patches, embed_dim] 115 | x = self.proj(x) # [B, num_patches, embed_dim] 116 | x = self.proj_drop(x) 117 | return x 118 | 119 | 120 | class Block(nn.Module): 121 | def __init__(self, dim, num_heads, mlp_ratio=4., qkv_bias=False, drop=0., attn_drop=0., 122 | drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm): 123 | super().__init__() 124 | self.norm1 = norm_layer(dim) 125 | self.attn = Attention(dim, num_heads=num_heads, qkv_bias=qkv_bias, attn_drop=attn_drop, proj_drop=drop) 126 | self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity() 127 | self.norm2 = norm_layer(dim) 128 | self.mlp_hidden_dim = int(dim * mlp_ratio) 129 | self.mlp = MLP(in_dim=dim, hidden_dim=self.mlp_hidden_dim, out_dim=dim) 130 | 131 | def forward(self, x): 132 | x = x + self.drop_path(self.attn(self.norm1(x))) 133 | x = x + self.drop_path(self.mlp(self.norm2(x))) 134 | return x 135 | 136 | 137 | class ConvTransBN(nn.Module): # (convolution => [BN] => ReLU) 138 | def __init__(self, in_channels, out_channels): 139 | super(ConvTransBN, self).__init__() 140 | self.conv = nn.Conv1d(in_channels, out_channels, kernel_size=3, padding=1) 141 | self.norm = nn.BatchNorm1d(out_channels) 142 | self.activation = nn.ReLU() 143 | 144 | def forward(self, x): 145 | out = self.conv(x) 146 | out = self.norm(out) 147 | return self.activation(out) 148 | 149 | 150 | class VisionTransformer(nn.Module): # Transformer-branch 151 | def __init__(self, config, vis, img_size, channel_num, patch_size, embed_dim, depth=1, num_heads=8, 152 | mlp_ratio=4., qkv_bias=True, num_classes=1, drop_rate=0., attn_drop_rate=0., drop_path_rate=0.): 153 | super(VisionTransformer, self).__init__() 154 | self.config = config 155 | self.vis = vis 156 | self.embeddings = Embeddings(config=config, patch_size=patch_size, img_size=img_size, in_channels=channel_num) 157 | self.depth = depth 158 | self.dim = embed_dim 159 | norm_layer = nn.LayerNorm 160 | self.norm = norm_layer(embed_dim) 161 | act_layer = nn.GELU 162 | 163 | dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)] # stochastic depth decay rule 164 | self.Encoder_blocks = nn.Sequential(*[ 165 | Block(dim=embed_dim, num_heads=num_heads, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, drop=drop_rate, 166 | attn_drop=attn_drop_rate, drop_path=dpr[i], norm_layer=norm_layer, act_layer=act_layer) 167 | for i in range(self.depth)]) 168 | 169 | self.head = nn.Linear(embed_dim, num_classes) if num_classes > 0 else nn.Identity() 170 | self.CTBN = ConvTransBN(in_channels=embed_dim, out_channels=embed_dim//2) 171 | self.CTBN2 = ConvTransBN(in_channels=embed_dim*2, out_channels=embed_dim) 172 | self.CTBN3 = ConvTransBN(in_channels=10, out_channels=196) 173 | 174 | def forward(self, x, skip_x, text, reconstruct=False): 175 | if not reconstruct: 176 | x = self.embeddings(x) 177 | # if self.dim == 64: 178 | # x = x+self.CTBN3(text) # [B, num_patches, embed_dim] 179 | x = self.Encoder_blocks(x) 180 | else: 181 | x = self.Encoder_blocks(x) 182 | if (self.dim == 64 and not reconstruct) or (self.dim == 512 and reconstruct): 183 | return x 184 | elif not reconstruct: 185 | x = x.transpose(1, 2) # [B, embed_dim, num_patches] 186 | x = self.CTBN(x) # [B, embed_dim//2, num_patches] 187 | x = x.transpose(1, 2) # [B, num_patches, embed_dim//2] 188 | y = torch.cat([x, skip_x], dim=2) # [B, num_patches, embed_dim] 189 | return y 190 | elif reconstruct: 191 | skip_x = skip_x.transpose(1, 2) 192 | skip_x = self.CTBN2(skip_x) 193 | skip_x = skip_x.transpose(1, 2) 194 | y = x+skip_x 195 | return y 196 | -------------------------------------------------------------------------------- /ImageBind/models/transformer.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # Portions Copyright (c) Meta Platforms, Inc. and affiliates. 3 | # All rights reserved. 4 | 5 | # This source code is licensed under the license found in the 6 | # LICENSE file in the root directory of this source tree. 7 | 8 | # Code modified from 9 | # https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/vision_transformer.py ; 10 | # https://github.com/facebookresearch/deit/blob/main/models.py 11 | # and https://github.com/facebookresearch/vissl/blob/main/vissl/models/trunks/vision_transformer.py 12 | 13 | 14 | from functools import partial 15 | from typing import Callable, List, Optional 16 | 17 | import torch 18 | import torch.nn as nn 19 | import torch.utils.checkpoint as checkpoint 20 | from timm.models.layers import DropPath, trunc_normal_ 21 | 22 | 23 | class Attention(nn.Module): 24 | def __init__( 25 | self, 26 | dim, 27 | num_heads=8, 28 | qkv_bias=False, 29 | qk_scale=None, 30 | attn_drop=0.0, 31 | proj_drop=0.0, 32 | ): 33 | super().__init__() 34 | self.num_heads = num_heads 35 | head_dim = dim // num_heads 36 | # NOTE scale factor was wrong in my original version, 37 | # can set manually to be compat with prev weights 38 | self.scale = qk_scale or head_dim**-0.5 39 | 40 | self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) 41 | self.attn_drop = nn.Dropout(attn_drop) 42 | self.proj = nn.Linear(dim, dim) 43 | self.proj_drop = nn.Dropout(proj_drop) 44 | 45 | def forward(self, x): 46 | B, N, C = x.shape 47 | qkv = ( 48 | self.qkv(x) 49 | .reshape(B, N, 3, self.num_heads, C // self.num_heads) 50 | .permute(2, 0, 3, 1, 4) 51 | ) 52 | q, k, v = ( 53 | qkv[0], 54 | qkv[1], 55 | qkv[2], 56 | ) # make torchscript happy (cannot use tensor as tuple) 57 | 58 | attn = (q @ k.transpose(-2, -1)) * self.scale 59 | attn = attn.softmax(dim=-1) 60 | attn = self.attn_drop(attn) 61 | 62 | x = (attn @ v).transpose(1, 2).reshape(B, N, C) 63 | x = self.proj(x) 64 | x = self.proj_drop(x) 65 | return x 66 | 67 | 68 | class Mlp(nn.Module): 69 | def __init__( 70 | self, 71 | in_features, 72 | hidden_features=None, 73 | out_features=None, 74 | act_layer=nn.GELU, 75 | drop=0.0, 76 | ): 77 | super().__init__() 78 | out_features = out_features or in_features 79 | hidden_features = hidden_features or in_features 80 | self.fc1 = nn.Linear(in_features, hidden_features) 81 | self.act = act_layer() 82 | self.fc2 = nn.Linear(hidden_features, out_features) 83 | self.drop = nn.Dropout(drop) 84 | 85 | def forward(self, x): 86 | x = self.fc1(x) 87 | x = self.act(x) 88 | x = self.drop(x) 89 | x = self.fc2(x) 90 | x = self.drop(x) 91 | return x 92 | 93 | 94 | class MultiheadAttention(nn.MultiheadAttention): 95 | def forward(self, x: torch.Tensor, attn_mask: torch.Tensor): 96 | return super().forward(x, x, x, need_weights=False, attn_mask=attn_mask)[0] 97 | 98 | 99 | class ViTAttention(Attention): 100 | def forward(self, x: torch.Tensor, attn_mask: torch.Tensor): 101 | assert attn_mask is None 102 | return super().forward(x) 103 | 104 | 105 | class BlockWithMasking(nn.Module): 106 | def __init__( 107 | self, 108 | dim: int, 109 | attn_target: Callable, 110 | mlp_ratio: int = 4, 111 | act_layer: Callable = nn.GELU, 112 | norm_layer: Callable = nn.LayerNorm, 113 | ffn_dropout_rate: float = 0.0, 114 | drop_path: float = 0.0, 115 | layer_scale_type: Optional[str] = None, 116 | layer_scale_init_value: float = 1e-4, 117 | ): 118 | super().__init__() 119 | 120 | assert not isinstance( 121 | attn_target, nn.Module 122 | ), "attn_target should be a Callable. Otherwise attn_target is shared across blocks!" 123 | self.attn = attn_target() 124 | if drop_path > 0.0: 125 | self.drop_path = DropPath(drop_path) 126 | else: 127 | self.drop_path = nn.Identity() 128 | self.norm_1 = norm_layer(dim) 129 | mlp_hidden_dim = int(mlp_ratio * dim) 130 | self.mlp = Mlp( 131 | in_features=dim, 132 | hidden_features=mlp_hidden_dim, 133 | act_layer=act_layer, 134 | drop=ffn_dropout_rate, 135 | ) 136 | self.norm_2 = norm_layer(dim) 137 | self.layer_scale_type = layer_scale_type 138 | if self.layer_scale_type is not None: 139 | assert self.layer_scale_type in [ 140 | "per_channel", 141 | "scalar", 142 | ], f"Found Layer scale type {self.layer_scale_type}" 143 | if self.layer_scale_type == "per_channel": 144 | # one gamma value per channel 145 | gamma_shape = [1, 1, dim] 146 | elif self.layer_scale_type == "scalar": 147 | # single gamma value for all channels 148 | gamma_shape = [1, 1, 1] 149 | # two gammas: for each part of the fwd in the encoder 150 | self.layer_scale_gamma1 = nn.Parameter( 151 | torch.ones(size=gamma_shape) * layer_scale_init_value, 152 | requires_grad=True, 153 | ) 154 | self.layer_scale_gamma2 = nn.Parameter( 155 | torch.ones(size=gamma_shape) * layer_scale_init_value, 156 | requires_grad=True, 157 | ) 158 | 159 | def forward(self, x: torch.Tensor, attn_mask: torch.Tensor): 160 | if self.layer_scale_type is None: 161 | x = x + self.drop_path(self.attn(self.norm_1(x), attn_mask)) 162 | x = x + self.drop_path(self.mlp(self.norm_2(x))) 163 | else: 164 | x = ( 165 | x 166 | + self.drop_path(self.attn(self.norm_1(x), attn_mask)) 167 | * self.layer_scale_gamma1 168 | ) 169 | x = x + self.drop_path(self.mlp(self.norm_2(x))) * self.layer_scale_gamma2 170 | return x 171 | 172 | 173 | _LAYER_NORM = partial(nn.LayerNorm, eps=1e-6) 174 | 175 | 176 | class SimpleTransformer(nn.Module): 177 | def __init__( 178 | self, 179 | attn_target: Callable, 180 | embed_dim: int, 181 | num_blocks: int, 182 | block: Callable = BlockWithMasking, 183 | pre_transformer_layer: Optional[Callable] = None, 184 | post_transformer_layer: Optional[Callable] = None, 185 | drop_path_rate: float = 0.0, 186 | drop_path_type: str = "progressive", 187 | norm_layer: Callable = _LAYER_NORM, 188 | mlp_ratio: int = 4, 189 | ffn_dropout_rate: float = 0.0, 190 | layer_scale_type: Optional[str] = None, # from cait; possible values are None, "per_channel", "scalar" 191 | layer_scale_init_value: float = 1e-4, # from cait; float 192 | weight_init_style: str = "jax", # possible values jax or pytorch 193 | ): 194 | """ 195 | Simple Transformer with the following features 196 | 1. Supports masked attention 197 | 2. Supports DropPath 198 | 3. Supports LayerScale 199 | 4. Supports Dropout in Attention and FFN 200 | 5. Makes few assumptions about the input except that it is a Tensor 201 | """ 202 | super().__init__() 203 | self.pre_transformer_layer = pre_transformer_layer 204 | if drop_path_type == "progressive": 205 | dpr = [x.item() for x in torch.linspace(0, drop_path_rate, num_blocks)] 206 | elif drop_path_type == "uniform": 207 | dpr = [drop_path_rate for i in range(num_blocks)] 208 | else: 209 | raise ValueError(f"Unknown drop_path_type: {drop_path_type}") 210 | 211 | self.blocks = nn.Sequential( 212 | *[ 213 | block( 214 | dim=embed_dim, 215 | attn_target=attn_target, 216 | mlp_ratio=mlp_ratio, 217 | ffn_dropout_rate=ffn_dropout_rate, 218 | drop_path=dpr[i], 219 | norm_layer=norm_layer, 220 | layer_scale_type=layer_scale_type, 221 | layer_scale_init_value=layer_scale_init_value, 222 | ) 223 | for i in range(num_blocks) 224 | ] 225 | ) 226 | self.post_transformer_layer = post_transformer_layer 227 | self.weight_init_style = weight_init_style 228 | self.apply(self._init_weights) 229 | 230 | def _init_weights(self, m): 231 | if isinstance(m, nn.Linear): 232 | if self.weight_init_style == "jax": 233 | # Based on MAE and official Jax ViT implementation 234 | torch.nn.init.xavier_uniform_(m.weight) 235 | elif self.weight_init_style == "pytorch": 236 | # PyTorch ViT uses trunc_normal_ 237 | trunc_normal_(m.weight, std=0.02) 238 | 239 | if m.bias is not None: 240 | nn.init.constant_(m.bias, 0) 241 | elif isinstance(m, (nn.LayerNorm)): 242 | nn.init.constant_(m.bias, 0) 243 | nn.init.constant_(m.weight, 1.0) 244 | 245 | def forward( 246 | self, 247 | tokens: torch.Tensor, 248 | attn_mask: torch.Tensor = None, 249 | use_checkpoint: bool = False, 250 | checkpoint_every_n: int = 1, 251 | checkpoint_blk_ids: Optional[List[int]] = None, 252 | ): 253 | """ 254 | Inputs 255 | - tokens: data of shape N x L x D (or L x N x D depending on the attention implementation) 256 | - attn: mask of shape L x L 257 | 258 | Output 259 | - x: data of shape N x L x D (or L x N x D depending on the attention implementation) 260 | """ 261 | if self.pre_transformer_layer: 262 | tokens = self.pre_transformer_layer(tokens) 263 | if use_checkpoint and checkpoint_blk_ids is None: 264 | checkpoint_blk_ids = [ 265 | blk_id 266 | for blk_id in range(len(self.blocks)) 267 | if blk_id % checkpoint_every_n == 0 268 | ] 269 | if checkpoint_blk_ids: 270 | checkpoint_blk_ids = set(checkpoint_blk_ids) 271 | for blk_id, blk in enumerate(self.blocks): 272 | if use_checkpoint and blk_id in checkpoint_blk_ids: 273 | tokens = checkpoint.checkpoint( 274 | blk, tokens, attn_mask, use_reentrant=False 275 | ) 276 | else: 277 | tokens = blk(tokens, attn_mask=attn_mask) 278 | if self.post_transformer_layer: 279 | tokens = self.post_transformer_layer(tokens) 280 | return tokens 281 | -------------------------------------------------------------------------------- /demo.py: -------------------------------------------------------------------------------- 1 | import ImageBind.data as data 2 | import llama 3 | import json 4 | import torch 5 | import pandas as pd 6 | import cv2 7 | import fundus_prep as prep 8 | # import BERTSimilarity.BERTSimilarity as bertsimilarity 9 | import torchvision.transforms as transforms 10 | from PIL import Image 11 | from PIL import ImageEnhance 12 | from sklearn.metrics import roc_curve, auc 13 | import matplotlib.pyplot as plt 14 | import numpy as np 15 | from sklearn.metrics import mean_absolute_error, accuracy_score, confusion_matrix 16 | from sklearn.metrics import cohen_kappa_score, balanced_accuracy_score 17 | 18 | def capitalize_sentences(text): 19 | # if not text[0].isalpha(): 20 | # text = text[1:] 21 | sentences = text.split('. ') # Split the text into sentences 22 | 23 | capitalized_sentences = [] 24 | for sentence in sentences: 25 | capitalized_sentence = sentence.capitalize() # Capitalize the first letter 26 | capitalized_sentences.append(capitalized_sentence) 27 | 28 | capitalized_text = '. '.join(capitalized_sentences) # Join the sentences back into text 29 | return capitalized_text 30 | 31 | def metrics(preds, labels): 32 | t_list = [0.5] 33 | for t in t_list: 34 | predictions = preds.tolist() 35 | groundTruth = labels.tolist() 36 | confusion = confusion_matrix(groundTruth, predictions) 37 | TP = confusion[1, 1] 38 | TN = confusion[0, 0] 39 | FP = confusion[0, 1] 40 | FN = confusion[1, 0] 41 | acc = accuracy_score(groundTruth, predictions) 42 | kappa = cohen_kappa_score(groundTruth, predictions) 43 | 44 | from sklearn.metrics import roc_auc_score, precision_score, f1_score, recall_score 45 | precision = TP / float(TP+FP) 46 | sensitivity = TP / float(TP+FN) 47 | specificity = TN / float(TN+FP) 48 | F1 = f1_score(groundTruth, predictions) 49 | balanced_accuracy = balanced_accuracy_score(groundTruth, predictions) 50 | 51 | if np.array(groundTruth).max() > 1: 52 | auc = roc_auc_score(labels, preds, multi_class='ovr') 53 | else: 54 | auc = roc_auc_score(labels, preds) 55 | # print(list(groundTruth), list(predictions)) 56 | print('Threshold:%.4f\tAccuracy:%.4f\tBalanced_Accuracy:%.4f\tSensitivity:%.4f\tSpecificity:%.4f\tPrecision:%.4f\tF1:%.4f\tAUC: %.4f\tKappa score:%.4f' % ( 57 | t, acc, balanced_accuracy, sensitivity, specificity, precision, F1, auc, kappa)) 58 | print('TN: %d\t FN:%d\t TP: %d\t FP: %d\n' % (TN, FN, TP, FP)) 59 | return acc, sensitivity, specificity, precision, F1, auc, kappa 60 | 61 | ## CUDA_VISIBLE_DEVICES=0,1 62 | def load_and_transform_vision_data(image_paths, device): 63 | if image_paths is None: 64 | return None 65 | 66 | image_ouputs = [] 67 | for image_path in image_paths: 68 | data_transform = transforms.Compose( 69 | [ 70 | transforms.Resize( 71 | 448, interpolation=transforms.InterpolationMode.BICUBIC 72 | ), 73 | transforms.CenterCrop(448), 74 | transforms.ToTensor(), 75 | transforms.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5]), 76 | ] 77 | ) 78 | with open(image_path, "rb") as fopen: 79 | image = Image.open(fopen).convert("RGB") 80 | # try: 81 | # img = prep.imread(fopen) 82 | # r_img, borders, mask, r_img = prep.process_without_gb(img,img) 83 | # image = Image.fromarray(cv2.cvtColor(r_img,cv2.COLOR_BGR2RGB)) 84 | # except: 85 | # image = Image.open(fopen).convert('RGB') 86 | 87 | # try: 88 | # bbox = image.getbbox() 89 | # image = image.crop(bbox) 90 | # except: 91 | # pass 92 | # image = Image.open(filename).convert('HSV') 93 | image = ImageEnhance.Contrast(image) 94 | image = image.enhance(1.3) 95 | image = np.array(image) 96 | min_R = np.min(image[:,:,0]) 97 | min_G = np.min(image[:,:,1]) 98 | min_B = np.min(image[:,:,2]) 99 | image[:,:,0] = image[:,:,0] - min_R +1 100 | image[:,:,1] = image[:,:,1] - min_G +1 101 | image[:,:,2] = image[:,:,2] - min_B +1 102 | image = Image.fromarray(image.astype('uint8')).convert('HSV') 103 | 104 | image = data_transform(image).to(device) 105 | image_ouputs.append(image) 106 | return torch.stack(image_ouputs, dim=0) 107 | 108 | llama_dir = "/llama-adapter/llama_model_weights" # /path/to/LLaMA/ 109 | 110 | device = "cuda" if torch.cuda.is_available() else "cpu" 111 | model = llama.load("/output_dir/checkpoint-12_30-20.pth", llama_dir).to(device) 112 | model.eval() 113 | 114 | model.to(device) 115 | 116 | ann = json.load(open('/Dataset/-MLLM-Fundus/All_json/RITE40_Test20.json')) 117 | fileHandler = open("/Valset_list_updated.txt", "r") 118 | listOfLines = fileHandler.readlines() 119 | for line in listOfLines: 120 | ann += json.load(open(line.strip())) 121 | 122 | Batchsize= 8 123 | predict = [] 124 | GroundTruth = [] 125 | image = [] 126 | similarity = [] 127 | cls_labels = [] 128 | cls_preds = [] 129 | instruction_gt = [] 130 | Keyword_list = [] 131 | data_dict = {} 132 | 133 | # bertsimilarity=bertsimilarity.BERTSimilarity() 134 | for index in range(0, len(ann), Batchsize): 135 | sample = [] 136 | prompt = [] 137 | prompt_gt = [] 138 | label = [] 139 | for i in range(Batchsize): 140 | try: 141 | url = ann[index+i]['ImageID'] 142 | # data_dict[url] = data_dict.get(url, 0) + 1 143 | sample.append(ann[index+i]['ImageID']) 144 | prompt_gt.append(ann[index+i]['Instruction']) 145 | prompt.append(llama.format_prompt(ann[index+i]['Instruction'])) 146 | label.append(ann[index+i]['Answer']) 147 | 148 | sample.append(ann[index+i]['ImageID']) 149 | prompt_gt.append(ann[index+i]['Instruction0']) 150 | prompt.append(llama.format_prompt(ann[index+i]['Instruction0'])) 151 | label.append(ann[index+i]['Answer0']) 152 | 153 | sample.append(ann[index+i]['ImageID']) 154 | prompt_gt.append(ann[index+i]['Instruction1']) 155 | prompt.append(llama.format_prompt(ann[index+i]['Instruction1'])) 156 | label.append(ann[index+i]['Answer1']) 157 | 158 | if ann[index+i]['Keyword'][0] == 'A': 159 | cls_labels.append([1.0, 0.0, 0.0, 0.0, 0.0, 0.0]) 160 | if 'FHE_label' in ann[index+i].keys(): 161 | if float(ann[index+i]['FHE_label']) > 0: 162 | cls_labels[len(cls_labels)-1][1] = 1.0 163 | cls_labels[len(cls_labels)-1][0] = 0.0 164 | if 'OCD_label' in ann[index+i].keys(): 165 | if float(ann[index+i]['OCD_label']) > 0: 166 | cls_labels[len(cls_labels)-1][2] = 1.0 167 | cls_labels[len(cls_labels)-1][0] = 0.0 168 | if 'FBC_label' in ann[index+i].keys(): 169 | if float(ann[index+i]['FBC_label']) > 0: 170 | cls_labels[len(cls_labels)-1][3] = 1.0 171 | cls_labels[len(cls_labels)-1][0] = 0.0 172 | if 'Macular_label' in ann[index+i].keys(): 173 | if float(ann[index+i]['Macular_label']) > 0: 174 | cls_labels[len(cls_labels)-1][4] = 1.0 175 | cls_labels[len(cls_labels)-1][0] = 0.0 176 | if 'AV_label' in ann[index+i].keys(): 177 | if float(ann[index+i]['AV_label']) > 0: 178 | cls_labels[len(cls_labels)-1][5] = 1.0 179 | cls_labels[len(cls_labels)-1][0] = 0.0 180 | cls_labels.append(cls_labels[len(cls_labels)-1]) 181 | cls_labels.append(cls_labels[len(cls_labels)-1]) 182 | Keyword_list.append(ann[index+i]['Keyword']) 183 | Keyword_list.append(ann[index+i]['Keyword']) 184 | Keyword_list.append(ann[index+i]['Keyword']) 185 | else: 186 | cls_labels.append([0.0, 0.0, 0.0, 0.0, 0.0, 0.0]) 187 | cls_labels.append([0.0, 0.0, 0.0, 0.0, 0.0, 0.0]) 188 | cls_labels.append([0.0, 0.0, 0.0, 0.0, 0.0, 0.0]) 189 | Keyword_list.append(ann[index+i]['Keyword']) 190 | Keyword_list.append(ann[index+i]['Keyword']) 191 | Keyword_list.append(ann[index+i]['Keyword']) 192 | # if ann[index+i]['Keyword'][0] == 'A': 193 | # cls_labels.append(1.0) 194 | # if 'AVR_label' in ann[index+i].keys(): 195 | # if float(ann[index+i]['AVR_label']) > 0: 196 | # cls_labels[index+i] = 2.0 197 | # if 'CDR_label' in ann[index+i].keys(): 198 | # if float(ann[index+i]['CDR_label']) > 0: 199 | # cls_labels[index+i] = 3.0 200 | # if 'Glaucoma_label' in ann[index+i].keys(): 201 | # if float(ann[index+i]['Glaucoma_label']) > 0: 202 | # cls_labels[index+i] = 4.0 203 | # if 'Myopia_label' in ann[index+i].keys(): 204 | # if float(ann[index+i]['Myopia_label']) > 0: 205 | # cls_labels[index+i] = 5.0 206 | # if 'DR_label' in ann[index+i].keys(): 207 | # if float(ann[index+i]['DR_label']) > 0: 208 | # cls_labels[index+i] = 6.0 209 | # if 'Macular_label' in ann[index+i].keys(): 210 | # if float(ann[index+i]['Macular_label']) > 0: 211 | # cls_labels[index+i] = 7.0 212 | # else: 213 | # cls_labels.append(0.0) 214 | except: 215 | continue 216 | # print(sample) 217 | input = load_and_transform_vision_data(sample, device) 218 | # prompt = prompt.to(device) 219 | results, cls_pred = model.generate(input, prompt, input_type="vision") 220 | for i in range(len(results)): 221 | # print(results[i]) 222 | # print(len(label[i])) 223 | # print(len(results[i])) 224 | # similarity.append(bertsimilarity.calculate_distance(label[i],results[i])) 225 | # similarity.append(0) 226 | image.append(sample[i]) 227 | instruction_gt.append(prompt_gt[i]) 228 | GroundTruth.append(label[i]) 229 | index = results[i].rfind('.') 230 | if (index+1)!=len(results[i]): 231 | results[i] = results[i][:index+1] 232 | predict.append(capitalize_sentences(results[i]).replace(' i ', ' I ').replace(' i\'', ' I\'')) 233 | # cls_labels.append(cls_labels[i]) 234 | # cls_preds.append([cls_pred[i][0].cpu().numpy(),cls_pred[i][1].cpu().numpy(),cls_pred[i][2].cpu().numpy(),cls_pred[i][3].cpu().numpy(),cls_pred[i][4].cpu().numpy(),cls_pred[i][5].cpu().numpy()]) 235 | cls_preds.append(cls_pred[i]) 236 | 237 | dict = {'ImageID': image, 'instruction_gt': instruction_gt, 'GT': GroundTruth , 'Predict': predict, 'Keyword': Keyword_list, 'cls_labels': cls_labels,'cls_preds': cls_preds} 238 | df = pd.DataFrame(dict) 239 | df.to_csv('./results/Test_result_12_30-20.csv',index=False) 240 | 241 | assert len(cls_labels) == len(cls_preds) 242 | 243 | cls_labels = np.array(cls_labels) 244 | cls_preds = np.array(cls_preds) 245 | 246 | class_1 = cls_labels[:,0] 247 | class_2 = cls_labels[:,1] 248 | class_3 = cls_labels[:,2] 249 | class_4 = cls_labels[:,3] 250 | class_5 = cls_labels[:,4] 251 | class_6 = cls_labels[:,5] 252 | class_1_pred = cls_preds[:,0] 253 | class_2_pred = cls_preds[:,1] 254 | class_3_pred = cls_preds[:,2] 255 | class_4_pred = cls_preds[:,3] 256 | class_5_pred = cls_preds[:,4] 257 | class_6_pred = cls_preds[:,5] 258 | 259 | metrics(class_1_pred, class_1) 260 | metrics(class_2_pred, class_2) 261 | metrics(class_3_pred, class_3) 262 | metrics(class_4_pred, class_4) 263 | metrics(class_5_pred, class_5) 264 | metrics(class_6_pred, class_6) 265 | -------------------------------------------------------------------------------- /llama/llama.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Meta Platforms, Inc. and affiliates. 2 | # This software may be used and distributed according to the terms of the GNU General Public License version 3. 3 | 4 | from typing import Optional, Tuple 5 | from dataclasses import dataclass 6 | import math 7 | 8 | import torch 9 | from torch import nn 10 | from torch.nn import Embedding, Linear 11 | import torch.nn.functional as F 12 | 13 | 14 | @dataclass 15 | class ModelArgs: 16 | dim: int = 512 17 | n_layers: int = 8 18 | n_heads: int = 8 19 | vocab_size: int = -1 # defined later by tokenizer 20 | multiple_of: int = 256 # make SwiGLU hidden layer size multiple of large power of 2 21 | norm_eps: float = 1e-5 22 | 23 | max_batch_size: int = 32 24 | max_seq_len: int = 2048 25 | 26 | w_bias: bool = True # use bias tuning 27 | w_lora: bool = True # use lora tuning 28 | lora_rank: int = 16 # lora rank 29 | 30 | 31 | class RMSNorm(torch.nn.Module): 32 | def __init__(self, dim: int, eps: float = 1e-6): 33 | super().__init__() 34 | self.eps = eps 35 | self.weight = nn.Parameter(torch.ones(dim)) 36 | 37 | def _norm(self, x): 38 | return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps) 39 | 40 | def forward(self, x): 41 | output = self._norm(x.float()).type_as(x) 42 | return output * self.weight 43 | 44 | 45 | def precompute_freqs_cis(dim: int, end: int, theta: float = 10000.0): 46 | freqs = 1.0 / (theta ** (torch.arange(0, dim, 2)[: (dim // 2)].float() / dim)) 47 | t = torch.arange(end, device=freqs.device) # type: ignore 48 | freqs = torch.outer(t, freqs).float() # type: ignore 49 | freqs_cis = torch.polar(torch.ones_like(freqs), freqs) # complex64 50 | return freqs_cis 51 | 52 | 53 | def reshape_for_broadcast(freqs_cis: torch.Tensor, x: torch.Tensor): 54 | ndim = x.ndim 55 | assert 0 <= 1 < ndim 56 | # print(x.shape, freqs_cis.shape) 57 | assert freqs_cis.shape == (x.shape[1], x.shape[-1]) 58 | shape = [d if i == 1 or i == ndim - 1 else 1 for i, d in enumerate(x.shape)] 59 | return freqs_cis.view(*shape) 60 | 61 | 62 | def apply_rotary_emb( 63 | xq: torch.Tensor, 64 | xk: torch.Tensor, 65 | freqs_cis: torch.Tensor, 66 | ) -> Tuple[torch.Tensor, torch.Tensor]: 67 | xq_ = torch.view_as_complex(xq.float().reshape(*xq.shape[:-1], -1, 2)) 68 | xk_ = torch.view_as_complex(xk.float().reshape(*xk.shape[:-1], -1, 2)) 69 | freqs_cis = reshape_for_broadcast(freqs_cis, xq_) 70 | xq_out = torch.view_as_real(xq_ * freqs_cis).flatten(3) 71 | xk_out = torch.view_as_real(xk_ * freqs_cis).flatten(3) 72 | return xq_out.type_as(xq), xk_out.type_as(xk) 73 | 74 | 75 | class Attention(nn.Module): 76 | def __init__(self, args: ModelArgs): 77 | super().__init__() 78 | 79 | self.n_local_heads = args.n_heads 80 | self.head_dim = args.dim // args.n_heads 81 | 82 | self.wq = Linear( 83 | args.dim, 84 | args.n_heads * self.head_dim, 85 | bias=args.w_bias 86 | ) 87 | self.wk = Linear( 88 | args.dim, 89 | args.n_heads * self.head_dim, 90 | bias=False 91 | ) 92 | self.wv = Linear( 93 | args.dim, 94 | args.n_heads * self.head_dim, 95 | bias=False 96 | ) 97 | self.wo = Linear( 98 | args.n_heads * self.head_dim, 99 | args.dim, 100 | bias=args.w_bias 101 | ) 102 | if args.w_bias: 103 | nn.init.constant_(self.wq.bias.data, 0) 104 | nn.init.constant_(self.wo.bias.data, 0) 105 | 106 | self.w_lora = args.w_lora 107 | if args.w_lora: 108 | self.lora_wq_l1 = Linear(args.dim, args.lora_rank, bias=False) 109 | self.lora_wq_l2 = Linear(args.lora_rank, args.dim, bias=False) 110 | 111 | self.lora_wk_l1 = Linear(args.dim, args.lora_rank, bias=False) 112 | self.lora_wk_l2 = Linear(args.lora_rank, args.dim, bias=False) 113 | 114 | self.lora_wv_l1 = Linear(args.dim, args.lora_rank, bias=False) 115 | self.lora_wv_l2 = Linear(args.lora_rank, args.dim, bias=False) 116 | 117 | self.lora_wo_l1 = Linear(args.dim, args.lora_rank, bias=False) 118 | self.lora_wo_l2 = Linear(args.lora_rank, args.dim, bias=False) 119 | nn.init.constant_(self.lora_wq_l2.weight.data, 0) 120 | nn.init.constant_(self.lora_wk_l2.weight.data, 0) 121 | nn.init.constant_(self.lora_wv_l2.weight.data, 0) 122 | nn.init.constant_(self.lora_wo_l2.weight.data, 0) 123 | 124 | self.cache_k = torch.zeros( 125 | (args.max_batch_size, args.max_seq_len, self.n_local_heads, self.head_dim) 126 | ).cuda() 127 | self.cache_v = torch.zeros( 128 | (args.max_batch_size, args.max_seq_len, self.n_local_heads, self.head_dim) 129 | ).cuda() 130 | 131 | self.gate = torch.nn.Parameter(torch.zeros(1, self.n_local_heads, 1, 1)) 132 | 133 | def forward(self, x: torch.Tensor, start_pos: int, freqs_cis: torch.Tensor, mask: Optional[torch.Tensor], adapter=None): 134 | bsz, seqlen, _ = x.shape 135 | xq, xk, xv = self.wq(x), self.wk(x), self.wv(x) 136 | if self.w_lora: 137 | xq = xq + self.lora_wq_l2(self.lora_wq_l1(x)) 138 | xk = xk + self.lora_wk_l2(self.lora_wk_l1(x)) 139 | xv = xv + self.lora_wv_l2(self.lora_wv_l1(x)) 140 | 141 | xq = xq.view(bsz, seqlen, self.n_local_heads, self.head_dim) 142 | xk = xk.view(bsz, seqlen, self.n_local_heads, self.head_dim) 143 | xv = xv.view(bsz, seqlen, self.n_local_heads, self.head_dim) 144 | 145 | xq, xk = apply_rotary_emb(xq, xk, freqs_cis=freqs_cis) 146 | 147 | if not self.training: 148 | self.cache_k = self.cache_k.to(xq) 149 | self.cache_v = self.cache_v.to(xq) 150 | 151 | self.cache_k[:bsz, start_pos : start_pos + seqlen] = xk 152 | self.cache_v[:bsz, start_pos : start_pos + seqlen] = xv 153 | 154 | keys = self.cache_k[:bsz, : start_pos + seqlen] 155 | values = self.cache_v[:bsz, : start_pos + seqlen] 156 | else: 157 | assert start_pos==0 158 | keys = xk 159 | values = xv 160 | 161 | if adapter is not None: 162 | adapter_len = adapter.shape[1] 163 | adapter_v = self.wv(adapter).view(bsz, adapter_len, self.n_local_heads, self.head_dim) 164 | adapter_v = adapter_v.transpose(1, 2) 165 | 166 | if adapter_len > 1: 167 | adapter_k = self.wk(adapter).view(bsz, adapter_len, self.n_local_heads, self.head_dim) 168 | adapter_k = adapter_k.transpose(1, 2) 169 | 170 | 171 | xq = xq.transpose(1, 2) 172 | keys = keys.transpose(1, 2) 173 | values = values.transpose(1, 2) 174 | scores = torch.matmul(xq, keys.transpose(2, 3)) / math.sqrt(self.head_dim) 175 | 176 | if mask is not None: 177 | scores = scores + mask # (bs, n_local_heads, slen, cache_len + slen) 178 | 179 | scores = F.softmax(scores.float(), dim=-1).type_as(xq) 180 | output = torch.matmul(scores, values) # (bs, n_local_heads, slen, head_dim) 181 | 182 | if adapter is not None: 183 | if adapter_len > 1: 184 | adapter_scores = torch.matmul(xq, adapter_k.transpose(2, 3)) / math.sqrt(self.head_dim) 185 | adapter_scores = self.gate.tanh() * F.softmax(adapter_scores.float(), dim=-1).type_as(xq) 186 | output = output + torch.matmul(adapter_scores, adapter_v) 187 | else: 188 | output = output + self.gate.tanh() * adapter_v 189 | 190 | output = output.transpose( 191 | 1, 2 192 | ).contiguous().view(bsz, seqlen, -1) 193 | 194 | if self.w_lora: 195 | return self.wo(output) + self.lora_wo_l2(self.lora_wo_l1(output)) 196 | else: 197 | return self.wo(output) 198 | 199 | 200 | class FeedForward(nn.Module): 201 | def __init__( 202 | self, 203 | dim: int, 204 | hidden_dim: int, 205 | multiple_of: int, 206 | args: ModelArgs 207 | ): 208 | super().__init__() 209 | hidden_dim = int(2 * hidden_dim / 3) 210 | hidden_dim = multiple_of * ((hidden_dim + multiple_of - 1) // multiple_of) 211 | 212 | self.w1 = Linear( 213 | dim, hidden_dim, bias=args.w_bias 214 | ) 215 | self.w2 = Linear( 216 | hidden_dim, dim, bias=args.w_bias 217 | ) 218 | self.w3 = Linear( 219 | dim, hidden_dim, bias=args.w_bias 220 | ) 221 | if args.w_bias: 222 | nn.init.constant_(self.w1.bias.data, 0) 223 | nn.init.constant_(self.w2.bias.data, 0) 224 | nn.init.constant_(self.w3.bias.data, 0) 225 | 226 | self.w_lora = args.w_lora 227 | if args.w_lora: 228 | self.lora_w1_l1 = Linear(dim, args.lora_rank, bias=False) 229 | self.lora_w1_l2 = Linear(args.lora_rank, hidden_dim, bias=False) 230 | self.lora_w2_l1 = Linear(hidden_dim, args.lora_rank, bias=False) 231 | self.lora_w2_l2 = Linear(args.lora_rank, dim, bias=False) 232 | self.lora_w3_l1 = Linear(dim, args.lora_rank, bias=False) 233 | self.lora_w3_l2 = Linear(args.lora_rank, hidden_dim, bias=False) 234 | nn.init.constant_(self.lora_w1_l2.weight.data, 0) 235 | nn.init.constant_(self.lora_w2_l2.weight.data, 0) 236 | nn.init.constant_(self.lora_w3_l2.weight.data, 0) 237 | 238 | def forward(self, x): 239 | if self.w_lora: 240 | out = F.silu(self.w1(x) + self.lora_w1_l2(self.lora_w1_l1(x))) * (self.w3(x) + self.lora_w3_l2(self.lora_w3_l1(x))) 241 | return self.w2(out) + self.lora_w2_l2(self.lora_w2_l1(out)) 242 | else: 243 | return self.w2(F.silu(self.w1(x)) * self.w3(x)) 244 | 245 | 246 | class TransformerBlock(nn.Module): 247 | def __init__(self, layer_id: int, args: ModelArgs): 248 | super().__init__() 249 | self.n_heads = args.n_heads 250 | self.dim = args.dim 251 | self.head_dim = args.dim // args.n_heads 252 | self.attention = Attention(args) 253 | self.feed_forward = FeedForward( 254 | dim=args.dim, hidden_dim=4 * args.dim, multiple_of=args.multiple_of, args=args 255 | ) 256 | self.layer_id = layer_id 257 | self.attention_norm = RMSNorm(args.dim, eps=args.norm_eps) 258 | self.ffn_norm = RMSNorm(args.dim, eps=args.norm_eps) 259 | 260 | def forward(self, x: torch.Tensor, start_pos: int, freqs_cis: torch.Tensor, mask: Optional[torch.Tensor], prompt=None): 261 | 262 | h = x + self.attention.forward(self.attention_norm(x), start_pos, freqs_cis, mask, prompt) 263 | out = h + self.feed_forward.forward(self.ffn_norm(h)) 264 | return out 265 | 266 | 267 | class Transformer(nn.Module): 268 | def __init__(self, params: ModelArgs): 269 | super().__init__() 270 | self.params = params 271 | self.vocab_size = params.vocab_size 272 | self.n_layers = params.n_layers 273 | self.tok_embeddings = Embedding( 274 | params.vocab_size, params.dim 275 | ) 276 | 277 | self.layers = torch.nn.ModuleList() 278 | for layer_id in range(params.n_layers): 279 | self.layers.append(TransformerBlock(layer_id, params)) 280 | 281 | self.norm = RMSNorm(params.dim, eps=params.norm_eps) 282 | self.output = Linear( 283 | params.dim, params.vocab_size, bias=False 284 | ) 285 | 286 | self.freqs_cis = precompute_freqs_cis( 287 | self.params.dim // self.params.n_heads, self.params.max_seq_len * 2 288 | ) 289 | 290 | @torch.inference_mode() 291 | def forward(self, tokens: torch.Tensor, start_pos: int): 292 | _bsz, seqlen = tokens.shape 293 | h = self.tok_embeddings(tokens) 294 | self.freqs_cis = self.freqs_cis.to(h.device) 295 | freqs_cis = self.freqs_cis[start_pos : start_pos + seqlen] 296 | 297 | mask = None 298 | if seqlen > 1: 299 | mask = torch.full((1, 1, seqlen, seqlen), float("-inf"), device=tokens.device) 300 | mask = torch.triu(mask, diagonal=start_pos + 1).type_as(h) 301 | 302 | for layer in self.layers: 303 | h = layer(h, start_pos, freqs_cis, mask) 304 | h = self.norm(h) 305 | output = self.output(h[:, -1, :]) # only compute last logits 306 | return output.float() 307 | -------------------------------------------------------------------------------- /ImageBind/data.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # Portions Copyright (c) Meta Platforms, Inc. and affiliates. 3 | # All rights reserved. 4 | 5 | # This source code is licensed under the license found in the 6 | # LICENSE file in the root directory of this source tree. 7 | 8 | import logging 9 | import math 10 | 11 | import torch 12 | import torch.nn as nn 13 | import torchaudio 14 | from PIL import Image 15 | from pytorchvideo import transforms as pv_transforms 16 | from pytorchvideo.data.clip_sampling import ConstantClipsPerVideoSampler 17 | from pytorchvideo.data.encoded_video import EncodedVideo 18 | from torchvision import transforms 19 | from torchvision.transforms._transforms_video import NormalizeVideo 20 | 21 | from .models.multimodal_preprocessors import SimpleTokenizer 22 | 23 | DEFAULT_AUDIO_FRAME_SHIFT_MS = 10 # in milliseconds 24 | 25 | BPE_PATH = "bpe/bpe_simple_vocab_16e6.txt.gz" 26 | 27 | 28 | def waveform2melspec(waveform, sample_rate, num_mel_bins, target_length): 29 | # Based on https://github.com/YuanGongND/ast/blob/d7d8b4b8e06cdaeb6c843cdb38794c1c7692234c/src/dataloader.py#L102 30 | waveform -= waveform.mean() 31 | fbank = torchaudio.compliance.kaldi.fbank( 32 | waveform, 33 | htk_compat=True, 34 | sample_frequency=sample_rate, 35 | use_energy=False, 36 | window_type="hanning", 37 | num_mel_bins=num_mel_bins, 38 | dither=0.0, 39 | frame_length=25, 40 | frame_shift=DEFAULT_AUDIO_FRAME_SHIFT_MS, 41 | ) 42 | # Convert to [mel_bins, num_frames] shape 43 | fbank = fbank.transpose(0, 1) 44 | # Pad to target_length 45 | n_frames = fbank.size(1) 46 | p = target_length - n_frames 47 | # if p is too large (say >20%), flash a warning 48 | if abs(p) / n_frames > 0.2: 49 | logging.warning( 50 | "Large gap between audio n_frames(%d) and " 51 | "target_length (%d). Is the audio_target_length " 52 | "setting correct?", 53 | n_frames, 54 | target_length, 55 | ) 56 | # cut and pad 57 | if p > 0: 58 | fbank = torch.nn.functional.pad(fbank, (0, p), mode="constant", value=0) 59 | elif p < 0: 60 | fbank = fbank[:, 0:target_length] 61 | # Convert to [1, mel_bins, num_frames] shape, essentially like a 1 62 | # channel image 63 | fbank = fbank.unsqueeze(0) 64 | return fbank 65 | 66 | 67 | def get_clip_timepoints(clip_sampler, duration): 68 | # Read out all clips in this video 69 | all_clips_timepoints = [] 70 | is_last_clip = False 71 | end = 0.0 72 | while not is_last_clip: 73 | start, end, _, _, is_last_clip = clip_sampler(end, duration, annotation=None) 74 | all_clips_timepoints.append((start, end)) 75 | return all_clips_timepoints 76 | 77 | 78 | def load_and_transform_vision_data(image_paths, device): 79 | if image_paths is None: 80 | return None 81 | 82 | image_ouputs = [] 83 | for image_path in image_paths: 84 | data_transform = transforms.Compose( 85 | [ 86 | transforms.Resize( 87 | 224, interpolation=transforms.InterpolationMode.BICUBIC 88 | ), 89 | transforms.CenterCrop(224), 90 | transforms.ToTensor(), 91 | transforms.Normalize( 92 | mean=(0.48145466, 0.4578275, 0.40821073), 93 | std=(0.26862954, 0.26130258, 0.27577711), 94 | ), 95 | ] 96 | ) 97 | with open(image_path, "rb") as fopen: 98 | image = Image.open(fopen).convert("RGB") 99 | 100 | image = data_transform(image).to(device) 101 | image_ouputs.append(image) 102 | return torch.stack(image_ouputs, dim=0) 103 | 104 | 105 | def load_and_transform_text(text, device): 106 | if text is None: 107 | return None 108 | tokenizer = SimpleTokenizer(bpe_path=BPE_PATH) 109 | tokens = [tokenizer(t).unsqueeze(0).to(device) for t in text] 110 | tokens = torch.cat(tokens, dim=0) 111 | return tokens 112 | 113 | 114 | def load_and_transform_audio_data( 115 | audio_paths, 116 | device, 117 | num_mel_bins=128, 118 | target_length=204, 119 | sample_rate=16000, 120 | clip_duration=2, 121 | clips_per_video=3, 122 | mean=-4.268, 123 | std=9.138, 124 | ): 125 | if audio_paths is None: 126 | return None 127 | 128 | audio_outputs = [] 129 | clip_sampler = ConstantClipsPerVideoSampler( 130 | clip_duration=clip_duration, clips_per_video=clips_per_video 131 | ) 132 | 133 | for audio_path in audio_paths: 134 | waveform, sr = torchaudio.load(audio_path) 135 | if sample_rate != sr: 136 | waveform = torchaudio.functional.resample( 137 | waveform, orig_freq=sr, new_freq=sample_rate 138 | ) 139 | all_clips_timepoints = get_clip_timepoints( 140 | clip_sampler, waveform.size(1) / sample_rate 141 | ) 142 | all_clips = [] 143 | for clip_timepoints in all_clips_timepoints: 144 | waveform_clip = waveform[ 145 | :, 146 | int(clip_timepoints[0] * sample_rate) : int( 147 | clip_timepoints[1] * sample_rate 148 | ), 149 | ] 150 | waveform_melspec = waveform2melspec( 151 | waveform_clip, sample_rate, num_mel_bins, target_length 152 | ) 153 | all_clips.append(waveform_melspec) 154 | 155 | normalize = transforms.Normalize(mean=mean, std=std) 156 | all_clips = [normalize(ac).to(device) for ac in all_clips] 157 | 158 | all_clips = torch.stack(all_clips, dim=0) 159 | audio_outputs.append(all_clips) 160 | 161 | return torch.stack(audio_outputs, dim=0) 162 | 163 | 164 | def crop_boxes(boxes, x_offset, y_offset): 165 | """ 166 | Perform crop on the bounding boxes given the offsets. 167 | Args: 168 | boxes (ndarray or None): bounding boxes to perform crop. The dimension 169 | is `num boxes` x 4. 170 | x_offset (int): cropping offset in the x axis. 171 | y_offset (int): cropping offset in the y axis. 172 | Returns: 173 | cropped_boxes (ndarray or None): the cropped boxes with dimension of 174 | `num boxes` x 4. 175 | """ 176 | cropped_boxes = boxes.copy() 177 | cropped_boxes[:, [0, 2]] = boxes[:, [0, 2]] - x_offset 178 | cropped_boxes[:, [1, 3]] = boxes[:, [1, 3]] - y_offset 179 | 180 | return cropped_boxes 181 | 182 | 183 | def uniform_crop(images, size, spatial_idx, boxes=None, scale_size=None): 184 | """ 185 | Perform uniform spatial sampling on the images and corresponding boxes. 186 | Args: 187 | images (tensor): images to perform uniform crop. The dimension is 188 | `num frames` x `channel` x `height` x `width`. 189 | size (int): size of height and weight to crop the images. 190 | spatial_idx (int): 0, 1, or 2 for left, center, and right crop if width 191 | is larger than height. Or 0, 1, or 2 for top, center, and bottom 192 | crop if height is larger than width. 193 | boxes (ndarray or None): optional. Corresponding boxes to images. 194 | Dimension is `num boxes` x 4. 195 | scale_size (int): optinal. If not None, resize the images to scale_size before 196 | performing any crop. 197 | Returns: 198 | cropped (tensor): images with dimension of 199 | `num frames` x `channel` x `size` x `size`. 200 | cropped_boxes (ndarray or None): the cropped boxes with dimension of 201 | `num boxes` x 4. 202 | """ 203 | assert spatial_idx in [0, 1, 2] 204 | ndim = len(images.shape) 205 | if ndim == 3: 206 | images = images.unsqueeze(0) 207 | height = images.shape[2] 208 | width = images.shape[3] 209 | 210 | if scale_size is not None: 211 | if width <= height: 212 | width, height = scale_size, int(height / width * scale_size) 213 | else: 214 | width, height = int(width / height * scale_size), scale_size 215 | images = torch.nn.functional.interpolate( 216 | images, 217 | size=(height, width), 218 | mode="bilinear", 219 | align_corners=False, 220 | ) 221 | 222 | y_offset = int(math.ceil((height - size) / 2)) 223 | x_offset = int(math.ceil((width - size) / 2)) 224 | 225 | if height > width: 226 | if spatial_idx == 0: 227 | y_offset = 0 228 | elif spatial_idx == 2: 229 | y_offset = height - size 230 | else: 231 | if spatial_idx == 0: 232 | x_offset = 0 233 | elif spatial_idx == 2: 234 | x_offset = width - size 235 | cropped = images[:, :, y_offset : y_offset + size, x_offset : x_offset + size] 236 | cropped_boxes = crop_boxes(boxes, x_offset, y_offset) if boxes is not None else None 237 | if ndim == 3: 238 | cropped = cropped.squeeze(0) 239 | return cropped, cropped_boxes 240 | 241 | 242 | class SpatialCrop(nn.Module): 243 | """ 244 | Convert the video into 3 smaller clips spatially. Must be used after the 245 | temporal crops to get spatial crops, and should be used with 246 | -2 in the spatial crop at the slowfast augmentation stage (so full 247 | frames are passed in here). Will return a larger list with the 248 | 3x spatial crops as well. 249 | """ 250 | 251 | def __init__(self, crop_size: int = 224, num_crops: int = 3): 252 | super().__init__() 253 | self.crop_size = crop_size 254 | if num_crops == 3: 255 | self.crops_to_ext = [0, 1, 2] 256 | self.flipped_crops_to_ext = [] 257 | elif num_crops == 1: 258 | self.crops_to_ext = [1] 259 | self.flipped_crops_to_ext = [] 260 | else: 261 | raise NotImplementedError("Nothing else supported yet") 262 | 263 | def forward(self, videos): 264 | """ 265 | Args: 266 | videos: A list of C, T, H, W videos. 267 | Returns: 268 | videos: A list with 3x the number of elements. Each video converted 269 | to C, T, H', W' by spatial cropping. 270 | """ 271 | assert isinstance(videos, list), "Must be a list of videos after temporal crops" 272 | assert all([video.ndim == 4 for video in videos]), "Must be (C,T,H,W)" 273 | res = [] 274 | for video in videos: 275 | for spatial_idx in self.crops_to_ext: 276 | res.append(uniform_crop(video, self.crop_size, spatial_idx)[0]) 277 | if not self.flipped_crops_to_ext: 278 | continue 279 | flipped_video = transforms.functional.hflip(video) 280 | for spatial_idx in self.flipped_crops_to_ext: 281 | res.append(uniform_crop(flipped_video, self.crop_size, spatial_idx)[0]) 282 | return res 283 | 284 | 285 | def load_and_transform_video_data( 286 | video_paths, 287 | device, 288 | clip_duration=2, 289 | clips_per_video=5, 290 | sample_rate=16000, 291 | ): 292 | if video_paths is None: 293 | return None 294 | 295 | video_outputs = [] 296 | video_transform = transforms.Compose( 297 | [ 298 | pv_transforms.ShortSideScale(224), 299 | NormalizeVideo( 300 | mean=(0.48145466, 0.4578275, 0.40821073), 301 | std=(0.26862954, 0.26130258, 0.27577711), 302 | ), 303 | ] 304 | ) 305 | 306 | clip_sampler = ConstantClipsPerVideoSampler( 307 | clip_duration=clip_duration, clips_per_video=clips_per_video 308 | ) 309 | frame_sampler = pv_transforms.UniformTemporalSubsample(num_samples=clip_duration) 310 | 311 | for video_path in video_paths: 312 | video = EncodedVideo.from_path( 313 | video_path, 314 | decoder="decord", 315 | decode_audio=False, 316 | **{"sample_rate": sample_rate}, 317 | ) 318 | 319 | all_clips_timepoints = get_clip_timepoints(clip_sampler, video.duration) 320 | 321 | all_video = [] 322 | for clip_timepoints in all_clips_timepoints: 323 | # Read the clip, get frames 324 | clip = video.get_clip(clip_timepoints[0], clip_timepoints[1]) 325 | if clip is None: 326 | raise ValueError("No clip found") 327 | video_clip = frame_sampler(clip["video"]) 328 | video_clip = video_clip / 255.0 # since this is float, need 0-1 329 | 330 | all_video.append(video_clip) 331 | 332 | all_video = [video_transform(clip) for clip in all_video] 333 | all_video = SpatialCrop(224, num_crops=3)(all_video) 334 | 335 | all_video = torch.stack(all_video, dim=0) 336 | video_outputs.append(all_video) 337 | 338 | return torch.stack(video_outputs, dim=0).to(device) 339 | -------------------------------------------------------------------------------- /util/misc.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Meta Platforms, Inc. and affiliates. 2 | # All rights reserved. 3 | 4 | # This source code is licensed under the license found in the 5 | # LICENSE file in the root directory of this source tree. 6 | # -------------------------------------------------------- 7 | # References: 8 | # DeiT: https://github.com/facebookresearch/deit 9 | # BEiT: https://github.com/microsoft/unilm/tree/master/beit 10 | # -------------------------------------------------------- 11 | 12 | import builtins 13 | import datetime 14 | import os 15 | import time 16 | from collections import defaultdict, deque 17 | from pathlib import Path 18 | 19 | import torch 20 | import torch.distributed as dist 21 | from torch._six import inf 22 | 23 | 24 | class SmoothedValue(object): 25 | """Track a series of values and provide access to smoothed values over a 26 | window or the global series average. 27 | """ 28 | 29 | def __init__(self, window_size=20, fmt=None): 30 | if fmt is None: 31 | fmt = "{median:.4f} ({global_avg:.4f})" 32 | self.deque = deque(maxlen=window_size) 33 | self.total = 0.0 34 | self.count = 0 35 | self.fmt = fmt 36 | 37 | def update(self, value, n=1): 38 | self.deque.append(value) 39 | self.count += n 40 | self.total += value * n 41 | 42 | def synchronize_between_processes(self): 43 | """ 44 | Warning: does not synchronize the deque! 45 | """ 46 | if not is_dist_avail_and_initialized(): 47 | return 48 | t = torch.tensor([self.count, self.total], dtype=torch.float64, device='cuda') 49 | dist.barrier() 50 | dist.all_reduce(t) 51 | t = t.tolist() 52 | self.count = int(t[0]) 53 | self.total = t[1] 54 | 55 | @property 56 | def median(self): 57 | d = torch.tensor(list(self.deque)) 58 | return d.median().item() 59 | 60 | @property 61 | def avg(self): 62 | d = torch.tensor(list(self.deque), dtype=torch.float32) 63 | return d.mean().item() 64 | 65 | @property 66 | def global_avg(self): 67 | return self.total / self.count 68 | 69 | @property 70 | def max(self): 71 | return max(self.deque) 72 | 73 | @property 74 | def value(self): 75 | return self.deque[-1] 76 | 77 | def __str__(self): 78 | return self.fmt.format( 79 | median=self.median, 80 | avg=self.avg, 81 | global_avg=self.global_avg, 82 | max=self.max, 83 | value=self.value) 84 | 85 | 86 | class MetricLogger(object): 87 | def __init__(self, delimiter="\t"): 88 | self.meters = defaultdict(SmoothedValue) 89 | self.delimiter = delimiter 90 | 91 | def update(self, **kwargs): 92 | for k, v in kwargs.items(): 93 | if v is None: 94 | continue 95 | if isinstance(v, torch.Tensor): 96 | v = v.item() 97 | assert isinstance(v, (float, int)) 98 | self.meters[k].update(v) 99 | 100 | def __getattr__(self, attr): 101 | if attr in self.meters: 102 | return self.meters[attr] 103 | if attr in self.__dict__: 104 | return self.__dict__[attr] 105 | raise AttributeError("'{}' object has no attribute '{}'".format( 106 | type(self).__name__, attr)) 107 | 108 | def __str__(self): 109 | loss_str = [] 110 | for name, meter in self.meters.items(): 111 | loss_str.append( 112 | "{}: {}".format(name, str(meter)) 113 | ) 114 | return self.delimiter.join(loss_str) 115 | 116 | def synchronize_between_processes(self): 117 | for meter in self.meters.values(): 118 | meter.synchronize_between_processes() 119 | 120 | def add_meter(self, name, meter): 121 | self.meters[name] = meter 122 | 123 | def log_every(self, iterable, print_freq, header=None): 124 | i = 0 125 | if not header: 126 | header = '' 127 | start_time = time.time() 128 | end = time.time() 129 | iter_time = SmoothedValue(fmt='{avg:.4f}') 130 | data_time = SmoothedValue(fmt='{avg:.4f}') 131 | space_fmt = ':' + str(len(str(len(iterable)))) + 'd' 132 | log_msg = [ 133 | header, 134 | '[{0' + space_fmt + '}/{1}]', 135 | 'eta: {eta}', 136 | '{meters}', 137 | 'time: {time}', 138 | 'data: {data}' 139 | ] 140 | if torch.cuda.is_available(): 141 | log_msg.append('max mem: {memory:.0f}') 142 | log_msg = self.delimiter.join(log_msg) 143 | MB = 1024.0 * 1024.0 144 | for obj in iterable: 145 | data_time.update(time.time() - end) 146 | yield obj 147 | iter_time.update(time.time() - end) 148 | if i % print_freq == 0 or i == len(iterable) - 1: 149 | eta_seconds = iter_time.global_avg * (len(iterable) - i) 150 | eta_string = str(datetime.timedelta(seconds=int(eta_seconds))) 151 | if torch.cuda.is_available(): 152 | print(log_msg.format( 153 | i, len(iterable), eta=eta_string, 154 | meters=str(self), 155 | time=str(iter_time), data=str(data_time), 156 | memory=torch.cuda.max_memory_allocated() / MB)) 157 | else: 158 | print(log_msg.format( 159 | i, len(iterable), eta=eta_string, 160 | meters=str(self), 161 | time=str(iter_time), data=str(data_time))) 162 | i += 1 163 | end = time.time() 164 | total_time = time.time() - start_time 165 | total_time_str = str(datetime.timedelta(seconds=int(total_time))) 166 | print('{} Total time: {} ({:.4f} s / it)'.format( 167 | header, total_time_str, total_time / len(iterable))) 168 | 169 | 170 | def setup_for_distributed(is_master): 171 | """ 172 | This function disables printing when not in master process 173 | """ 174 | builtin_print = builtins.print 175 | 176 | def print(*args, **kwargs): 177 | force = kwargs.pop('force', False) 178 | force = force or (get_world_size() > 8) 179 | if is_master or force: 180 | now = datetime.datetime.now().time() 181 | builtin_print('[{}] '.format(now), end='') # print with time stamp 182 | builtin_print(*args, **kwargs) 183 | 184 | builtins.print = print 185 | 186 | 187 | def is_dist_avail_and_initialized(): 188 | if not dist.is_available(): 189 | return False 190 | if not dist.is_initialized(): 191 | return False 192 | return True 193 | 194 | 195 | def get_world_size(): 196 | if not is_dist_avail_and_initialized(): 197 | return 1 198 | return dist.get_world_size() 199 | 200 | 201 | def get_rank(): 202 | if not is_dist_avail_and_initialized(): 203 | return 0 204 | return dist.get_rank() 205 | 206 | 207 | def is_main_process(): 208 | return get_rank() == 0 209 | 210 | 211 | def save_on_master(*args, **kwargs): 212 | if is_main_process(): 213 | torch.save(*args, **kwargs) 214 | 215 | 216 | def init_distributed_mode(args): 217 | if args.dist_on_itp: 218 | args.rank = int(os.environ['OMPI_COMM_WORLD_RANK']) 219 | args.world_size = int(os.environ['OMPI_COMM_WORLD_SIZE']) 220 | args.gpu = int(os.environ['OMPI_COMM_WORLD_LOCAL_RANK']) 221 | args.dist_url = "tcp://%s:%s" % (os.environ['MASTER_ADDR'], os.environ['MASTER_PORT']) 222 | os.environ['LOCAL_RANK'] = str(args.gpu) 223 | os.environ['RANK'] = str(args.rank) 224 | os.environ['WORLD_SIZE'] = str(args.world_size) 225 | # ["RANK", "WORLD_SIZE", "MASTER_ADDR", "MASTER_PORT", "LOCAL_RANK"] 226 | elif 'RANK' in os.environ and 'WORLD_SIZE' in os.environ: 227 | args.rank = int(os.environ["RANK"]) 228 | args.world_size = int(os.environ['WORLD_SIZE']) 229 | args.gpu = int(os.environ['LOCAL_RANK']) 230 | elif 'SLURM_PROCID' in os.environ: 231 | args.rank = int(os.environ['SLURM_PROCID']) 232 | args.gpu = args.rank % torch.cuda.device_count() 233 | else: 234 | print('Not using distributed mode') 235 | setup_for_distributed(is_master=True) # hack 236 | args.distributed = False 237 | return 238 | 239 | args.distributed = True 240 | 241 | print("GPU::", args.gpu) 242 | torch.cuda.set_device(args.gpu) 243 | args.dist_backend = 'nccl' 244 | print('| distributed init (rank {}): {}, gpu {}'.format( 245 | args.rank, args.dist_url, args.gpu), flush=True) 246 | torch.distributed.init_process_group(backend=args.dist_backend, init_method=args.dist_url, 247 | world_size=args.world_size, rank=args.rank) 248 | torch.distributed.barrier() 249 | setup_for_distributed(args.rank == 0) 250 | 251 | 252 | class NativeScalerWithGradNormCount: 253 | state_dict_key = "amp_scaler" 254 | 255 | def __init__(self): 256 | self._scaler = torch.cuda.amp.GradScaler() 257 | 258 | def __call__(self, loss, optimizer, clip_grad=None, parameters=None, create_graph=False, update_grad=True): 259 | self._scaler.scale(loss).backward(create_graph=create_graph) 260 | if update_grad: 261 | if clip_grad is not None: 262 | assert parameters is not None 263 | self._scaler.unscale_(optimizer) # unscale the gradients of optimizer's assigned params in-place 264 | norm = torch.nn.utils.clip_grad_norm_(parameters, clip_grad) 265 | else: 266 | self._scaler.unscale_(optimizer) 267 | norm = get_grad_norm_(parameters) 268 | self._scaler.step(optimizer) 269 | self._scaler.update() 270 | else: 271 | norm = None 272 | return norm 273 | 274 | def state_dict(self): 275 | return self._scaler.state_dict() 276 | 277 | def load_state_dict(self, state_dict): 278 | self._scaler.load_state_dict(state_dict) 279 | 280 | 281 | def get_grad_norm_(parameters, norm_type: float = 2.0) -> torch.Tensor: 282 | if isinstance(parameters, torch.Tensor): 283 | parameters = [parameters] 284 | parameters = [p for p in parameters if p.grad is not None] 285 | norm_type = float(norm_type) 286 | if len(parameters) == 0: 287 | return torch.tensor(0.) 288 | device = parameters[0].grad.device 289 | if norm_type == inf: 290 | total_norm = max(p.grad.detach().abs().max().to(device) for p in parameters) 291 | else: 292 | total_norm = torch.norm(torch.stack([torch.norm(p.grad.detach(), norm_type).to(device) for p in parameters]), norm_type) 293 | return total_norm 294 | 295 | 296 | def save_model(args, epoch, model, model_without_ddp, optimizer, loss_scaler): 297 | output_dir = Path(args.output_dir) 298 | epoch_name = str(epoch) 299 | if loss_scaler is not None: 300 | checkpoint_paths = [output_dir / ('checkpoint-%s.pth' % epoch_name)] 301 | for checkpoint_path in checkpoint_paths: 302 | to_save = { 303 | 'model': model_without_ddp.state_dict(), 304 | 'optimizer': optimizer.state_dict(), 305 | 'epoch': epoch, 306 | 'scaler': loss_scaler.state_dict(), 307 | 'args': args, 308 | } 309 | 310 | save_on_master(to_save, checkpoint_path) 311 | else: 312 | client_state = {'epoch': epoch} 313 | model.save_checkpoint(save_dir=args.output_dir, tag="checkpoint-%s" % epoch_name, client_state=client_state) 314 | 315 | 316 | def load_model(args, model_without_ddp, optimizer, loss_scaler): 317 | if args.resume: 318 | if args.resume.startswith('https'): 319 | checkpoint = torch.hub.load_state_dict_from_url( 320 | args.resume, map_location='cpu', check_hash=True) 321 | else: 322 | checkpoint = torch.load(args.resume, map_location='cpu') 323 | new_checkpoint = {} 324 | for key, value in checkpoint['model'].items(): 325 | key = key.replace("llma", "llama") 326 | new_checkpoint[key] = value 327 | print(model_without_ddp.load_state_dict(new_checkpoint, strict=False)) 328 | print("Resume checkpoint %s" % args.resume) 329 | 330 | 331 | def all_reduce_mean(x): 332 | world_size = get_world_size() 333 | if world_size > 1: 334 | x_reduce = torch.tensor(x).cuda() 335 | dist.all_reduce(x_reduce) 336 | x_reduce /= world_size 337 | return x_reduce.item() 338 | else: 339 | return x 340 | 341 | 342 | def add_weight_decay(model, weight_decay=1e-5, skip_list=()): 343 | decay = [] 344 | no_decay = [] 345 | for name, param in model.named_parameters(): 346 | if not param.requires_grad: 347 | continue # frozen weights 348 | if len(param.shape) == 1 or name.endswith(".bias") or name in skip_list: 349 | no_decay.append(param) 350 | else: 351 | decay.append(param) 352 | return [ 353 | {'params': no_decay, 'weight_decay': 0.}, 354 | {'params': decay, 'weight_decay': weight_decay}] -------------------------------------------------------------------------------- /ImageBind/models/imagebind_model.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # Portions Copyright (c) Meta Platforms, Inc. and affiliates. 3 | # All rights reserved. 4 | 5 | # This source code is licensed under the license found in the 6 | # LICENSE file in the root directory of this source tree. 7 | 8 | 9 | import os 10 | from functools import partial 11 | from types import SimpleNamespace 12 | 13 | import torch 14 | import torch.nn as nn 15 | 16 | from .helpers import (EinOpsRearrange, LearnableLogitScaling, Normalize, 17 | SelectElement, SelectEOSAndProject) 18 | from .multimodal_preprocessors import (AudioPreprocessor, 19 | IMUPreprocessor, PadIm2Video, 20 | PatchEmbedGeneric, 21 | RGBDTPreprocessor, 22 | SpatioTemporalPosEmbeddingHelper, 23 | TextPreprocessor, 24 | ThermalPreprocessor) 25 | from .transformer import MultiheadAttention, SimpleTransformer 26 | 27 | ModalityType = SimpleNamespace( 28 | VISION="vision", 29 | TEXT="text", 30 | AUDIO="audio", 31 | THERMAL="thermal", 32 | DEPTH="depth", 33 | IMU="imu", 34 | ) 35 | 36 | 37 | class ImageBindModel(nn.Module): 38 | def __init__( 39 | self, 40 | video_frames=2, 41 | kernel_size=(2, 14, 14), 42 | audio_kernel_size=16, 43 | audio_stride=10, 44 | out_embed_dim=768, 45 | vision_embed_dim=1024, 46 | vision_num_blocks=24, 47 | vision_num_heads=16, 48 | audio_embed_dim=768, 49 | audio_num_blocks=12, 50 | audio_num_heads=12, 51 | audio_num_mel_bins=128, 52 | audio_target_len=204, 53 | audio_drop_path=0.1, 54 | text_embed_dim=768, 55 | text_num_blocks=12, 56 | text_num_heads=12, 57 | depth_embed_dim=384, 58 | depth_kernel_size=16, 59 | depth_num_blocks=12, 60 | depth_num_heads=8, 61 | depth_drop_path=0.0, 62 | thermal_embed_dim=768, 63 | thermal_kernel_size=16, 64 | thermal_num_blocks=12, 65 | thermal_num_heads=12, 66 | thermal_drop_path=0.0, 67 | imu_embed_dim=512, 68 | imu_kernel_size=8, 69 | imu_num_blocks=6, 70 | imu_num_heads=8, 71 | imu_drop_path=0.7, 72 | ): 73 | super().__init__() 74 | 75 | self.modality_preprocessors = self._create_modality_preprocessors( 76 | video_frames, 77 | vision_embed_dim, 78 | kernel_size, 79 | text_embed_dim, 80 | audio_embed_dim, 81 | audio_kernel_size, 82 | audio_stride, 83 | audio_num_mel_bins, 84 | audio_target_len, 85 | depth_embed_dim, 86 | depth_kernel_size, 87 | thermal_embed_dim, 88 | thermal_kernel_size, 89 | imu_embed_dim, 90 | ) 91 | 92 | self.modality_trunks = self._create_modality_trunks( 93 | vision_embed_dim, 94 | vision_num_blocks, 95 | vision_num_heads, 96 | text_embed_dim, 97 | text_num_blocks, 98 | text_num_heads, 99 | audio_embed_dim, 100 | audio_num_blocks, 101 | audio_num_heads, 102 | audio_drop_path, 103 | depth_embed_dim, 104 | depth_num_blocks, 105 | depth_num_heads, 106 | depth_drop_path, 107 | thermal_embed_dim, 108 | thermal_num_blocks, 109 | thermal_num_heads, 110 | thermal_drop_path, 111 | imu_embed_dim, 112 | imu_num_blocks, 113 | imu_num_heads, 114 | imu_drop_path, 115 | ) 116 | 117 | self.modality_heads = self._create_modality_heads( 118 | out_embed_dim, 119 | vision_embed_dim, 120 | text_embed_dim, 121 | audio_embed_dim, 122 | depth_embed_dim, 123 | thermal_embed_dim, 124 | imu_embed_dim, 125 | ) 126 | 127 | self.modality_postprocessors = self._create_modality_postprocessors( 128 | out_embed_dim 129 | ) 130 | 131 | def _create_modality_preprocessors( 132 | self, 133 | video_frames=2, 134 | vision_embed_dim=1024, 135 | kernel_size=(2, 14, 14), 136 | text_embed_dim=768, 137 | audio_embed_dim=768, 138 | audio_kernel_size=16, 139 | audio_stride=10, 140 | audio_num_mel_bins=128, 141 | audio_target_len=204, 142 | depth_embed_dim=768, 143 | depth_kernel_size=16, 144 | thermal_embed_dim=768, 145 | thermal_kernel_size=16, 146 | imu_embed_dim=512, 147 | ): 148 | rgbt_stem = PatchEmbedGeneric( 149 | proj_stem=[ 150 | PadIm2Video(pad_type="repeat", ntimes=2), 151 | nn.Conv3d( 152 | in_channels=3, 153 | kernel_size=kernel_size, 154 | out_channels=vision_embed_dim, 155 | stride=kernel_size, 156 | bias=False, 157 | ), 158 | ] 159 | ) 160 | rgbt_preprocessor = RGBDTPreprocessor( 161 | img_size=[3, video_frames, 224, 224], 162 | num_cls_tokens=1, 163 | pos_embed_fn=partial(SpatioTemporalPosEmbeddingHelper, learnable=True), 164 | rgbt_stem=rgbt_stem, 165 | depth_stem=None, 166 | ) 167 | 168 | text_preprocessor = TextPreprocessor( 169 | context_length=77, 170 | vocab_size=49408, 171 | embed_dim=text_embed_dim, 172 | causal_masking=True, 173 | ) 174 | 175 | audio_stem = PatchEmbedGeneric( 176 | proj_stem=[ 177 | nn.Conv2d( 178 | in_channels=1, 179 | kernel_size=audio_kernel_size, 180 | stride=audio_stride, 181 | out_channels=audio_embed_dim, 182 | bias=False, 183 | ), 184 | ], 185 | norm_layer=nn.LayerNorm(normalized_shape=audio_embed_dim), 186 | ) 187 | audio_preprocessor = AudioPreprocessor( 188 | img_size=[1, audio_num_mel_bins, audio_target_len], 189 | num_cls_tokens=1, 190 | pos_embed_fn=partial(SpatioTemporalPosEmbeddingHelper, learnable=True), 191 | audio_stem=audio_stem, 192 | ) 193 | 194 | depth_stem = PatchEmbedGeneric( 195 | [ 196 | nn.Conv2d( 197 | kernel_size=depth_kernel_size, 198 | in_channels=1, 199 | out_channels=depth_embed_dim, 200 | stride=depth_kernel_size, 201 | bias=False, 202 | ), 203 | ], 204 | norm_layer=nn.LayerNorm(normalized_shape=depth_embed_dim), 205 | ) 206 | 207 | depth_preprocessor = RGBDTPreprocessor( 208 | img_size=[1, 224, 224], 209 | num_cls_tokens=1, 210 | pos_embed_fn=partial(SpatioTemporalPosEmbeddingHelper, learnable=True), 211 | rgbt_stem=None, 212 | depth_stem=depth_stem, 213 | ) 214 | 215 | thermal_stem = PatchEmbedGeneric( 216 | [ 217 | nn.Conv2d( 218 | kernel_size=thermal_kernel_size, 219 | in_channels=1, 220 | out_channels=thermal_embed_dim, 221 | stride=thermal_kernel_size, 222 | bias=False, 223 | ), 224 | ], 225 | norm_layer=nn.LayerNorm(normalized_shape=thermal_embed_dim), 226 | ) 227 | thermal_preprocessor = ThermalPreprocessor( 228 | img_size=[1, 224, 224], 229 | num_cls_tokens=1, 230 | pos_embed_fn=partial(SpatioTemporalPosEmbeddingHelper, learnable=True), 231 | thermal_stem=thermal_stem, 232 | ) 233 | 234 | imu_stem = PatchEmbedGeneric( 235 | [ 236 | nn.Linear( 237 | in_features=48, 238 | out_features=imu_embed_dim, 239 | bias=False, 240 | ), 241 | ], 242 | norm_layer=nn.LayerNorm(normalized_shape=imu_embed_dim), 243 | ) 244 | 245 | imu_preprocessor = IMUPreprocessor( 246 | img_size=[6, 2000], 247 | num_cls_tokens=1, 248 | kernel_size=8, 249 | embed_dim=imu_embed_dim, 250 | pos_embed_fn=partial(SpatioTemporalPosEmbeddingHelper, learnable=True), 251 | imu_stem=imu_stem, 252 | ) 253 | 254 | modality_preprocessors = { 255 | ModalityType.VISION: rgbt_preprocessor, 256 | ModalityType.TEXT: text_preprocessor, 257 | ModalityType.AUDIO: audio_preprocessor, 258 | ModalityType.DEPTH: depth_preprocessor, 259 | ModalityType.THERMAL: thermal_preprocessor, 260 | ModalityType.IMU: imu_preprocessor, 261 | } 262 | 263 | return nn.ModuleDict(modality_preprocessors) 264 | 265 | def _create_modality_trunks( 266 | self, 267 | vision_embed_dim=1024, 268 | vision_num_blocks=24, 269 | vision_num_heads=16, 270 | text_embed_dim=768, 271 | text_num_blocks=12, 272 | text_num_heads=12, 273 | audio_embed_dim=768, 274 | audio_num_blocks=12, 275 | audio_num_heads=12, 276 | audio_drop_path=0.0, 277 | depth_embed_dim=768, 278 | depth_num_blocks=12, 279 | depth_num_heads=12, 280 | depth_drop_path=0.0, 281 | thermal_embed_dim=768, 282 | thermal_num_blocks=12, 283 | thermal_num_heads=12, 284 | thermal_drop_path=0.0, 285 | imu_embed_dim=512, 286 | imu_num_blocks=6, 287 | imu_num_heads=8, 288 | imu_drop_path=0.7, 289 | ): 290 | def instantiate_trunk( 291 | embed_dim, num_blocks, num_heads, pre_transformer_ln, add_bias_kv, drop_path 292 | ): 293 | return SimpleTransformer( 294 | embed_dim=embed_dim, 295 | num_blocks=num_blocks, 296 | ffn_dropout_rate=0.0, 297 | drop_path_rate=drop_path, 298 | attn_target=partial( 299 | MultiheadAttention, 300 | embed_dim=embed_dim, 301 | num_heads=num_heads, 302 | bias=True, 303 | add_bias_kv=add_bias_kv, 304 | ), 305 | pre_transformer_layer=nn.Sequential( 306 | nn.LayerNorm(embed_dim, eps=1e-6) 307 | if pre_transformer_ln 308 | else nn.Identity(), 309 | EinOpsRearrange("b l d -> l b d"), 310 | ), 311 | post_transformer_layer=EinOpsRearrange("l b d -> b l d"), 312 | ) 313 | 314 | modality_trunks = {} 315 | modality_trunks[ModalityType.VISION] = instantiate_trunk( 316 | vision_embed_dim, 317 | vision_num_blocks, 318 | vision_num_heads, 319 | pre_transformer_ln=True, 320 | add_bias_kv=False, 321 | drop_path=0.0, 322 | ) 323 | modality_trunks[ModalityType.TEXT] = instantiate_trunk( 324 | text_embed_dim, 325 | text_num_blocks, 326 | text_num_heads, 327 | pre_transformer_ln=False, 328 | add_bias_kv=False, 329 | drop_path=0.0, 330 | ) 331 | modality_trunks[ModalityType.AUDIO] = instantiate_trunk( 332 | audio_embed_dim, 333 | audio_num_blocks, 334 | audio_num_heads, 335 | pre_transformer_ln=False, 336 | add_bias_kv=True, 337 | drop_path=audio_drop_path, 338 | ) 339 | modality_trunks[ModalityType.DEPTH] = instantiate_trunk( 340 | depth_embed_dim, 341 | depth_num_blocks, 342 | depth_num_heads, 343 | pre_transformer_ln=False, 344 | add_bias_kv=True, 345 | drop_path=depth_drop_path, 346 | ) 347 | modality_trunks[ModalityType.THERMAL] = instantiate_trunk( 348 | thermal_embed_dim, 349 | thermal_num_blocks, 350 | thermal_num_heads, 351 | pre_transformer_ln=False, 352 | add_bias_kv=True, 353 | drop_path=thermal_drop_path, 354 | ) 355 | modality_trunks[ModalityType.IMU] = instantiate_trunk( 356 | imu_embed_dim, 357 | imu_num_blocks, 358 | imu_num_heads, 359 | pre_transformer_ln=False, 360 | add_bias_kv=True, 361 | drop_path=imu_drop_path, 362 | ) 363 | 364 | return nn.ModuleDict(modality_trunks) 365 | 366 | def _create_modality_heads( 367 | self, 368 | out_embed_dim, 369 | vision_embed_dim, 370 | text_embed_dim, 371 | audio_embed_dim, 372 | depth_embed_dim, 373 | thermal_embed_dim, 374 | imu_embed_dim, 375 | ): 376 | modality_heads = {} 377 | 378 | modality_heads[ModalityType.VISION] = nn.Sequential( 379 | nn.LayerNorm(normalized_shape=vision_embed_dim, eps=1e-6), 380 | SelectElement(index=0), 381 | nn.Linear(vision_embed_dim, out_embed_dim, bias=False), 382 | ) 383 | 384 | modality_heads[ModalityType.TEXT] = SelectEOSAndProject( 385 | proj=nn.Sequential( 386 | nn.LayerNorm(normalized_shape=text_embed_dim, eps=1e-6), 387 | nn.Linear(text_embed_dim, out_embed_dim, bias=False), 388 | ) 389 | ) 390 | 391 | modality_heads[ModalityType.AUDIO] = nn.Sequential( 392 | nn.LayerNorm(normalized_shape=audio_embed_dim, eps=1e-6), 393 | SelectElement(index=0), 394 | nn.Linear(audio_embed_dim, out_embed_dim, bias=False), 395 | ) 396 | 397 | modality_heads[ModalityType.DEPTH] = nn.Sequential( 398 | nn.LayerNorm(normalized_shape=depth_embed_dim, eps=1e-6), 399 | SelectElement(index=0), 400 | nn.Linear(depth_embed_dim, out_embed_dim, bias=False), 401 | ) 402 | 403 | modality_heads[ModalityType.THERMAL] = nn.Sequential( 404 | nn.LayerNorm(normalized_shape=thermal_embed_dim, eps=1e-6), 405 | SelectElement(index=0), 406 | nn.Linear(thermal_embed_dim, out_embed_dim, bias=False), 407 | ) 408 | 409 | modality_heads[ModalityType.IMU] = nn.Sequential( 410 | nn.LayerNorm(normalized_shape=imu_embed_dim, eps=1e-6), 411 | SelectElement(index=0), 412 | nn.Dropout(p=0.5), 413 | nn.Linear(imu_embed_dim, out_embed_dim, bias=False), 414 | ) 415 | 416 | return nn.ModuleDict(modality_heads) 417 | 418 | def _create_modality_postprocessors(self, out_embed_dim): 419 | modality_postprocessors = {} 420 | 421 | modality_postprocessors[ModalityType.VISION] = Normalize(dim=-1) 422 | modality_postprocessors[ModalityType.TEXT] = nn.Sequential( 423 | Normalize(dim=-1), LearnableLogitScaling(learnable=True) 424 | ) 425 | modality_postprocessors[ModalityType.AUDIO] = nn.Sequential( 426 | Normalize(dim=-1), 427 | LearnableLogitScaling(logit_scale_init=20.0, learnable=False), 428 | ) 429 | modality_postprocessors[ModalityType.DEPTH] = nn.Sequential( 430 | Normalize(dim=-1), 431 | LearnableLogitScaling(logit_scale_init=5.0, learnable=False), 432 | ) 433 | modality_postprocessors[ModalityType.THERMAL] = nn.Sequential( 434 | Normalize(dim=-1), 435 | LearnableLogitScaling(logit_scale_init=10.0, learnable=False), 436 | ) 437 | modality_postprocessors[ModalityType.IMU] = nn.Sequential( 438 | Normalize(dim=-1), 439 | LearnableLogitScaling(logit_scale_init=5.0, learnable=False), 440 | ) 441 | 442 | return nn.ModuleDict(modality_postprocessors) 443 | 444 | def forward(self, inputs): 445 | outputs = {} 446 | for modality_key, modality_value in inputs.items(): 447 | reduce_list = ( 448 | modality_value.ndim >= 5 449 | ) # Audio and Video inputs consist of multiple clips 450 | if reduce_list: 451 | B, S = modality_value.shape[:2] 452 | modality_value = modality_value.reshape( 453 | B * S, *modality_value.shape[2:] 454 | ) 455 | 456 | if modality_value is not None: 457 | modality_value = self.modality_preprocessors[modality_key]( 458 | **{modality_key: modality_value} 459 | ) 460 | trunk_inputs = modality_value["trunk"] 461 | head_inputs = modality_value["head"] 462 | modality_value = self.modality_trunks[modality_key](**trunk_inputs) 463 | modality_value = self.modality_heads[modality_key]( 464 | modality_value, **head_inputs 465 | ) 466 | modality_value = self.modality_postprocessors[modality_key]( 467 | modality_value 468 | ) 469 | 470 | if reduce_list: 471 | modality_value = modality_value.reshape(B, S, -1) 472 | modality_value = modality_value.mean(dim=1) 473 | 474 | outputs[modality_key] = modality_value 475 | 476 | return outputs 477 | 478 | 479 | def imagebind_huge(pretrained=False): 480 | model = ImageBindModel( 481 | vision_embed_dim=1280, 482 | vision_num_blocks=32, 483 | vision_num_heads=16, 484 | text_embed_dim=1024, 485 | text_num_blocks=24, 486 | text_num_heads=16, 487 | out_embed_dim=1024, 488 | audio_drop_path=0.1, 489 | imu_drop_path=0.7, 490 | ) 491 | 492 | if pretrained: 493 | if not os.path.exists("imagebind_huge.pth"): 494 | print( 495 | "Downloading imagebind weights to imagebind_huge.pth ..." 496 | ) 497 | torch.hub.download_url_to_file( 498 | "https://dl.fbaipublicfiles.com/imagebind/imagebind_huge.pth", 499 | "imagebind_huge.pth", 500 | progress=True, 501 | ) 502 | 503 | model.load_state_dict(torch.load("imagebind_huge.pth")) 504 | """ 505 | dict = torch.load("/cpfs01/user/lizihan/llama-adapter/imagebind-llm/output_dir/imagebind-10.pth")['model'] 506 | for name in dict.keys(): 507 | if name.startswith("image_bind."): 508 | dict[name.replace("image_bind.","")] = dict.pop(name) 509 | model.load_state_dict(dict, strict=False) 510 | """ 511 | return model 512 | -------------------------------------------------------------------------------- /main_pretrain.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.backends.cudnn as cudnn 3 | from torch.utils.tensorboard import SummaryWriter 4 | from torch.utils.data import Dataset 5 | import torchvision.transforms as transforms 6 | 7 | import util.misc as misc 8 | from util.misc import NativeScalerWithGradNormCount as NativeScaler 9 | from PIL import Image 10 | from PIL import ImageEnhance 11 | Image.LOAD_TRUNCATED_IMAGES = True 12 | from llama.llama_adapter import LLaMA_adapter 13 | 14 | import random 15 | import deepspeed 16 | import argparse 17 | import datetime 18 | import json 19 | import numpy as np 20 | import os 21 | import time 22 | import cv2 23 | from pathlib import Path 24 | 25 | from engine_pretrain import train_one_epoch, val_one_epoch 26 | 27 | from llama import Tokenizer 28 | import fundus_prep as prep 29 | import copy 30 | try: 31 | from torchvision.transforms import InterpolationMode 32 | BICUBIC = InterpolationMode.BICUBIC 33 | except ImportError: 34 | BICUBIC = Image.BICUBIC 35 | 36 | PROMPT_DICT = { 37 | "prompt_input": ( 38 | "Below is an instruction that describes a task, paired with an input that provides further context. " 39 | "Write a response that appropriately completes the request.\n\n" 40 | "### Instruction:\n{instruction}\n\n### Input:\n{input}\n\n### Response:" 41 | ), 42 | "prompt_no_input": ( 43 | "Below is an instruction that describes a task. " 44 | "Write a response that appropriately completes the request.\n\n" 45 | "### Instruction:\n{instruction}\n\n### Response:" 46 | ), 47 | } 48 | 49 | OPTION_DICT = { 50 | 0: "A. normal", 51 | 1: "B. other diseases", 52 | 2: "C. arteriovenous ratio", 53 | 3: "D. cup-to-disc ratio", 54 | 4: "E. glaucoma", 55 | 5: "F. myopia", 56 | 6: "G. diabetic retinopathy", 57 | 7: "H. age-related macular degeneration" 58 | } 59 | 60 | class CaptionCOCO(Dataset): 61 | def __init__(self, transform, max_words=512, partition='train', tokenizer_path=None): 62 | # ann = json.load(open("/cpfs01/shared/Gvlab-A100/Gvlab-A100_hdd/lizihan/MLLM_Dataset/imagebank/imagebank_Clean.json")) 63 | # ann += json.load(open("/cpfs01/shared/Gvlab-A100/Gvlab-A100_hdd/lizihan/PMC-OA-Full/PMC_Clean.json")) 64 | if partition == 'train': 65 | # self.ann = ann 66 | ann = json.load(open("/cpfs01/user/lizihan/Dataset/-MLLM-Fundus/All_json/GPT_RITE40_Train20.json")) 67 | fileHandler = open ("/cpfs01/user/lizihan/Trainset_list_updated.txt", "r") 68 | listOfLines = fileHandler.readlines() 69 | for line in listOfLines: 70 | ann += json.load(open(line.strip())) 71 | self.ann = ann 72 | self.data_dict = {} 73 | 74 | else: 75 | ann = json.load(open("/cpfs01/user/lizihan/Dataset/-MLLM-Fundus/All_json/GPT_RITE40_Test20.json")) 76 | fileHandler = open ("/cpfs01/user/lizihan/Valset_list_updated.txt", "r") 77 | listOfLines = fileHandler.readlines() 78 | for line in listOfLines: 79 | ann += json.load(open(line.strip())) 80 | self.ann = ann 81 | self.data_dict = {} 82 | # sample_num = 10000 83 | # self.ann = random.sample(ann, sample_num) 84 | 85 | self.transform = transform 86 | self.max_words = max_words 87 | self.max_keywords = 32 88 | tokenizer = Tokenizer(model_path=tokenizer_path) 89 | self.tokenizer1 = tokenizer 90 | def __len__(self): 91 | return len(self.ann) 92 | 93 | def get_qa(self, orig_qa): 94 | qa = orig_qa.replace('\n\n', '\n') 95 | qa_list = qa.split('\n') 96 | qa_list = [sentence[6:] for sentence in qa_list] 97 | return qa_list 98 | 99 | def __getitem__(self, index): 100 | labels_cls = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0] 101 | data_item = self.ann[index] 102 | if data_item['Keyword'][0] == 'A': 103 | labels_cls[0] = 1.0 104 | if 'FHE_label' in data_item.keys(): 105 | if float(data_item['FHE_label']) > 0: 106 | labels_cls[1] = 1.0 107 | labels_cls[0] = 0.0 108 | if 'OCD_label' in data_item.keys(): 109 | if float(data_item['OCD_label']) > 0: 110 | labels_cls[2] = 1.0 111 | labels_cls[0] = 0.0 112 | if 'FBC_label' in data_item.keys(): 113 | if float(data_item['FBC_label']) > 0: 114 | labels_cls[3] = 1.0 115 | labels_cls[0] = 0.0 116 | if 'Macular_label' in data_item.keys(): 117 | if float(data_item['Macular_label']) > 0: 118 | labels_cls[4] = 1.0 119 | labels_cls[0] = 0.0 120 | if 'AV_label' in data_item.keys(): 121 | if float(data_item['AV_label']) > 0: 122 | labels_cls[5] = 1.0 123 | labels_cls[0] = 0.0 124 | 125 | if 'ImageID' in data_item.keys(): 126 | url = data_item['ImageID'] 127 | # self.data_dict[url] = self.data_dict.get(url, 0) + 1 128 | question = data_item['Instruction'] # + " Please choose from the following options: A. normal, B. other diseases, C. arteriovenous ratio, D. cup-to-disc ratio, E. glaucoma, F. myopia, G. diabetic retinopathy, H. age-related macular degeneration." 129 | answer = data_item['Answer'] # + " The answer is " + OPTION_DICT[int(labels_cls[0])] + "." 130 | if 'Instruction0' in data_item.keys(): 131 | question0 = data_item['Instruction0'] 132 | answer0 = data_item['Answer0'] 133 | question1 = data_item['Instruction1'] 134 | answer1 = data_item['Answer1'] 135 | else: 136 | question0 = " " 137 | answer0 = " " 138 | question1 = " " 139 | answer1 = " " 140 | Keyword = data_item['Keyword'] 141 | 142 | filename = url 143 | 144 | image = Image.open(filename).convert('RGB') 145 | 146 | image = ImageEnhance.Contrast(image) 147 | image = image.enhance(1.3) 148 | image = np.array(image) 149 | min_R = np.min(image[:,:,0]) 150 | min_G = np.min(image[:,:,1]) 151 | min_B = np.min(image[:,:,2]) 152 | image[:,:,0] = image[:,:,0] - min_R +1 153 | image[:,:,1] = image[:,:,1] - min_G +1 154 | image[:,:,2] = image[:,:,2] - min_B +1 155 | image = Image.fromarray(image.astype('uint8')).convert('HSV') 156 | image = self.transform(image) 157 | # input1 = question 158 | question = {'instruction': question} 159 | question0 = {'instruction': question0} 160 | question1 = {'instruction': question1} 161 | elif 'image' in data_item.keys(): 162 | url = data_item['image'] 163 | question = "This is a "+ data_item['modality']+ " image. "+data_item['question'] 164 | answer = data_item['caption'] 165 | filename = "/cpfs01/shared/Gvlab-A100/Gvlab-A100_hdd/lizihan/PMC-OA-Full/images_full/image_only/" + url 166 | try: 167 | image = Image.open(filename).convert('RGB') 168 | except: 169 | filename = "/cpfs01/shared/Gvlab-A100/Gvlab-A100_hdd/lizihan/PMC-OA-Full/images_full/image_duplicate/" + url 170 | image = Image.open(filename).convert('RGB') 171 | # image = cv2.imread(filename) 172 | # image = Image.fromarray(image) 173 | image = self.transform(image) 174 | input1 = {'instruction': question} 175 | elif 'img_id' in data_item.keys(): 176 | url = data_item['img_id'] 177 | question = "This is a "+ data_item['modality']+ " image. "+data_item['question'] 178 | answer = data_item['answer'] 179 | filename = "/cpfs01/shared/Gvlab-A100/Gvlab-A100_hdd/lizihan/MLLM_Dataset/imagebank/imagebank_image/" + url +'.jpg' 180 | try: 181 | image = Image.open(filename).convert('RGB') 182 | image = self.transform(image) 183 | input1 = {'instruction': question} 184 | except: 185 | print('Truncated image: '+str(data_item['img_id'])) 186 | # image = cv2.imread(filename) 187 | # image = Image.fromarray(image) 188 | else: 189 | image = torch.zeros(3, 448, 448) 190 | # input1 = {'instruction': data_item['instruction'], 'input': data_item['input']} 191 | input1 = data_item['instruction'] 192 | Keyword = data_item['Keyword'] 193 | answer = data_item['output'] 194 | 195 | # input1 = PROMPT_DICT['prompt_no_input'].format_map(input1) 196 | question = PROMPT_DICT['prompt_no_input'].format_map(question) 197 | question0 = PROMPT_DICT['prompt_no_input'].format_map(question0) 198 | question1 = PROMPT_DICT['prompt_no_input'].format_map(question1) 199 | input2 = question + answer + question0 + answer0 + question1 + answer1 200 | question_index = torch.tensor(self.tokenizer1.encode(question, bos=True, eos=False), dtype=torch.int64) 201 | answer_index = torch.tensor(self.tokenizer1.encode(question+answer, bos=True, eos=False), dtype=torch.int64) 202 | question0_index = torch.tensor(self.tokenizer1.encode(question+answer+question0, bos=True, eos=False), dtype=torch.int64) 203 | answer0_index = torch.tensor(self.tokenizer1.encode(question+answer+question0+answer0, bos=True, eos=False), dtype=torch.int64) 204 | question1_index = torch.tensor(self.tokenizer1.encode(question+answer+question0+answer0+question1, bos=True, eos=False), dtype=torch.int64) 205 | input2 = torch.tensor(self.tokenizer1.encode(input2, bos=True, eos=True), dtype=torch.int64) 206 | 207 | padding = self.max_words - input2.shape[0] 208 | if padding > 0: 209 | input2 = torch.cat((input2, torch.zeros(padding, dtype=torch.int64) - 1)) 210 | elif padding < 0: 211 | input2 = input2[:self.max_words] 212 | 213 | labels = copy.deepcopy(input2) 214 | 215 | labels[:len(question_index)] = -1 216 | labels[len(answer_index):len(question0_index)] = -1 217 | if len(question1_index) >= self.max_words: 218 | labels[len(answer0_index):] = -1 219 | else: 220 | labels[len(answer0_index):len(question1_index)] = -1 221 | 222 | input2_mask = input2.ge(0) 223 | label_mask = labels.ge(0) 224 | input2[~input2_mask] = 0 225 | labels[~label_mask] = 0 226 | input2_mask = input2_mask.float() 227 | label_mask = label_mask.float() 228 | 229 | # return input2, labels, input2_mask, image 230 | return input2, labels, labels_cls, image, Keyword 231 | 232 | def get_args_parser(): 233 | parser = argparse.ArgumentParser('imagebind-llm pre-training', add_help=False) 234 | parser.add_argument('--batch_size', default=64, type=int, 235 | help='Batch size per GPU (effective batch size is batch_size * accum_iter * # gpus') 236 | parser.add_argument('--epochs', default=400, type=int) 237 | parser.add_argument('--accum_iter', default=1, type=int, 238 | help='Accumulate gradient iterations (for increasing the effective batch size under memory constraints)') 239 | 240 | # Model parameters 241 | parser.add_argument('--model', default='mae_vit_large_patch16', type=str, metavar='MODEL', 242 | help='Name of model to train') # llama-adapter: currently no use 243 | parser.add_argument('--llama_path', default='/path/to/llama', type=str, 244 | help='path to LLaMA pretrained checkpoint') 245 | 246 | parser.add_argument('--input_size', default=224, type=int, 247 | help='images input size') 248 | parser.add_argument('--clip_grad', type=int, default=-1, 249 | help='grad clipping norm') 250 | # Optimizer parameters 251 | parser.add_argument('--weight_decay', type=float, default=0.05, 252 | help='weight decay (default: 0.05)') 253 | 254 | parser.add_argument('--lr', type=float, default=None, metavar='LR', 255 | help='learning rate (absolute lr)') 256 | parser.add_argument('--blr', type=float, default=1e-3, metavar='LR', 257 | help='base learning rate: absolute_lr = base_lr * total_batch_size / 256') 258 | parser.add_argument('--min_lr', type=float, default=0., metavar='LR', 259 | help='lower lr bound for cyclic schedulers that hit 0') 260 | 261 | parser.add_argument('--warmup_epochs', type=int, default=40, metavar='N', 262 | help='epochs to warmup LR') 263 | 264 | # Dataset parameters 265 | parser.add_argument('--data_path', default='/datasets01/imagenet_full_size/061417/', type=str, 266 | help='dataset path') 267 | 268 | parser.add_argument('--output_dir', default='./output_dir', 269 | help='path where to save, empty for no saving') 270 | parser.add_argument('--log_dir', default='./output_dir', 271 | help='path where to tensorboard log') 272 | parser.add_argument('--device', default='cuda', 273 | help='device to use for training / testing') 274 | parser.add_argument('--seed', default=0, type=int) 275 | parser.add_argument('--resume', default='', 276 | help='resume from checkpoint') 277 | 278 | parser.add_argument('--start_epoch', default=0, type=int, metavar='N', 279 | help='start epoch') 280 | parser.add_argument('--num_workers', default=12, type=int) 281 | parser.add_argument('--pin_mem', action='store_true', 282 | help='Pin CPU memory in DataLoader for more efficient (sometimes) transfer to GPU.') 283 | parser.add_argument('--no_pin_mem', action='store_false', dest='pin_mem') 284 | parser.set_defaults(pin_mem=True) 285 | parser.add_argument('--use_checkpoint', default=False, type=bool) 286 | 287 | # distributed training parameters 288 | parser.add_argument('--world_size', default=1, type=int, 289 | help='number of distributed processes') 290 | parser.add_argument('--local_rank', default=-1, type=int) 291 | parser.add_argument('--dist_on_itp', action='store_true') 292 | parser.add_argument('--dist_url', default='env://', 293 | help='url used to set up distributed training') 294 | 295 | return parser 296 | 297 | 298 | def main(args): 299 | misc.init_distributed_mode(args) 300 | 301 | print('job dir: {}'.format(os.path.dirname(os.path.realpath(__file__)))) 302 | print("{}".format(args).replace(', ', ',\n')) 303 | 304 | device = torch.device(args.device) 305 | 306 | # fix the seed for reproducibility 307 | seed = args.seed + misc.get_rank() 308 | torch.manual_seed(seed) 309 | np.random.seed(seed) 310 | cudnn.benchmark = True 311 | 312 | # define the model 313 | llama_type = "7B" 314 | llama_ckpt_dir = os.path.join(args.llama_path, llama_type) 315 | llama_tokenzier_path = os.path.join(llama_ckpt_dir, 'tokenizer.model') 316 | model = LLaMA_adapter(llama_ckpt_dir, llama_tokenzier_path) 317 | 318 | model.to(device) 319 | 320 | model_without_ddp = model 321 | print("Model = %s" % str(model_without_ddp)) 322 | 323 | print("Trainable Params:") 324 | print([(key, val.shape) for key, val in model.get_trainable_params().items()]) 325 | 326 | if args.distributed: 327 | model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[args.gpu], find_unused_parameters=True) 328 | model_without_ddp = model.module 329 | 330 | # training detail 331 | eff_batch_size = args.batch_size * args.accum_iter * misc.get_world_size() 332 | 333 | if args.lr is None: # only base_lr is specified 334 | args.lr = args.blr * eff_batch_size / 256 335 | 336 | param_groups = misc.add_weight_decay(model_without_ddp, args.weight_decay) 337 | optimizer = torch.optim.AdamW(param_groups, lr=args.lr, betas=(0.9, 0.95)) 338 | # print(optimizer) 339 | loss_scaler = NativeScaler() 340 | 341 | # optionally resume 342 | misc.load_model(args=args, model_without_ddp=model_without_ddp, optimizer=optimizer, loss_scaler=loss_scaler) 343 | 344 | # create data 345 | transform_train = transforms.Compose([ 346 | transforms.RandomResizedCrop(size=(448, 448), scale=(0.9, 1.0), ratio=(0.75, 1.3333), interpolation=BICUBIC, 347 | antialias=None), # 3 is bicubic 348 | transforms.ToTensor(), 349 | # transforms.Normalize(mean=[0.48145466, 0.4578275, 0.40821073], std=[0.26862954, 0.26130258, 0.27577711])]) 350 | transforms.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5])]) 351 | 352 | dataset_train = CaptionCOCO(transform=transform_train, max_words=512, partition='train', tokenizer_path=llama_tokenzier_path) 353 | dataset_val = CaptionCOCO(transform=transform_train, max_words=512, partition='val', tokenizer_path=llama_tokenzier_path) 354 | 355 | if True: # args.distributed: 356 | num_tasks = misc.get_world_size() 357 | global_rank = misc.get_rank() 358 | sampler_train = torch.utils.data.DistributedSampler( 359 | dataset_train, num_replicas=num_tasks, rank=global_rank, shuffle=True 360 | ) 361 | 362 | sampler_val = torch.utils.data.DistributedSampler( 363 | dataset_val, num_replicas=num_tasks, rank=global_rank, shuffle=True 364 | ) 365 | 366 | print("Sampler_train = %s" % str(sampler_train)) 367 | else: 368 | sampler_train = torch.utils.data.RandomSampler(dataset_train) 369 | 370 | data_loader_train = torch.utils.data.DataLoader( 371 | dataset_train, sampler=sampler_train, 372 | batch_size=args.batch_size, 373 | num_workers=args.num_workers, 374 | pin_memory=args.pin_mem, 375 | drop_last=True, 376 | ) 377 | 378 | data_loader_val = torch.utils.data.DataLoader( 379 | dataset_val, sampler=sampler_val, 380 | batch_size=args.batch_size, 381 | num_workers=args.num_workers, 382 | pin_memory=args.pin_mem, 383 | drop_last=True, 384 | ) 385 | 386 | # SummaryWrite 387 | if global_rank == 0 and args.log_dir is not None: 388 | os.makedirs(args.log_dir, exist_ok=True) 389 | log_writer = SummaryWriter(log_dir=args.log_dir) 390 | else: 391 | log_writer = None 392 | 393 | 394 | torch.cuda.reset_peak_memory_stats() 395 | torch.cuda.empty_cache() 396 | print(f"Start training for {args.epochs} epochs") 397 | start_time = time.time() 398 | 399 | for epoch in range(args.start_epoch, args.epochs): 400 | if args.distributed: 401 | data_loader_train.sampler.set_epoch(epoch) 402 | data_loader_val.sampler.set_epoch(epoch) 403 | 404 | train_stats = train_one_epoch( 405 | model, data_loader_train, 406 | optimizer, device, epoch, loss_scaler, 407 | log_writer=log_writer, 408 | args=args 409 | ) 410 | 411 | # if args.output_dir and ((epoch+1) % 5 == 0 or (epoch + 1) == args.epochs): 412 | if args.output_dir and ((epoch+1) % 5 == 0 ): 413 | 414 | misc.save_model( 415 | args=args, model=model, model_without_ddp=model_without_ddp, optimizer=optimizer, 416 | loss_scaler=loss_scaler, epoch=epoch) 417 | 418 | log_stats = {**{f'train_{k}': v for k, v in train_stats.items()}, 419 | 'epoch': epoch, 420 | **{f'val_{k}': v for k, v in train_stats.items()}} 421 | 422 | if args.output_dir and misc.is_main_process(): 423 | if log_writer is not None: 424 | log_writer.flush() 425 | with open(os.path.join(args.output_dir, "log.txt"), mode="a", encoding="utf-8") as f: 426 | f.write(json.dumps(log_stats) + "\n") 427 | 428 | total_time = time.time() - start_time 429 | total_time_str = str(datetime.timedelta(seconds=int(total_time))) 430 | print('Training time {}'.format(total_time_str)) 431 | 432 | if __name__ == '__main__': 433 | args = get_args_parser() 434 | args = args.parse_args() 435 | if args.output_dir: 436 | Path(args.output_dir).mkdir(parents=True, exist_ok=True) 437 | main(args) 438 | -------------------------------------------------------------------------------- /ImageBind/LICENSE: -------------------------------------------------------------------------------- 1 | Attribution-NonCommercial-ShareAlike 4.0 International 2 | 3 | ======================================================================= 4 | 5 | Creative Commons Corporation ("Creative Commons") is not a law firm and 6 | does not provide legal services or legal advice. Distribution of 7 | Creative Commons public licenses does not create a lawyer-client or 8 | other relationship. Creative Commons makes its licenses and related 9 | information available on an "as-is" basis. Creative Commons gives no 10 | warranties regarding its licenses, any material licensed under their 11 | terms and conditions, or any related information. Creative Commons 12 | disclaims all liability for damages resulting from their use to the 13 | fullest extent possible. 14 | 15 | Using Creative Commons Public Licenses 16 | 17 | Creative Commons public licenses provide a standard set of terms and 18 | conditions that creators and other rights holders may use to share 19 | original works of authorship and other material subject to copyright 20 | and certain other rights specified in the public license below. The 21 | following considerations are for informational purposes only, are not 22 | exhaustive, and do not form part of our licenses. 23 | 24 | Considerations for licensors: Our public licenses are 25 | intended for use by those authorized to give the public 26 | permission to use material in ways otherwise restricted by 27 | copyright and certain other rights. Our licenses are 28 | irrevocable. Licensors should read and understand the terms 29 | and conditions of the license they choose before applying it. 30 | Licensors should also secure all rights necessary before 31 | applying our licenses so that the public can reuse the 32 | material as expected. Licensors should clearly mark any 33 | material not subject to the license. This includes other CC- 34 | licensed material, or material used under an exception or 35 | limitation to copyright. More considerations for licensors: 36 | wiki.creativecommons.org/Considerations_for_licensors 37 | 38 | Considerations for the public: By using one of our public 39 | licenses, a licensor grants the public permission to use the 40 | licensed material under specified terms and conditions. If 41 | the licensor's permission is not necessary for any reason--for 42 | example, because of any applicable exception or limitation to 43 | copyright--then that use is not regulated by the license. Our 44 | licenses grant only permissions under copyright and certain 45 | other rights that a licensor has authority to grant. Use of 46 | the licensed material may still be restricted for other 47 | reasons, including because others have copyright or other 48 | rights in the material. A licensor may make special requests, 49 | such as asking that all changes be marked or described. 50 | Although not required by our licenses, you are encouraged to 51 | respect those requests where reasonable. More considerations 52 | for the public: 53 | wiki.creativecommons.org/Considerations_for_licensees 54 | 55 | ======================================================================= 56 | 57 | Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International 58 | Public License 59 | 60 | By exercising the Licensed Rights (defined below), You accept and agree 61 | to be bound by the terms and conditions of this Creative Commons 62 | Attribution-NonCommercial-ShareAlike 4.0 International Public License 63 | ("Public License"). To the extent this Public License may be 64 | interpreted as a contract, You are granted the Licensed Rights in 65 | consideration of Your acceptance of these terms and conditions, and the 66 | Licensor grants You such rights in consideration of benefits the 67 | Licensor receives from making the Licensed Material available under 68 | these terms and conditions. 69 | 70 | 71 | Section 1 -- Definitions. 72 | 73 | a. Adapted Material means material subject to Copyright and Similar 74 | Rights that is derived from or based upon the Licensed Material 75 | and in which the Licensed Material is translated, altered, 76 | arranged, transformed, or otherwise modified in a manner requiring 77 | permission under the Copyright and Similar Rights held by the 78 | Licensor. For purposes of this Public License, where the Licensed 79 | Material is a musical work, performance, or sound recording, 80 | Adapted Material is always produced where the Licensed Material is 81 | synched in timed relation with a moving image. 82 | 83 | b. Adapter's License means the license You apply to Your Copyright 84 | and Similar Rights in Your contributions to Adapted Material in 85 | accordance with the terms and conditions of this Public License. 86 | 87 | c. BY-NC-SA Compatible License means a license listed at 88 | creativecommons.org/compatiblelicenses, approved by Creative 89 | Commons as essentially the equivalent of this Public License. 90 | 91 | d. Copyright and Similar Rights means copyright and/or similar rights 92 | closely related to copyright including, without limitation, 93 | performance, broadcast, sound recording, and Sui Generis Database 94 | Rights, without regard to how the rights are labeled or 95 | categorized. For purposes of this Public License, the rights 96 | specified in Section 2(b)(1)-(2) are not Copyright and Similar 97 | Rights. 98 | 99 | e. Effective Technological Measures means those measures that, in the 100 | absence of proper authority, may not be circumvented under laws 101 | fulfilling obligations under Article 11 of the WIPO Copyright 102 | Treaty adopted on December 20, 1996, and/or similar international 103 | agreements. 104 | 105 | f. Exceptions and Limitations means fair use, fair dealing, and/or 106 | any other exception or limitation to Copyright and Similar Rights 107 | that applies to Your use of the Licensed Material. 108 | 109 | g. License Elements means the license attributes listed in the name 110 | of a Creative Commons Public License. The License Elements of this 111 | Public License are Attribution, NonCommercial, and ShareAlike. 112 | 113 | h. Licensed Material means the artistic or literary work, database, 114 | or other material to which the Licensor applied this Public 115 | License. 116 | 117 | i. Licensed Rights means the rights granted to You subject to the 118 | terms and conditions of this Public License, which are limited to 119 | all Copyright and Similar Rights that apply to Your use of the 120 | Licensed Material and that the Licensor has authority to license. 121 | 122 | j. Licensor means the individual(s) or entity(ies) granting rights 123 | under this Public License. 124 | 125 | k. NonCommercial means not primarily intended for or directed towards 126 | commercial advantage or monetary compensation. For purposes of 127 | this Public License, the exchange of the Licensed Material for 128 | other material subject to Copyright and Similar Rights by digital 129 | file-sharing or similar means is NonCommercial provided there is 130 | no payment of monetary compensation in connection with the 131 | exchange. 132 | 133 | l. Share means to provide material to the public by any means or 134 | process that requires permission under the Licensed Rights, such 135 | as reproduction, public display, public performance, distribution, 136 | dissemination, communication, or importation, and to make material 137 | available to the public including in ways that members of the 138 | public may access the material from a place and at a time 139 | individually chosen by them. 140 | 141 | m. Sui Generis Database Rights means rights other than copyright 142 | resulting from Directive 96/9/EC of the European Parliament and of 143 | the Council of 11 March 1996 on the legal protection of databases, 144 | as amended and/or succeeded, as well as other essentially 145 | equivalent rights anywhere in the world. 146 | 147 | n. You means the individual or entity exercising the Licensed Rights 148 | under this Public License. Your has a corresponding meaning. 149 | 150 | 151 | Section 2 -- Scope. 152 | 153 | a. License grant. 154 | 155 | 1. Subject to the terms and conditions of this Public License, 156 | the Licensor hereby grants You a worldwide, royalty-free, 157 | non-sublicensable, non-exclusive, irrevocable license to 158 | exercise the Licensed Rights in the Licensed Material to: 159 | 160 | a. reproduce and Share the Licensed Material, in whole or 161 | in part, for NonCommercial purposes only; and 162 | 163 | b. produce, reproduce, and Share Adapted Material for 164 | NonCommercial purposes only. 165 | 166 | 2. Exceptions and Limitations. For the avoidance of doubt, where 167 | Exceptions and Limitations apply to Your use, this Public 168 | License does not apply, and You do not need to comply with 169 | its terms and conditions. 170 | 171 | 3. Term. The term of this Public License is specified in Section 172 | 6(a). 173 | 174 | 4. Media and formats; technical modifications allowed. The 175 | Licensor authorizes You to exercise the Licensed Rights in 176 | all media and formats whether now known or hereafter created, 177 | and to make technical modifications necessary to do so. The 178 | Licensor waives and/or agrees not to assert any right or 179 | authority to forbid You from making technical modifications 180 | necessary to exercise the Licensed Rights, including 181 | technical modifications necessary to circumvent Effective 182 | Technological Measures. For purposes of this Public License, 183 | simply making modifications authorized by this Section 2(a) 184 | (4) never produces Adapted Material. 185 | 186 | 5. Downstream recipients. 187 | 188 | a. Offer from the Licensor -- Licensed Material. Every 189 | recipient of the Licensed Material automatically 190 | receives an offer from the Licensor to exercise the 191 | Licensed Rights under the terms and conditions of this 192 | Public License. 193 | 194 | b. Additional offer from the Licensor -- Adapted Material. 195 | Every recipient of Adapted Material from You 196 | automatically receives an offer from the Licensor to 197 | exercise the Licensed Rights in the Adapted Material 198 | under the conditions of the Adapter's License You apply. 199 | 200 | c. No downstream restrictions. You may not offer or impose 201 | any additional or different terms or conditions on, or 202 | apply any Effective Technological Measures to, the 203 | Licensed Material if doing so restricts exercise of the 204 | Licensed Rights by any recipient of the Licensed 205 | Material. 206 | 207 | 6. No endorsement. Nothing in this Public License constitutes or 208 | may be construed as permission to assert or imply that You 209 | are, or that Your use of the Licensed Material is, connected 210 | with, or sponsored, endorsed, or granted official status by, 211 | the Licensor or others designated to receive attribution as 212 | provided in Section 3(a)(1)(A)(i). 213 | 214 | b. Other rights. 215 | 216 | 1. Moral rights, such as the right of integrity, are not 217 | licensed under this Public License, nor are publicity, 218 | privacy, and/or other similar personality rights; however, to 219 | the extent possible, the Licensor waives and/or agrees not to 220 | assert any such rights held by the Licensor to the limited 221 | extent necessary to allow You to exercise the Licensed 222 | Rights, but not otherwise. 223 | 224 | 2. Patent and trademark rights are not licensed under this 225 | Public License. 226 | 227 | 3. To the extent possible, the Licensor waives any right to 228 | collect royalties from You for the exercise of the Licensed 229 | Rights, whether directly or through a collecting society 230 | under any voluntary or waivable statutory or compulsory 231 | licensing scheme. In all other cases the Licensor expressly 232 | reserves any right to collect such royalties, including when 233 | the Licensed Material is used other than for NonCommercial 234 | purposes. 235 | 236 | 237 | Section 3 -- License Conditions. 238 | 239 | Your exercise of the Licensed Rights is expressly made subject to the 240 | following conditions. 241 | 242 | a. Attribution. 243 | 244 | 1. If You Share the Licensed Material (including in modified 245 | form), You must: 246 | 247 | a. retain the following if it is supplied by the Licensor 248 | with the Licensed Material: 249 | 250 | i. identification of the creator(s) of the Licensed 251 | Material and any others designated to receive 252 | attribution, in any reasonable manner requested by 253 | the Licensor (including by pseudonym if 254 | designated); 255 | 256 | ii. a copyright notice; 257 | 258 | iii. a notice that refers to this Public License; 259 | 260 | iv. a notice that refers to the disclaimer of 261 | warranties; 262 | 263 | v. a URI or hyperlink to the Licensed Material to the 264 | extent reasonably practicable; 265 | 266 | b. indicate if You modified the Licensed Material and 267 | retain an indication of any previous modifications; and 268 | 269 | c. indicate the Licensed Material is licensed under this 270 | Public License, and include the text of, or the URI or 271 | hyperlink to, this Public License. 272 | 273 | 2. You may satisfy the conditions in Section 3(a)(1) in any 274 | reasonable manner based on the medium, means, and context in 275 | which You Share the Licensed Material. For example, it may be 276 | reasonable to satisfy the conditions by providing a URI or 277 | hyperlink to a resource that includes the required 278 | information. 279 | 3. If requested by the Licensor, You must remove any of the 280 | information required by Section 3(a)(1)(A) to the extent 281 | reasonably practicable. 282 | 283 | b. ShareAlike. 284 | 285 | In addition to the conditions in Section 3(a), if You Share 286 | Adapted Material You produce, the following conditions also apply. 287 | 288 | 1. The Adapter's License You apply must be a Creative Commons 289 | license with the same License Elements, this version or 290 | later, or a BY-NC-SA Compatible License. 291 | 292 | 2. You must include the text of, or the URI or hyperlink to, the 293 | Adapter's License You apply. You may satisfy this condition 294 | in any reasonable manner based on the medium, means, and 295 | context in which You Share Adapted Material. 296 | 297 | 3. You may not offer or impose any additional or different terms 298 | or conditions on, or apply any Effective Technological 299 | Measures to, Adapted Material that restrict exercise of the 300 | rights granted under the Adapter's License You apply. 301 | 302 | 303 | Section 4 -- Sui Generis Database Rights. 304 | 305 | Where the Licensed Rights include Sui Generis Database Rights that 306 | apply to Your use of the Licensed Material: 307 | 308 | a. for the avoidance of doubt, Section 2(a)(1) grants You the right 309 | to extract, reuse, reproduce, and Share all or a substantial 310 | portion of the contents of the database for NonCommercial purposes 311 | only; 312 | 313 | b. if You include all or a substantial portion of the database 314 | contents in a database in which You have Sui Generis Database 315 | Rights, then the database in which You have Sui Generis Database 316 | Rights (but not its individual contents) is Adapted Material, 317 | including for purposes of Section 3(b); and 318 | 319 | c. You must comply with the conditions in Section 3(a) if You Share 320 | all or a substantial portion of the contents of the database. 321 | 322 | For the avoidance of doubt, this Section 4 supplements and does not 323 | replace Your obligations under this Public License where the Licensed 324 | Rights include other Copyright and Similar Rights. 325 | 326 | 327 | Section 5 -- Disclaimer of Warranties and Limitation of Liability. 328 | 329 | a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE 330 | EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS 331 | AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF 332 | ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, 333 | IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, 334 | WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR 335 | PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, 336 | ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT 337 | KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT 338 | ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU. 339 | 340 | b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE 341 | TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, 342 | NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, 343 | INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, 344 | COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR 345 | USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN 346 | ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR 347 | DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR 348 | IN PART, THIS LIMITATION MAY NOT APPLY TO YOU. 349 | 350 | c. The disclaimer of warranties and limitation of liability provided 351 | above shall be interpreted in a manner that, to the extent 352 | possible, most closely approximates an absolute disclaimer and 353 | waiver of all liability. 354 | 355 | 356 | Section 6 -- Term and Termination. 357 | 358 | a. This Public License applies for the term of the Copyright and 359 | Similar Rights licensed here. However, if You fail to comply with 360 | this Public License, then Your rights under this Public License 361 | terminate automatically. 362 | 363 | b. Where Your right to use the Licensed Material has terminated under 364 | Section 6(a), it reinstates: 365 | 366 | 1. automatically as of the date the violation is cured, provided 367 | it is cured within 30 days of Your discovery of the 368 | violation; or 369 | 370 | 2. upon express reinstatement by the Licensor. 371 | 372 | For the avoidance of doubt, this Section 6(b) does not affect any 373 | right the Licensor may have to seek remedies for Your violations 374 | of this Public License. 375 | 376 | c. For the avoidance of doubt, the Licensor may also offer the 377 | Licensed Material under separate terms or conditions or stop 378 | distributing the Licensed Material at any time; however, doing so 379 | will not terminate this Public License. 380 | 381 | d. Sections 1, 5, 6, 7, and 8 survive termination of this Public 382 | License. 383 | 384 | 385 | Section 7 -- Other Terms and Conditions. 386 | 387 | a. The Licensor shall not be bound by any additional or different 388 | terms or conditions communicated by You unless expressly agreed. 389 | 390 | b. Any arrangements, understandings, or agreements regarding the 391 | Licensed Material not stated herein are separate from and 392 | independent of the terms and conditions of this Public License. 393 | 394 | 395 | Section 8 -- Interpretation. 396 | 397 | a. For the avoidance of doubt, this Public License does not, and 398 | shall not be interpreted to, reduce, limit, restrict, or impose 399 | conditions on any use of the Licensed Material that could lawfully 400 | be made without permission under this Public License. 401 | 402 | b. To the extent possible, if any provision of this Public License is 403 | deemed unenforceable, it shall be automatically reformed to the 404 | minimum extent necessary to make it enforceable. If the provision 405 | cannot be reformed, it shall be severed from this Public License 406 | without affecting the enforceability of the remaining terms and 407 | conditions. 408 | 409 | c. No term or condition of this Public License will be waived and no 410 | failure to comply consented to unless expressly agreed to by the 411 | Licensor. 412 | 413 | d. Nothing in this Public License constitutes or may be interpreted 414 | as a limitation upon, or waiver of, any privileges and immunities 415 | that apply to the Licensor or You, including from the legal 416 | processes of any jurisdiction or authority. 417 | 418 | ======================================================================= 419 | 420 | Creative Commons is not a party to its public 421 | licenses. Notwithstanding, Creative Commons may elect to apply one of 422 | its public licenses to material it publishes and in those instances 423 | will be considered the “Licensor.” The text of the Creative Commons 424 | public licenses is dedicated to the public domain under the CC0 Public 425 | Domain Dedication. Except for the limited purpose of indicating that 426 | material is shared under a Creative Commons public license or as 427 | otherwise permitted by the Creative Commons policies published at 428 | creativecommons.org/policies, Creative Commons does not authorize the 429 | use of the trademark "Creative Commons" or any other trademark or logo 430 | of Creative Commons without its prior written consent including, 431 | without limitation, in connection with any unauthorized modifications 432 | to any of its public licenses or any other arrangements, 433 | understandings, or agreements concerning use of licensed material. For 434 | the avoidance of doubt, this paragraph does not form part of the 435 | public licenses. 436 | 437 | Creative Commons may be contacted at creativecommons.org. --------------------------------------------------------------------------------