|
| 1 | +from beartype import beartype |
| 2 | +from beartype.typing import List, Optional |
| 3 | + |
| 4 | +import torch |
| 5 | +from torch import nn, einsum |
| 6 | +import torch.nn.functional as F |
| 7 | + |
| 8 | +from einops import rearrange |
| 9 | + |
| 10 | +import open_clip |
| 11 | + |
| 12 | +def exists(val): |
| 13 | + return val is not None |
| 14 | + |
| 15 | +def l2norm(t): |
| 16 | + return F.normalize(t, dim = -1) |
| 17 | + |
| 18 | +class OpenClipAdapter(nn.Module): |
| 19 | + @beartype |
| 20 | + def __init__( |
| 21 | + self, |
| 22 | + name = 'ViT-B/32', |
| 23 | + pretrained = 'laion400m_e32', |
| 24 | + tokenizer_name = 'ViT-B-32-quickgelu', |
| 25 | + eos_id = 49407 |
| 26 | + ): |
| 27 | + super().__init__() |
| 28 | + |
| 29 | + clip, _, preprocess = open_clip.create_model_and_transforms(name, pretrained = pretrained) |
| 30 | + tokenizer = open_clip.get_tokenizer(tokenizer_name) |
| 31 | + |
| 32 | + self.clip = clip |
| 33 | + self.tokenizer = tokenizer |
| 34 | + self.eos_id = eos_id |
| 35 | + |
| 36 | + # hook for getting final text representation |
| 37 | + |
| 38 | + text_attention_final = self.find_layer('ln_final') |
| 39 | + self._dim_latent = text_attention_final.weight.shape[0] |
| 40 | + self.text_handle = text_attention_final.register_forward_hook(self._text_hook) |
| 41 | + |
| 42 | + # normalize fn |
| 43 | + |
| 44 | + self.clip_normalize = preprocess.transforms[-1] |
| 45 | + self.cleared = False |
| 46 | + |
| 47 | + @property |
| 48 | + def device(self): |
| 49 | + return next(self.parameters()).device |
| 50 | + |
| 51 | + def find_layer(self, layer): |
| 52 | + modules = dict([*self.clip.named_modules()]) |
| 53 | + return modules.get(layer, None) |
| 54 | + |
| 55 | + def clear(self): |
| 56 | + if self.cleared: |
| 57 | + return |
| 58 | + |
| 59 | + self.text_handle() |
| 60 | + |
| 61 | + def _text_hook(self, _, inputs, outputs): |
| 62 | + self.text_encodings = outputs |
| 63 | + |
| 64 | + @property |
| 65 | + def dim_latent(self): |
| 66 | + return self._dim_latent |
| 67 | + |
| 68 | + @property |
| 69 | + def max_text_len(self): |
| 70 | + return self.clip.positional_embedding.shape[0] |
| 71 | + |
| 72 | + @beartype |
| 73 | + def embed_texts( |
| 74 | + self, |
| 75 | + texts: List[str] |
| 76 | + ): |
| 77 | + ids = self.tokenizer(texts) |
| 78 | + ids = ids.to(self.device) |
| 79 | + ids = ids[..., :self.max_text_len] |
| 80 | + |
| 81 | + is_eos_id = (ids == self.eos_id) |
| 82 | + text_mask_excluding_eos = is_eos_id.cumsum(dim = -1) == 0 |
| 83 | + text_mask = F.pad(text_mask_excluding_eos, (1, -1), value = True) |
| 84 | + text_mask = text_mask & (ids != 0) |
| 85 | + assert not self.cleared |
| 86 | + |
| 87 | + text_embed = self.clip.encode_text(ids) |
| 88 | + text_encodings = self.text_encodings |
| 89 | + text_encodings = text_encodings.masked_fill(~text_mask[..., None], 0.) |
| 90 | + return text_encodings.float(), text_mask |
0 commit comments