|
|
|
# Copyright 2021 Zilliz. All rights reserved.
|
|
|
|
#
|
|
|
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
|
|
# you may not use this file except in compliance with the License.
|
|
|
|
# You may obtain a copy of the License at
|
|
|
|
#
|
|
|
|
# http://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
#
|
|
|
|
# Unless required by applicable law or agreed to in writing, software
|
|
|
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
|
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
|
|
# See the License for the specific language governing permissions and
|
|
|
|
# limitations under the License.
|
|
|
|
|
|
|
|
import sys
|
|
|
|
from pathlib import Path
|
|
|
|
from PIL import Image
|
|
|
|
import torch
|
|
|
|
import yaml
|
|
|
|
from torchvision import transforms
|
|
|
|
from urllib.parse import urlparse
|
|
|
|
from timm.models.hub import download_cached_file
|
|
|
|
|
|
|
|
from towhee.types.image_utils import to_pil
|
|
|
|
from towhee.operator.base import NNOperator, OperatorFlag
|
|
|
|
from towhee.types.arg import arg, to_image_color
|
|
|
|
from towhee import register
|
|
|
|
|
|
|
|
def is_url(url_or_filename):
|
|
|
|
parsed = urlparse(url_or_filename)
|
|
|
|
return parsed.scheme in ("http", "https")
|
|
|
|
|
|
|
|
@register(output_schema=['vec'])
|
|
|
|
class Albef(NNOperator):
|
|
|
|
"""
|
|
|
|
ALBEF multi-modal embedding operator
|
|
|
|
"""
|
|
|
|
def prepare_model(self, checkpoint_path, model, interpolate_pos_embed):
|
|
|
|
checkpoint = self.load_checkpoint(checkpoint_path)
|
|
|
|
state_dict = checkpoint['model']
|
|
|
|
pos_embed_reshaped = interpolate_pos_embed(state_dict['visual_encoder.pos_embed'],model.visual_encoder)
|
|
|
|
state_dict['visual_encoder.pos_embed'] = pos_embed_reshaped
|
|
|
|
m_pos_embed_reshaped = interpolate_pos_embed(state_dict['visual_encoder_m.pos_embed'],model.visual_encoder_m)
|
|
|
|
state_dict['visual_encoder_m.pos_embed'] = m_pos_embed_reshaped
|
|
|
|
for key in list(state_dict.keys()):
|
|
|
|
if 'bert' in key:
|
|
|
|
encoder_key = key.replace('bert.','')
|
|
|
|
state_dict[encoder_key] = state_dict[key]
|
|
|
|
del state_dict[key]
|
|
|
|
msg = model.load_state_dict(state_dict,strict=False)
|
|
|
|
return model
|
|
|
|
|
|
|
|
def load_checkpoint(self, url_or_filename):
|
|
|
|
if is_url(url_or_filename):
|
|
|
|
cached_file = download_cached_file(url_or_filename, check_hash=False, progress=True)
|
|
|
|
checkpoint = torch.load(cached_file, map_location='cpu')
|
|
|
|
elif os.path.isfile(url_or_filename):
|
|
|
|
checkpoint = torch.load(url_or_filename, map_location='cpu')
|
|
|
|
else:
|
|
|
|
raise RuntimeError('checkpoint url or path is invalid')
|
|
|
|
|
|
|
|
return checkpoint
|
|
|
|
|
|
|
|
def __init__(self, model_name: str, modality: str):
|
|
|
|
self.modality = modality
|
|
|
|
config = self._configs()[model_name]
|
|
|
|
|
|
|
|
path = str(Path(__file__).parent)
|
|
|
|
sys.path.append(path)
|
|
|
|
|
|
|
|
from models.model_retrieval import ALBEF
|
|
|
|
from models.vit import interpolate_pos_embed
|
|
|
|
from models.tokenization_bert import BertTokenizer
|
|
|
|
sys.path.pop()
|
|
|
|
|
|
|
|
self.device = "cuda" if torch.cuda.is_available() else "cpu"
|
|
|
|
|
|
|
|
normalize = transforms.Normalize((0.48145466, 0.4578275, 0.40821073), (0.26862954, 0.26130258, 0.27577711))
|
|
|
|
tokenizer = BertTokenizer.from_pretrained(config['text_encoder'])
|
|
|
|
self.tokenizer = tokenizer
|
|
|
|
|
|
|
|
cfg = yaml.load(open(path + '/' + config['cfg_path'], 'r'), Loader=yaml.Loader)
|
|
|
|
cfg['bert_config'] = path + '/' + cfg['bert_config']
|
|
|
|
model = ALBEF(config=cfg, text_encoder=config['text_encoder'], tokenizer=tokenizer)
|
|
|
|
checkpoint_path = config['weights']
|
|
|
|
|
|
|
|
self.model = self.prepare_model(checkpoint_path, model, interpolate_pos_embed)
|
|
|
|
|
|
|
|
self.test_transform = transforms.Compose([
|
|
|
|
transforms.Resize((cfg['image_res'],cfg['image_res']),interpolation=Image.BICUBIC),
|
|
|
|
transforms.ToTensor(),
|
|
|
|
normalize,
|
|
|
|
])
|
|
|
|
|
|
|
|
|
|
|
|
def inference_single_data(self, data):
|
|
|
|
if self.modality == 'image':
|
|
|
|
vec = self._inference_from_image(data)
|
|
|
|
elif self.modality == 'text':
|
|
|
|
vec = self._inference_from_text(data)
|
|
|
|
else:
|
|
|
|
raise ValueError("modality[{}] not implemented.".format(self._modality))
|
|
|
|
return vec.detach().cpu().numpy().flatten()
|
|
|
|
|
|
|
|
def __call__(self, data):
|
|
|
|
if not isinstance(data, list):
|
|
|
|
data = [data]
|
|
|
|
else:
|
|
|
|
data = data
|
|
|
|
results = []
|
|
|
|
for single_data in data:
|
|
|
|
result = self.inference_single_data(single_data)
|
|
|
|
results.append(result)
|
|
|
|
if len(data) == 1:
|
|
|
|
return results[0]
|
|
|
|
else:
|
|
|
|
return results
|
|
|
|
|
|
|
|
def _inference_from_text(self, text):
|
|
|
|
text_input = self.tokenizer(text, padding='max_length', truncation=True, max_length=30, return_tensors="pt").to(self.device)
|
|
|
|
|
|
|
|
text_output = self.model.text_encoder(text_input.input_ids, attention_mask = text_input.attention_mask, mode='text')
|
|
|
|
text_feat = text_output.last_hidden_state
|
|
|
|
text_embed = self.model.text_proj(text_feat[:,0,:])
|
|
|
|
return text_embed
|
|
|
|
|
|
|
|
@arg(1, to_image_color('RGB'))
|
|
|
|
def _inference_from_image(self, img):
|
|
|
|
image = to_pil(img)
|
|
|
|
image = self.test_transform(image).unsqueeze(0)
|
|
|
|
image_feat = self.model.visual_encoder(image)
|
|
|
|
image_embed = self.model.vision_proj(image_feat[:,0,:])
|
|
|
|
return image_embed
|
|
|
|
|
|
|
|
def _configs(self):
|
|
|
|
config = {}
|
|
|
|
config['albef_4m'] = {}
|
|
|
|
config['albef_4m']['tokenizer'] = 'bert-base-uncased'
|
|
|
|
config['albef_4m']['text_encoder'] = 'bert-base-uncased'
|
|
|
|
config['albef_4m']['cfg_path'] = './configs/Retrieval_flickr.yaml'
|
|
|
|
config['albef_4m']['weights'] = 'https://storage.googleapis.com/sfr-pcl-data-research/ALBEF/ALBEF_4M.pth'
|
|
|
|
|
|
|
|
config['albef_14m'] = {}
|
|
|
|
config['albef_14m']['tokenizer'] = 'bert-base-uncased'
|
|
|
|
config['albef_14m']['text_encoder'] = 'bert-base-uncased'
|
|
|
|
config['albef_14m']['cfg_path'] = './configs/Retrieval_flickr.yaml'
|
|
|
|
config['albef_14m']['weights'] = 'https://storage.googleapis.com/sfr-pcl-data-research/ALBEF/ALBEF.pth'
|
|
|
|
return config
|