|
| 1 | +# ------------------------------------------------------------- |
| 2 | +# |
| 3 | +# Licensed to the Apache Software Foundation (ASF) under one |
| 4 | +# or more contributor license agreements. See the NOTICE file |
| 5 | +# distributed with this work for additional information |
| 6 | +# regarding copyright ownership. The ASF licenses this file |
| 7 | +# to you under the Apache License, Version 2.0 (the |
| 8 | +# "License"); you may not use this file except in compliance |
| 9 | +# with the License. You may obtain a copy of the License at |
| 10 | +# |
| 11 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 12 | +# |
| 13 | +# Unless required by applicable law or agreed to in writing, |
| 14 | +# software distributed under the License is distributed on an |
| 15 | +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
| 16 | +# KIND, either express or implied. See the License for the |
| 17 | +# specific language governing permissions and limitations |
| 18 | +# under the License. |
| 19 | +# |
| 20 | +# ------------------------------------------------------------- |
| 21 | +import numpy as np |
| 22 | +from torchvision import transforms |
| 23 | + |
| 24 | +from systemds.scuro.modality.transformed import TransformedModality |
| 25 | +from systemds.scuro.representations.unimodal import UnimodalRepresentation |
| 26 | +import torch |
| 27 | +from systemds.scuro.representations.utils import save_embeddings |
| 28 | +from systemds.scuro.modality.type import ModalityType |
| 29 | +from systemds.scuro.drsearch.operator_registry import register_representation |
| 30 | +from transformers import CLIPProcessor, CLIPModel |
| 31 | + |
| 32 | +from systemds.scuro.utils.converter import numpy_dtype_to_torch_dtype |
| 33 | +from systemds.scuro.utils.static_variables import get_device |
| 34 | +from systemds.scuro.utils.torch_dataset import CustomDataset |
| 35 | + |
| 36 | + |
| 37 | +@register_representation(ModalityType.VIDEO) |
| 38 | +class CLIPVisual(UnimodalRepresentation): |
| 39 | + def __init__(self, output_file=None): |
| 40 | + parameters = {} |
| 41 | + super().__init__("CLIPVisual", ModalityType.EMBEDDING, parameters) |
| 42 | + self.model = CLIPModel.from_pretrained("openai/clip-vit-base-patch32").to( |
| 43 | + get_device() |
| 44 | + ) |
| 45 | + self.processor = CLIPProcessor.from_pretrained("openai/clip-vit-base-patch32") |
| 46 | + self.output_file = output_file |
| 47 | + |
| 48 | + def transform(self, modality): |
| 49 | + transformed_modality = TransformedModality(modality, self) |
| 50 | + self.data_type = numpy_dtype_to_torch_dtype(modality.data_type) |
| 51 | + if next(self.model.parameters()).dtype != self.data_type: |
| 52 | + self.model = self.model.to(self.data_type) |
| 53 | + |
| 54 | + embeddings = self.create_visual_embeddings(modality) |
| 55 | + |
| 56 | + if self.output_file is not None: |
| 57 | + save_embeddings(embeddings, self.output_file) |
| 58 | + |
| 59 | + transformed_modality.data = list(embeddings.values()) |
| 60 | + return transformed_modality |
| 61 | + |
| 62 | + def create_visual_embeddings(self, modality): |
| 63 | + tf = transforms.Compose([transforms.ToPILImage(), transforms.ToTensor()]) |
| 64 | + dataset = CustomDataset( |
| 65 | + modality.data, |
| 66 | + self.data_type, |
| 67 | + get_device(), |
| 68 | + (modality.metadata[0]["width"], modality.metadata[0]["height"]), |
| 69 | + tf=tf, |
| 70 | + ) |
| 71 | + embeddings = {} |
| 72 | + for instance in torch.utils.data.DataLoader(dataset): |
| 73 | + id = int(instance["id"][0]) |
| 74 | + frames = instance["data"][0] |
| 75 | + embeddings[id] = [] |
| 76 | + batch_size = 64 |
| 77 | + |
| 78 | + for start_index in range(0, len(frames), batch_size): |
| 79 | + end_index = min(start_index + batch_size, len(frames)) |
| 80 | + frame_ids_range = range(start_index, end_index) |
| 81 | + frame_batch = frames[frame_ids_range] |
| 82 | + |
| 83 | + inputs = self.processor(images=frame_batch, return_tensors="pt") |
| 84 | + with torch.no_grad(): |
| 85 | + output = self.model.get_image_features(**inputs) |
| 86 | + |
| 87 | + if len(output.shape) > 2: |
| 88 | + output = torch.nn.functional.adaptive_avg_pool2d(output, (1, 1)) |
| 89 | + |
| 90 | + embeddings[id].extend( |
| 91 | + torch.flatten(output, 1) |
| 92 | + .detach() |
| 93 | + .cpu() |
| 94 | + .float() |
| 95 | + .numpy() |
| 96 | + .astype(modality.data_type) |
| 97 | + ) |
| 98 | + |
| 99 | + embeddings[id] = np.array(embeddings[id]) |
| 100 | + return embeddings |
| 101 | + |
| 102 | + |
| 103 | +@register_representation(ModalityType.TEXT) |
| 104 | +class CLIPText(UnimodalRepresentation): |
| 105 | + def __init__(self, output_file=None): |
| 106 | + parameters = {} |
| 107 | + super().__init__("CLIPText", ModalityType.EMBEDDING, parameters) |
| 108 | + self.model = CLIPModel.from_pretrained("openai/clip-vit-base-patch32").to( |
| 109 | + get_device() |
| 110 | + ) |
| 111 | + self.processor = CLIPProcessor.from_pretrained("openai/clip-vit-base-patch32") |
| 112 | + self.output_file = output_file |
| 113 | + |
| 114 | + def transform(self, modality): |
| 115 | + transformed_modality = TransformedModality(modality, self) |
| 116 | + |
| 117 | + embeddings = self.create_text_embeddings(modality.data, self.model) |
| 118 | + |
| 119 | + if self.output_file is not None: |
| 120 | + save_embeddings(embeddings, self.output_file) |
| 121 | + |
| 122 | + transformed_modality.data = embeddings |
| 123 | + return transformed_modality |
| 124 | + |
| 125 | + def create_text_embeddings(self, data, model): |
| 126 | + embeddings = [] |
| 127 | + for d in data: |
| 128 | + inputs = self.processor(text=d, return_tensors="pt", padding=True) |
| 129 | + with torch.no_grad(): |
| 130 | + text_embedding = model.get_text_features(**inputs) |
| 131 | + embeddings.append(text_embedding.squeeze().numpy().reshape(1, -1)) |
| 132 | + |
| 133 | + return embeddings |
0 commit comments