| 10 | |
| 11 | # Models in ["ViT-B/32", "ViT-B/16", "ViT-L/14", "ViT-L/14@336px"] |
| 12 | class ClipImageEmbedder(nn.Module): |
| 13 | def __init__( |
| 14 | self, |
| 15 | model="ViT-L/14", |
| 16 | jit=False, |
| 17 | device='cuda' if torch.cuda.is_available() else 'cpu', |
| 18 | antialias=True, |
| 19 | ucg_rate=0. |
| 20 | ): |
| 21 | super().__init__() |
| 22 | from clip import load as load_clip |
| 23 | self.model, _ = load_clip(name=model, device=device, jit=jit) |
| 24 | |
| 25 | self.antialias = antialias |
| 26 | |
| 27 | self.register_buffer('mean', torch.Tensor([0.48145466, 0.4578275, 0.40821073]), persistent=False) |
| 28 | self.register_buffer('std', torch.Tensor([0.26862954, 0.26130258, 0.27577711]), persistent=False) |
| 29 | self.ucg_rate = ucg_rate |
| 30 | |
| 31 | self.init_uncond() |
| 32 | |
| 33 | def init_uncond(self, path="nulltext.npy"): |
| 34 | try: |
| 35 | assert os.path.exists(path), f"Uncond file {path} not found." |
| 36 | print(f"Loading uncond from {path}") |
| 37 | uncond = torch.from_numpy(np.load(path)) |
| 38 | self.register_buffer("uncond", uncond) |
| 39 | except: |
| 40 | self.uncond = None |
| 41 | |
| 42 | def preprocess(self, x): |
| 43 | # resize to 224, normalize to [0,1] and re-normalize according to clip |
| 44 | x = torch.nn.functional.interpolate(x, size=(224, 224), mode='bilinear', align_corners=False) |
| 45 | assert x.min() >= -1. and x.max() <= 1. |
| 46 | x = (x + 1.) / 2. |
| 47 | x = (x - self.mean.reshape(1,-1,1,1)) / self.std.reshape(1,-1,1,1) |
| 48 | return x |
| 49 | |
| 50 | def forward(self, x, no_dropout=False): |
| 51 | # x is assumed to be in range [-1,1] |
| 52 | out = self.model.encode_image(self.preprocess(x)) |
| 53 | out = out.to(x.dtype) |
| 54 | if self.ucg_rate > 0. and not no_dropout: |
| 55 | out = torch.bernoulli((1. - self.ucg_rate) * torch.ones(out.shape[0], device=out.device))[:, None] * out |
| 56 | return out.unsqueeze(1) |
| 57 | |
| 58 | @torch.no_grad() |
| 59 | def get_unconditional_conditioning(self, device="cuda"): |
| 60 | if self.uncond is None: |
| 61 | raise ValueError("Unconditional conditioning not initialized.") |
| 62 | return self.uncond.to(device) |
| 63 | |
| 64 | |
| 65 | class DummyOpenCLIPTextEmbedder(nn.Module): |
nothing calls this directly
no outgoing calls
no test coverage detected