1import abc
2from dataclasses import dataclass
3from typing import Tuple, Optional, Any
4
5import torch
6from transformers import CLIPTextModel, AutoTokenizer
7
8
9@dataclass
[docs]
10class BatchData:
[docs]
11 images: torch.Tensor
[docs]
12 labels: Optional[torch.Tensor] = None
13
14
[docs]
15class BaseBatchProcessor(abc.ABC):
16 @abc.abstractmethod
17 def __call__(self, batch) -> BatchData:
18 raise NotImplementedError
19
20
[docs]
21class SimpleBatchProcessor(BaseBatchProcessor):
22 def __init__(self):
23 pass
24
25 def __call__(self, batch) -> BatchData:
26 return BatchData(
27 images=batch[0],
28 )
29
30
[docs]
31class ClipTextEmbedder(object):
32 def __init__(self):
[docs]
33 self.model = CLIPTextModel.from_pretrained("openai/clip-vit-base-patch32")
[docs]
34 self.tokenizer = AutoTokenizer.from_pretrained(
35 "openai/clip-vit-base-patch32"
36 )
37
[docs]
38 def embed(self, text_labels):
39 inputs = self.tokenizer(text_labels, padding=True, return_tensors="pt")
40
41 outputs = self.model(**inputs)
42
43 # last_hidden_state = outputs.last_hidden_state
44
45 pooled_output = outputs.pooler_output # pooled (EOS token) states
46 return pooled_output
47
48
[docs]
49class ClipBatchProcessor(BaseBatchProcessor):
50 def __init__(self):
[docs]
51 self.clip_text_embedder = ClipTextEmbedder()
52
53 def __call__(self, batch: Tuple[torch.Tensor, Any]) -> BatchData:
54 idx = torch.randint(0, len(batch[0][1]), (len(batch),))
55
56 images = []
57 raw_labels = []
58
59 for i in range(len(batch)):
60 images.append(batch[i][0])
61 raw_labels.append(batch[i][1][idx[i]])
62
63 labels = self.clip_text_embedder.embed(raw_labels)
64
65 return BatchData(
66 images=torch.stack(images),
67 labels=labels,
68 )