diff --git a/align_weights.pth b/align_weights.pth new file mode 100644 index 0000000000000000000000000000000000000000..e662969189b67fb91f07e06903d4bd4658d89206 --- /dev/null +++ b/align_weights.pth @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:19f6836095e80e1293fd49860f36640e2bb8c2c92e870767dc674eb501e45a42 +size 84935866 diff --git a/alignedthreeattn_backbone.py b/alignedthreeattn_backbone.py new file mode 100644 index 0000000000000000000000000000000000000000..d23cc29b3f8dafc6a555f31aacb620c36fa0ee98 --- /dev/null +++ b/alignedthreeattn_backbone.py @@ -0,0 +1,1136 @@ +import open_clip +from open_clip.transformer import VisionTransformer + +import torch +from torch import Tensor, nn +import torch.nn.functional as F + +import numpy as np + +from einops import rearrange, repeat + +from typing import List, Optional + + +from utils.factory import create_model_and_transforms, get_tokenizer +from prs_hook import hook_prs_logger + + +class CLIPPerHead(nn.Module): + def __init__( + self, pretrained="openai", model_name="ViT-B-16", spatial=False + ) -> None: + super().__init__() + self.spatial = spatial + model, _, preprocess = create_model_and_transforms( + model_name, pretrained=pretrained + ) + model.eval() + model.requires_grad_(False) + self.prs = hook_prs_logger(model, "cuda:0", spatial=self.spatial) + self.model = model + + def forward(self, x): + self.prs.reinit() + with torch.no_grad(): + attn_method = "head" if self.spatial else "head_no_spatial" + representation = self.model.encode_image( + x, attn_method=attn_method, normalize=False + ) + # attentions, mlps = self.prs.finalize(representation) + attentions = torch.stack(self.prs.attentions, axis=1).to(x.device) + # return attentions, mlps + # attentions = rearrange(attentions, "b l h d -> b (l h) d") + return attentions + + +class CLIPAttnNode(nn.Module): + def __init__( + self, pretrained="openai", model_name="ViT-B-16", spatial=False + ) -> None: + super().__init__() + self.spatial = spatial + model, _, preprocess = create_model_and_transforms( + model_name, pretrained=pretrained + ) + model.eval() + model.requires_grad_(False) + self.prs = hook_prs_logger(model, "cuda:0", spatial=self.spatial) + self.model = model + + def forward(self, x): + self.prs.reinit() + with torch.no_grad(): + attn_method = "head" if self.spatial else "head_no_spatial" + representation = self.model.encode_image( + x, attn_method=attn_method, normalize=False + ) + # attentions, mlps = self.prs.finalize(representation) + attentions = torch.stack(self.prs.attentions, axis=1).to(x.device) + # mlps = torch.stack(self.prs.mlps, axis=1).to(x.device) + # return attentions, mlps + # attentions = rearrange(attentions, "b l h d -> b (l h) d") + attentions = attentions.sum(dim=-2) + return attentions + + +class CLIPMLPNode(nn.Module): + def __init__( + self, pretrained="openai", model_name="ViT-B-16", spatial=False + ) -> None: + super().__init__() + self.spatial = spatial + model, _, preprocess = create_model_and_transforms( + model_name, pretrained=pretrained + ) + model.eval() + model.requires_grad_(False) + self.prs = hook_prs_logger(model, "cuda:0", spatial=self.spatial) + self.model = model + + def forward(self, x): + self.prs.reinit() + with torch.no_grad(): + attn_method = "head" if self.spatial else "head_no_spatial" + representation = self.model.encode_image( + x, attn_method=attn_method, normalize=False + ) + # attentions, mlps = self.prs.finalize(representation) + # attentions = torch.stack(self.prs.attentions, axis=1).to(x.device) + mlps = torch.stack(self.prs.mlps[1:], axis=1).to(x.device) + # return attentions, mlps + # attentions = rearrange(attentions, "b l h d -> b (l h) d") + # attentions = attentions.sum(dim=2) + return mlps if self.spatial else mlps[:, :, 0, :] + + +class CLIPDebug(nn.Module): + def __init__( + self, pretrained="openai", model_name="ViT-B-16", spatial=False + ) -> None: + super().__init__() + model, _, preprocess = create_model_and_transforms( + model_name, pretrained=pretrained + ) + model.eval() + model.requires_grad_(False) + self.prs = hook_prs_logger(model, "cuda:0", spatial=False) + self.model = model + + def forward(self, x): + self.prs.reinit() + with torch.no_grad(): + attn_method = "head_no_spatial" + representation = self.model.encode_image( + x, attn_method=attn_method, normalize=False + ) + # attentions, mlps = self.prs.finalize(representation) + mlps = torch.stack(self.prs.mlps, axis=1).to(x.device) + # return attentions, mlps + # attentions = rearrange(attentions, "b l h d -> b (l h) d") + return mlps[:, 1:, :] + + +class CLIPLastLayer(nn.Module): + def __init__( + self, pretrained="openai", model_name="ViT-B-16", spatial=False + ) -> None: + super().__init__() + self.spatial = spatial + model, _, preprocess = create_model_and_transforms( + model_name, pretrained=pretrained + ) + model.eval() + model.requires_grad_(False) + self.prs = hook_prs_logger(model, "cuda:0", spatial=self.spatial) + self.model = model + + def forward(self, x): + self.prs.reinit() + with torch.no_grad(): + attn_method = "head" if self.spatial else "head_no_spatial" + representation = self.model.encode_image( + x, attn_method=attn_method, normalize=False + ) + # attentions, mlps = self.prs.finalize(representation) + attentions = torch.stack(self.prs.attentions, axis=1).to(x.device) + mlps = torch.stack(self.prs.mlps, axis=1).to(x.device) + mlps = mlps if self.spatial else mlps[:, :, 0, :] + # attentions = rearrange(attentions, "b l h d -> b (l h) d") + ret = attentions[:, :].sum(2).sum(1) + mlps[:, :].sum(1) + return ret.unsqueeze(1) + + +class SlowCLIPEndNode(nn.Module): + def __init__( + self, pretrained="openai", model_name="ViT-B-16", spatial=False + ) -> None: + super().__init__() + self.spatial = spatial + model, _, preprocess = create_model_and_transforms( + model_name, pretrained=pretrained + ) + model.eval() + model.requires_grad_(False) + self.prs = hook_prs_logger(model, "cuda:0", spatial=self.spatial) + self.model = model + + def forward(self, x): + self.prs.reinit() + with torch.no_grad(): + attn_method = "head" if self.spatial else "head_no_spatial" + representation = self.model.encode_image( + x, attn_method=attn_method, normalize=False + ) + # attentions, mlps = self.prs.finalize(representation) + attentions = torch.stack(self.prs.attentions, axis=1).to(x.device) + mlps = torch.stack(self.prs.mlps, axis=1).to(x.device) + mlps = mlps if self.spatial else mlps[:, :, 0, :] + # attentions = rearrange(attentions, "b l h d -> b (l h) d") + + rets = [] + for i in range(attentions.shape[1]): + ret = attentions[:, : i + 1].sum(2).sum(1) + mlps[:, : i + 2].sum(1) + rets.append(ret) + rets = torch.stack(rets, dim=1) + return rets + + +class CLIPEverything(nn.Module): + def __init__( + self, pretrained="openai", model_name="ViT-B-16", spatial=False + ) -> None: + super().__init__() + self.spatial = spatial + model, _, preprocess = create_model_and_transforms( + model_name, pretrained=pretrained + ) + model.eval() + model.requires_grad_(False) + self.prs = hook_prs_logger(model, "cuda:0", spatial=self.spatial) + self.model = model + + def forward(self, x): + self.prs.reinit() + with torch.no_grad(): + attn_method = "head" if self.spatial else "head_no_spatial" + representation = self.model.encode_image( + x, attn_method=attn_method, normalize=False + ) + # attentions, mlps = self.prs.finalize(representation) + attentions = torch.stack(self.prs.attentions, axis=1).to(x.device) + mlps = torch.stack(self.prs.mlps, axis=1).to(x.device) + # attentions = rearrange(attentions, "b l h d -> b (l h) d") + + end_nodes = [] + for i in range(attentions.shape[1]): + ret = attentions[:, : i + 1].sum(-2).sum(1) + mlps[:, : i + 2].sum(1) + end_nodes.append(ret) + end_nodes = torch.stack(end_nodes, dim=1) + + attn_mats = torch.stack(self.prs.attn_mats, axis=1).to(x.device) + + return attentions, mlps, end_nodes, attn_mats + + +class EasyCLIPLastLayer(nn.Module): + def __init__(self, ver="ViT-B-16", data="openai", **kwargs) -> None: + super().__init__() + model, _, _ = open_clip.create_model_and_transforms(ver, pretrained=data) + self.vision_model: VisionTransformer = model.visual + self.vision_model.requires_grad_(False) + self.vision_model.eval() + + def forward( + self, + x, + ): + #### original code #### begin + + ############################## + ### patchify ### + ############################## + + # to patches - whether to use dual patchnorm - https://arxiv.org/abs/2302.01327v1 + if self.vision_model.input_patchnorm: + # einops - rearrange(x, 'b c (h p1) (w p2) -> b (h w) (c p1 p2)') + x = x.reshape( + x.shape[0], + x.shape[1], + self.vision_model.grid_size[0], + self.vision_model.patch_size[0], + self.vision_model.grid_size[1], + self.vision_model.patch_size[1], + ) + x = x.permute(0, 2, 4, 1, 3, 5) + x = x.reshape( + x.shape[0], + self.vision_model.grid_size[0] * self.vision_model.grid_size[1], + -1, + ) + x = self.vision_model.patchnorm_pre_ln(x) + x = self.vision_model.conv1(x) + else: + x = self.vision_model.conv1(x) # shape = [*, width, grid, grid] + x = x.reshape(x.shape[0], x.shape[1], -1) # shape = [*, width, grid ** 2] + x = x.permute(0, 2, 1) # shape = [*, grid ** 2, width] + + # class embeddings and positional embeddings + x = torch.cat( + [ + self.vision_model.class_embedding.to(x.dtype) + + torch.zeros( + x.shape[0], 1, x.shape[-1], dtype=x.dtype, device=x.device + ), + x, + ], + dim=1, + ) # shape = [*, grid ** 2 + 1, width] + x = x + self.vision_model.positional_embedding.to(x.dtype) + + # a patch_dropout of 0. would mean it is disabled and this function would do nothing but return what was passed in + x = self.vision_model.patch_dropout(x) + x = self.vision_model.ln_pre(x) + + #### original code #### end + + #### modified code #### begin + + ############################## + ### transformer ### + ############################## + + x = x.permute(1, 0, 2) # NLD -> LND + + local_tokens = {} + global_tokens = {} + tokens = [] + for i, r in enumerate(self.vision_model.transformer.resblocks): + x = r(x) # [1+p**2, B, D] + x_save = x.clone() + x_save = x_save[1:, :, :] # [p**2, B, D] + p = int(np.sqrt(x_save.shape[0])) + x_save = rearrange(x_save, "(p1 p2) b d -> b d p1 p2", p1=p, p2=p) + local_tokens[str(i)] = x_save + global_tokens[str(i)] = x[0, :, :] # [B, D] + tokens.append(x[0, :, :]) + return tokens[-1].unsqueeze(1) + + +class CLIPSumResidual(nn.Module): + def __init__(self, ver="ViT-B-16", data="openai", output_text=False, **kwargs) -> None: + super().__init__() + model, _, _ = open_clip.create_model_and_transforms(ver, pretrained=data) + self.vision_model: VisionTransformer = model.visual + self.vision_model.requires_grad_(False) + self.vision_model.eval() + + self.output_text = output_text + + def forward( + self, + x, + ): + #### original code #### begin + + ############################## + ### patchify ### + ############################## + + # to patches - whether to use dual patchnorm - https://arxiv.org/abs/2302.01327v1 + if self.vision_model.input_patchnorm: + # einops - rearrange(x, 'b c (h p1) (w p2) -> b (h w) (c p1 p2)') + x = x.reshape( + x.shape[0], + x.shape[1], + self.vision_model.grid_size[0], + self.vision_model.patch_size[0], + self.vision_model.grid_size[1], + self.vision_model.patch_size[1], + ) + x = x.permute(0, 2, 4, 1, 3, 5) + x = x.reshape( + x.shape[0], + self.vision_model.grid_size[0] * self.vision_model.grid_size[1], + -1, + ) + x = self.vision_model.patchnorm_pre_ln(x) + x = self.vision_model.conv1(x) + else: + x = self.vision_model.conv1(x) # shape = [*, width, grid, grid] + x = x.reshape(x.shape[0], x.shape[1], -1) # shape = [*, width, grid ** 2] + x = x.permute(0, 2, 1) # shape = [*, grid ** 2, width] + + # class embeddings and positional embeddings + x = torch.cat( + [ + self.vision_model.class_embedding.to(x.dtype) + + torch.zeros( + x.shape[0], 1, x.shape[-1], dtype=x.dtype, device=x.device + ), + x, + ], + dim=1, + ) # shape = [*, grid ** 2 + 1, width] + x = x + self.vision_model.positional_embedding.to(x.dtype) + + # a patch_dropout of 0. would mean it is disabled and this function would do nothing but return what was passed in + x = self.vision_model.patch_dropout(x) + x = self.vision_model.ln_pre(x) + + #### original code #### end + + #### modified code #### begin + + ############################## + ### transformer ### + ############################## + + x = x.permute(1, 0, 2) # NLD -> LND + + + tokens = [] + for i, r in enumerate(self.vision_model.transformer.resblocks): + x = r(x) # [1+p**2, B, D] + tokens.append(x.permute(1, 0, 2)) + mytokens = torch.stack(tokens, dim=1) + x = x.permute(1, 0, 2) # LND -> NLD + + if self.vision_model.attn_pool is not None: + x = self.vision_model.attn_pool(x) + x = self.vision_model.ln_post(x) + pooled, tokens = self.vision_model._global_pool(x) + else: + pooled, tokens = self.vision_model._global_pool(x) + pooled = self.vision_model.ln_post(pooled) + + if self.vision_model.proj is not None: + pooled = pooled @ self.vision_model.proj + + if self.output_text: + return pooled, mytokens + + return mytokens + +class CLIPEndNode(nn.Module): + def __init__(self, ver="ViT-B-16", data="openai", spatial=False, **kwargs) -> None: + super().__init__() + model, _, _ = open_clip.create_model_and_transforms(ver, pretrained=data) + self.vision_model: VisionTransformer = model.visual + self.vision_model.requires_grad_(False) + self.vision_model.eval() + + self.spatial = spatial + + def forward( + self, + x, + ): + #### original code #### begin + + ############################## + ### patchify ### + ############################## + + # to patches - whether to use dual patchnorm - https://arxiv.org/abs/2302.01327v1 + if self.vision_model.input_patchnorm: + # einops - rearrange(x, 'b c (h p1) (w p2) -> b (h w) (c p1 p2)') + x = x.reshape( + x.shape[0], + x.shape[1], + self.vision_model.grid_size[0], + self.vision_model.patch_size[0], + self.vision_model.grid_size[1], + self.vision_model.patch_size[1], + ) + x = x.permute(0, 2, 4, 1, 3, 5) + x = x.reshape( + x.shape[0], + self.vision_model.grid_size[0] * self.vision_model.grid_size[1], + -1, + ) + x = self.vision_model.patchnorm_pre_ln(x) + x = self.vision_model.conv1(x) + else: + x = self.vision_model.conv1(x) # shape = [*, width, grid, grid] + x = x.reshape(x.shape[0], x.shape[1], -1) # shape = [*, width, grid ** 2] + x = x.permute(0, 2, 1) # shape = [*, grid ** 2, width] + + # class embeddings and positional embeddings + x = torch.cat( + [ + self.vision_model.class_embedding.to(x.dtype) + + torch.zeros( + x.shape[0], 1, x.shape[-1], dtype=x.dtype, device=x.device + ), + x, + ], + dim=1, + ) # shape = [*, grid ** 2 + 1, width] + x = x + self.vision_model.positional_embedding.to(x.dtype) + + # a patch_dropout of 0. would mean it is disabled and this function would do nothing but return what was passed in + x = self.vision_model.patch_dropout(x) + x = self.vision_model.ln_pre(x) + + #### original code #### end + + #### modified code #### begin + + ############################## + ### transformer ### + ############################## + + x = x.permute(1, 0, 2) # NLD -> LND + + local_tokens = {} + global_tokens = {} + tokens = [] + for i, r in enumerate(self.vision_model.transformer.resblocks): + x = r(x) # [1+p**2, B, D] + x_save = x.clone() + x_save = x_save[1:, :, :] # [p**2, B, D] + p = int(np.sqrt(x_save.shape[0])) + x_save = rearrange(x_save, "(p1 p2) b d -> b d p1 p2", p1=p, p2=p) + local_tokens[str(i)] = x_save + global_tokens[str(i)] = x[0, :, :] # [B, D] + if self.spatial: + tokens.append(rearrange(x, "p b d -> b p d")) + else: + tokens.append(x[0, :, :]) + return torch.stack(tokens, dim=1) + + # return local_tokens, global_tokens + + +class ModifiedCLIP(nn.Module): + def __init__(self, ver="ViT-B-16", data="openai", **kwargs) -> None: + super().__init__() + model, _, _ = open_clip.create_model_and_transforms(ver, pretrained=data) + self.vision_model: VisionTransformer = model.visual + self.vision_model.requires_grad_(False) + self.vision_model.eval() + + def get_tokens( + self, + x, + ): + #### original code #### begin + + ############################## + ### patchify ### + ############################## + + # to patches - whether to use dual patchnorm - https://arxiv.org/abs/2302.01327v1 + if self.vision_model.input_patchnorm: + # einops - rearrange(x, 'b c (h p1) (w p2) -> b (h w) (c p1 p2)') + x = x.reshape( + x.shape[0], + x.shape[1], + self.vision_model.grid_size[0], + self.vision_model.patch_size[0], + self.vision_model.grid_size[1], + self.vision_model.patch_size[1], + ) + x = x.permute(0, 2, 4, 1, 3, 5) + x = x.reshape( + x.shape[0], + self.vision_model.grid_size[0] * self.vision_model.grid_size[1], + -1, + ) + x = self.vision_model.patchnorm_pre_ln(x) + x = self.vision_model.conv1(x) + else: + x = self.vision_model.conv1(x) # shape = [*, width, grid, grid] + x = x.reshape(x.shape[0], x.shape[1], -1) # shape = [*, width, grid ** 2] + x = x.permute(0, 2, 1) # shape = [*, grid ** 2, width] + + # class embeddings and positional embeddings + x = torch.cat( + [ + self.vision_model.class_embedding.to(x.dtype) + + torch.zeros( + x.shape[0], 1, x.shape[-1], dtype=x.dtype, device=x.device + ), + x, + ], + dim=1, + ) # shape = [*, grid ** 2 + 1, width] + x = x + self.vision_model.positional_embedding.to(x.dtype) + + # a patch_dropout of 0. would mean it is disabled and this function would do nothing but return what was passed in + x = self.vision_model.patch_dropout(x) + x = self.vision_model.ln_pre(x) + + #### original code #### end + + #### modified code #### begin + + ############################## + ### transformer ### + ############################## + + x = x.permute(1, 0, 2) # NLD -> LND + + local_tokens = {} + global_tokens = {} + for i, r in enumerate(self.vision_model.transformer.resblocks): + x = r(x) # [1+p**2, B, D] + x_save = x.clone() + x_save = x_save[1:, :, :] # [p**2, B, D] + p = int(np.sqrt(x_save.shape[0])) + x_save = rearrange(x_save, "(p1 p2) b d -> b d p1 p2", p1=p, p2=p) + local_tokens[str(i)] = x_save + global_tokens[str(i)] = x[0, :, :] # [B, D] + + return local_tokens, global_tokens + + +# from dinov2.models.vision_transformer import DinoVisionTransformer + + +class ModifiedDiNOv2(nn.Module): + def __init__(self, ver="dinov2_vitb14", **kwargs) -> None: + super().__init__() + vision_model = torch.hub.load("facebookresearch/dinov2", ver) + # self.vision_model: DinoVisionTransformer = vision_model + self.vision_model = vision_model + self.vision_model.requires_grad_(False) + self.vision_model.eval() + + def get_tokens( + self, + x, + ): + #### original code #### begin + x = self.vision_model.prepare_tokens_with_masks(x) + #### original code #### end + + #### modified code #### begin + local_tokens = {} + global_tokens = {} + for i, blk in enumerate(self.vision_model.blocks): + x = blk(x) + saved_x = x.clone() + global_tokens[str(i)] = saved_x[:, 0, :] # [B, C] + saved_x = saved_x[:, 1:, :] # remove cls token, [B, N, C] + p = int(np.sqrt(saved_x.shape[1])) + saved_x = rearrange(saved_x, "b (p1 p2) c -> b c p1 p2", p1=p, p2=p) + local_tokens[str(i)] = saved_x + return local_tokens, global_tokens + + +class DiNOv2EndNode(nn.Module): + def __init__(self, ver="dinov2_vitb14_reg", num_layers=12, spatial=False) -> None: + super().__init__() + self.dinov2 = torch.hub.load("facebookresearch/dinov2", ver) + self.dinov2.requires_grad_(False) + self.dinov2.eval() + + self.num_layers = num_layers + self.spatial = spatial + + def forward(self, x): + out = self.dinov2.get_intermediate_layers( + x, self.num_layers, return_class_token=True, norm=False + ) + class_tokens, spatial_tokens = [], [] + for i, (sp, cls) in enumerate(out): + class_tokens.append(cls) + spatial_tokens.append(sp) + if self.spatial: + c = torch.stack(class_tokens, dim=1) # [B, L, C] + p = torch.stack(spatial_tokens, dim=1) # [B, L, P, C] + c = repeat(c, "b l c -> b l p c", p=1) + return torch.cat([c, p], dim=2) + else: + return torch.stack(class_tokens, dim=1) + + +class DiNOv2SumResidual(nn.Module): + def __init__(self, ver="dinov2_vitb14_reg", num_layers=12, spatial=True) -> None: + super().__init__() + self.dinov2 = torch.hub.load("facebookresearch/dinov2", ver) + self.dinov2.requires_grad_(False) + self.dinov2.eval() + + self.num_layers = num_layers + self.spatial = spatial + + def forward(self, x): + # resample to 196x196 + x = torch.nn.functional.interpolate(x, size=(196, 196), mode="bilinear") + out = self.dinov2.get_intermediate_layers( + x, self.num_layers, return_class_token=True, norm=False + ) + class_tokens, spatial_tokens = [], [] + for i, (sp, cls) in enumerate(out): + class_tokens.append(cls) + spatial_tokens.append(sp) + if self.spatial: + c = torch.stack(class_tokens, dim=1) # [B, L, C] + p = torch.stack(spatial_tokens, dim=1) # [B, L, P, C] + c = repeat(c, "b l c -> b l p c", p=1) + return torch.cat([c, p], dim=2) + else: + return torch.stack(class_tokens, dim=1) + + +class DiNOv2AttnMlpNode(nn.Module): + + def __init__(self, ver="dinov2_vitb14_reg", num_reg=4) -> None: + super().__init__() + dinov2 = torch.hub.load("facebookresearch/dinov2", ver) + dinov2.requires_grad_(False) + dinov2.eval() + + def forward(self, x: Tensor) -> Tensor: + def attn_residual_func(x: Tensor) -> Tensor: + return self.ls1(self.attn(self.norm1(x))) + + def ffn_residual_func(x: Tensor) -> Tensor: + return self.ls2(self.mlp(self.norm2(x))) + + self.saved_attn_node = attn_residual_func(x) + x = x + self.saved_attn_node + self.saved_mlp_node = ffn_residual_func(x) + x = x + self.saved_mlp_node + return x + + setattr(dinov2.blocks[0].__class__, "forward", forward) + + self.dinov2 = dinov2 + self.num_reg = num_reg + + def forward(self, x: Tensor) -> Tensor: + out = self.dinov2(x) + attn_nodes = [block.saved_attn_node for block in self.dinov2.blocks] + mlp_nodes = [block.saved_mlp_node for block in self.dinov2.blocks] + nodes = torch.stack(attn_nodes + mlp_nodes, dim=1) + # remove register tokens + nodes = torch.cat([nodes[:, :, :1], nodes[:, :, self.num_reg + 1 :]], dim=2) + return nodes + + +class DiNOv2AttnNode(nn.Module): + def __init__(self, ver="dinov2_vitb14_reg", num_reg=4) -> None: + super().__init__() + self.dino = DiNOv2AttnMlpNode(ver=ver, num_reg=num_reg) + self.num_reg = num_reg + + def forward(self, x: Tensor) -> Tensor: + # resample to 196x196 + # x = torch.nn.functional.interpolate(x, size=(196, 196), mode="bilinear") + out = self.dino(x) + nodes = [block.saved_attn_node for block in self.dino.dinov2.blocks] + nodes = torch.stack(nodes, dim=1) + # remove register tokens + nodes = torch.cat([nodes[:, :, :1], nodes[:, :, self.num_reg + 1 :]], dim=2) + return nodes + + + +class DINOv1AttnNode(nn.Module): + def __init__(self, ver='dino_vits16'): + super().__init__() + dino = torch.hub.load('facebookresearch/dino:main', ver) + dino.requires_grad_(False) + dino.eval() + + def forward(self, x, return_attention=False): + y, attn = self.attn(self.norm1(x)) + if return_attention: + return attn + self.saved_attn = y + x = x + self.drop_path(y) + x = x + self.drop_path(self.mlp(self.norm2(x))) + return x + + setattr(dino.blocks[0].__class__, 'forward', forward) + self.dino = dino + + def forward(self, x): + out = self.dino(x) + attn_nodes = [block.saved_attn for block in self.dino.blocks] + out = torch.stack(attn_nodes, dim=1) + d = out.shape[-1] + if d < 768: + out = F.pad(out, (0, 768 - d), 'constant', 0) + return out + + +from segment_anything import sam_model_registry, SamPredictor +from segment_anything.modeling.sam import Sam + + +class ModifiedSAM(torch.nn.Module): + def __init__(self, **kwargs): + super().__init__(**kwargs) + sam: Sam = sam_model_registry["vit_b"](checkpoint=None) + sd = torch.hub.load_state_dict_from_url( + "https://dl.fbaipublicfiles.com/segment_anything/sam_vit_b_01ec64.pth" + ) + sam.load_state_dict(sd) + + def new_forward(self, x: torch.Tensor) -> torch.Tensor: + x = self.patch_embed(x) + if self.pos_embed is not None: + x = x + self.pos_embed + local_tokens, global_tokens = {}, {} + for i, blk in enumerate(self.blocks): + x = blk(x) + x_save = x.clone() + x_save = x_save.permute(0, 3, 1, 2) + local_tokens[f"{i}"] = x_save + global_tokens[f"{i}"] = x_save.mean(dim=(2, 3)) + + return local_tokens, global_tokens + + setattr(sam.image_encoder.__class__, "forward", new_forward) + + self.image_encoder = sam.image_encoder + self.image_encoder.requires_grad_(False) + self.image_encoder.eval() + + def get_tokens( + self, + x, + ): + with torch.no_grad(): + x = torch.nn.functional.interpolate(x, size=(1024, 1024), mode="bilinear") + local_tokens, global_tokens = self.image_encoder(x) + return local_tokens, global_tokens + + +import timm + + +class ModifiedMAE(timm.models.vision_transformer.VisionTransformer): + def __init__(self, **kwargs): + super(ModifiedMAE, self).__init__(**kwargs) + + sd = torch.hub.load_state_dict_from_url( + "https://dl.fbaipublicfiles.com/mae/pretrain/mae_pretrain_vit_base.pth" + ) + + checkpoint_model = sd["model"] + state_dict = self.state_dict() + for k in ["head.weight", "head.bias"]: + if ( + k in checkpoint_model + and checkpoint_model[k].shape != state_dict[k].shape + ): + print(f"Removing key {k} from pretrained checkpoint") + del checkpoint_model[k] + + # load pre-trained model + msg = self.load_state_dict(checkpoint_model, strict=False) + print(msg) + + self.requires_grad_(False) + self.eval() + + def get_tokens( + self, + x, + ): + B = x.shape[0] + x = self.patch_embed(x) + + cls_tokens = self.cls_token.expand( + B, -1, -1 + ) # stole cls_tokens impl from Phil Wang, thanks + x = torch.cat((cls_tokens, x), dim=1) + x = x + self.pos_embed + x = self.pos_drop(x) + + local_tokens = {} + global_tokens = {} + for i, blk in enumerate(self.blocks): + x = blk(x) + saved_x = x.clone() + saved_x = saved_x[:, 1:, :] # remove cls token, [B, N, C] + p = int(np.sqrt(saved_x.shape[1])) + saved_x = rearrange(saved_x, "b (p1 p2) c -> b c p1 p2", p1=p, p2=p) + local_tokens[str(i)] = saved_x + global_tokens[str(i)] = x[:, 0, :] # [B, C] + return local_tokens, global_tokens + + +class MAEEndNode(nn.Module): + def __init__(self, spatial=False, **kwargs): + super().__init__(**kwargs) + model = ModifiedMAE() + model.requires_grad_(False) + model.eval() + self.model = model + + self.spatial = spatial + + def forward(self, x): + local_tokens, global_tokens = self.model.get_tokens(x) + # global_tokens = torch.stack(list(global_tokens.values()), dim=1) + # return global_tokens + if not self.spatial: + local_tokens = [tk.mean(dim=(2, 3)) for tk in local_tokens.values()] + local_tokens = torch.stack(local_tokens, dim=1) + return local_tokens + else: + local_tokens = [ + rearrange(tk, "b c p1 p2 -> b (p1 p2) c") + for tk in local_tokens.values() + ] + local_tokens = torch.stack(local_tokens, dim=1) + global_tokens = torch.stack(list(global_tokens.values()), dim=1) + global_tokens = repeat(global_tokens, "b l c -> b l p c", p=1) + return torch.cat([global_tokens, local_tokens], dim=2) + + +class MAEEndNodePatch(nn.Module): + def __init__(self, **kwargs): + super().__init__(**kwargs) + model = ModifiedMAE() + model.requires_grad_(False) + model.eval() + self.model = model + + def forward(self, x): + local_tokens, global_tokens = self.model.get_tokens(x) + for k, v in local_tokens.items(): + local_tokens[k] = v.mean(dim=(2, 3)) + local_tokens = torch.stack(list(local_tokens.values()), dim=1) + return local_tokens + + +class MAEAttnMlpNode(timm.models.vision_transformer.VisionTransformer): + def __init__(self, **kwargs): + super(MAEAttnMlpNode, self).__init__(**kwargs) + + sd = torch.hub.load_state_dict_from_url( + "https://dl.fbaipublicfiles.com/mae/pretrain/mae_pretrain_vit_base.pth" + ) + + checkpoint_model = sd["model"] + state_dict = self.state_dict() + for k in ["head.weight", "head.bias"]: + if ( + k in checkpoint_model + and checkpoint_model[k].shape != state_dict[k].shape + ): + print(f"Removing key {k} from pretrained checkpoint") + del checkpoint_model[k] + + # load pre-trained model + msg = self.load_state_dict(checkpoint_model, strict=False) + print(msg) + + self.requires_grad_(False) + self.eval() + + def forward(self, x): + self.saved_attn_node = self.ls1(self.attn(self.norm1(x))) + x = x + self.saved_attn_node + self.saved_mlp_node = self.ls2(self.mlp(self.norm2(x))) + x = x + self.saved_mlp_node + # x = x + self.drop_path1(self.ls1(self.attn(self.norm1(x)))) + # x = x + self.drop_path2(self.ls2(self.mlp(self.norm2(x)))) + return x + + setattr(self.blocks[0].__class__, "forward", forward) + + def forward(self, x): + out = super().forward(x) + attn_nodes = [block.saved_attn_node for block in self.blocks] + mlp_nodes = [block.saved_mlp_node for block in self.blocks] + nodes = torch.stack(attn_nodes + mlp_nodes, dim=1) + return nodes + + +class MAEAttnNode(nn.Module): + def __init__(self, **kwargs): + super().__init__(**kwargs) + model = MAEAttnMlpNode() + self.model = model + + def forward(self, x): + out = self.model(x) + attn_nodes = [block.saved_attn_node for block in self.model.blocks] + return torch.stack(attn_nodes, dim=1) + + +from torchvision.models import ViT_B_16_Weights, ViT_L_16_Weights, ViT_H_14_Weights +from torchvision.models import vit_b_16, vit_l_16, vit_h_14 +from torchvision.models import list_models, get_model +from torchvision.models.feature_extraction import ( + create_feature_extractor, + get_graph_node_names, +) + + +class ModifiedImgNet(nn.Module): + def __init__(self, **kwargs) -> None: + super().__init__() + model = get_model("vit_b_16", weights=ViT_B_16_Weights.IMAGENET1K_V1) + model.requires_grad_(False) + model.eval() + layers = [f"encoder.layers.encoder_layer_{i}.add_1" for i in range(12)] + model = create_feature_extractor(model, layers) + + self.model = model + + def get_tokens( + self, + x, + ): + em = self.model(x) + out_list = list(em.values()) + + local_tokens = {} + global_tokens = {} + for i, out in enumerate(out_list): + saved_x = out.clone() + saved_x = saved_x[:, 1:, :] # remove cls token, [B, N, C] + p = int(np.sqrt(saved_x.shape[1])) + saved_x = rearrange(saved_x, "b (p1 p2) c -> b c p1 p2", p1=p, p2=p) + local_tokens[str(i)] = saved_x + global_tokens[str(i)] = out[:, 0, :] # [B, C] + return local_tokens, global_tokens + + +import math +import torch +import torch.nn as nn +from functools import partial, reduce +from operator import mul + +from timm.models.layers import PatchEmbed + + +class ModifiedMoCov3(timm.models.vision_transformer.VisionTransformer): + def __init__( + self, + stop_grad_conv1=False, + norm_layer=partial(nn.LayerNorm, eps=1e-6), + **kwargs, + ): + super().__init__(norm_layer=partial(nn.LayerNorm, eps=1e-6), **kwargs) + # Use fixed 2D sin-cos position embedding + self.build_2d_sincos_position_embedding() + + # weight initialization + for name, m in self.named_modules(): + if isinstance(m, nn.Linear): + if "qkv" in name: + # treat the weights of Q, K, V separately + val = math.sqrt( + 6.0 / float(m.weight.shape[0] // 3 + m.weight.shape[1]) + ) + nn.init.uniform_(m.weight, -val, val) + else: + nn.init.xavier_uniform_(m.weight) + nn.init.zeros_(m.bias) + nn.init.normal_(self.cls_token, std=1e-6) + + if isinstance(self.patch_embed, PatchEmbed): + # xavier_uniform initialization + val = math.sqrt( + 6.0 + / float( + 3 * reduce(mul, self.patch_embed.patch_size, 1) + self.embed_dim + ) + ) + nn.init.uniform_(self.patch_embed.proj.weight, -val, val) + nn.init.zeros_(self.patch_embed.proj.bias) + + if stop_grad_conv1: + self.patch_embed.proj.weight.requires_grad = False + self.patch_embed.proj.bias.requires_grad = False + + checkpoint = torch.hub.load_state_dict_from_url( + "https://dl.fbaipublicfiles.com/moco-v3/vit-b-300ep/vit-b-300ep.pth.tar" + ) + + linear_keyword = "head" + # rename moco pre-trained keys + state_dict = checkpoint["state_dict"] + for k in list(state_dict.keys()): + # retain only base_encoder up to before the embedding layer + if k.startswith("module.base_encoder") and not k.startswith( + "module.base_encoder.%s" % linear_keyword + ): + # remove prefix + state_dict[k[len("module.base_encoder.") :]] = state_dict[k] + # delete renamed or unused k + del state_dict[k] + + msg = self.load_state_dict(state_dict, strict=False) + assert set(msg.missing_keys) == { + "%s.weight" % linear_keyword, + "%s.bias" % linear_keyword, + } + + # print("=> loaded pre-trained self '{}'".format(checkpoint)) + + self.requires_grad_(False) + self.eval() + + def build_2d_sincos_position_embedding(self, temperature=10000.0): + h, w = self.patch_embed.grid_size + grid_w = torch.arange(w, dtype=torch.float32) + grid_h = torch.arange(h, dtype=torch.float32) + grid_w, grid_h = torch.meshgrid(grid_w, grid_h) + assert ( + self.embed_dim % 4 == 0 + ), "Embed dimension must be divisible by 4 for 2D sin-cos position embedding" + pos_dim = self.embed_dim // 4 + omega = torch.arange(pos_dim, dtype=torch.float32) / pos_dim + omega = 1.0 / (temperature**omega) + out_w = torch.einsum("m,d->md", [grid_w.flatten(), omega]) + out_h = torch.einsum("m,d->md", [grid_h.flatten(), omega]) + pos_emb = torch.cat( + [torch.sin(out_w), torch.cos(out_w), torch.sin(out_h), torch.cos(out_h)], + dim=1, + )[None, :, :] + + # assert self.num_tokens == 1, 'Assuming one and only one token, [cls]' + pe_token = torch.zeros([1, 1, self.embed_dim], dtype=torch.float32) + self.pos_embed = nn.Parameter(torch.cat([pe_token, pos_emb], dim=1)) + self.pos_embed.requires_grad = False + + def get_tokens( + self, + x, + ): + B = x.shape[0] + x = self.patch_embed(x) + + cls_tokens = self.cls_token.expand( + B, -1, -1 + ) # stole cls_tokens impl from Phil Wang, thanks + x = torch.cat((cls_tokens, x), dim=1) + x = x + self.pos_embed + x = self.pos_drop(x) + + local_tokens = {} + global_tokens = {} + for i, blk in enumerate(self.blocks): + x = blk(x) + saved_x = x.clone() + saved_x = saved_x[:, 1:, :] # remove cls token, [B, N, C] + p = int(np.sqrt(saved_x.shape[1])) + saved_x = rearrange(saved_x, "b (p1 p2) c -> b c p1 p2", p1=p, p2=p) + local_tokens[str(i)] = saved_x + global_tokens[str(i)] = x[:, 0, :] # [B, C] + return local_tokens, global_tokens + + +if __name__ == "__main__": + # clip = CLIPAttnNode().cuda() + # dino = DiNOv2AttnNode().cuda() + dinov1 = DINOv1AttnNode().cuda() + # mae = MAEAttnNode().cuda() + x = torch.randn(1, 3, 224, 224).cuda() + # print(clip(x).shape) + # print(dino(x).shape) + # print(mae(x).shape) + print(dinov1(x).shape) diff --git a/alignedthreeattn_model.py b/alignedthreeattn_model.py new file mode 100644 index 0000000000000000000000000000000000000000..1e6523872927478c630a8974835a202381d4af93 --- /dev/null +++ b/alignedthreeattn_model.py @@ -0,0 +1,38 @@ +# %% +import os +import torch +from PIL import Image +from einops import rearrange, repeat +import numpy as np + +import torch +import torch.nn.functional as F + +align_weights = torch.load("align_weights.pth") +from torch import nn +from backbone import CLIPAttnNode, DiNOv2AttnNode, MAEAttnNode +class ThreeAttnNodes(nn.Module): + def __init__(self, align_weights=align_weights): + super().__init__() + self.backbone1 = CLIPAttnNode() + self.backbone2 = DiNOv2AttnNode() + self.backbone3 = MAEAttnNode() + for backbone in [self.backbone1, self.backbone2, self.backbone3]: + backbone.requires_grad_(False) + backbone.eval() + self.align_weights = align_weights + + @torch.no_grad() + def forward(self, x): + # resize x to 672x672 + x = F.interpolate(x, size=(672, 672), mode="bilinear") + feat1 = self.backbone1(x) + feat3 = self.backbone3(x) + # resize x to 588x588 + x = F.interpolate(x, size=(588, 588), mode="bilinear") + feat2 = self.backbone2(x) + feats = torch.cat([feat1, feat2, feat3], dim=1) + out = torch.einsum("b l p i, l o i -> b l p o", feats, self.align_weights) + out = rearrange(out[:, :, 1:], "b l (h w) o -> b l h w o", h=42, w=42) + return out + diff --git a/prs_hook.py b/prs_hook.py new file mode 100644 index 0000000000000000000000000000000000000000..b606bde0236660e259ca2ce607a64fce5b06ceba --- /dev/null +++ b/prs_hook.py @@ -0,0 +1,224 @@ +import time +import numpy as np +import torch +from PIL import Image +import glob +import sys +import argparse +import datetime +import json +from pathlib import Path + + +class PRSLogger(object): + def __init__(self, model, device, spatial: bool = True): + self.current_layer = 0 + self.device = device + self.attentions = [] + self.mlps = [] + self.ks = [] + self.qs = [] + self.vs = [] + self.attn_mats = [] + self.spatial = spatial + self.post_ln_std = None + self.post_ln_mean = None + self.model = model + + @torch.no_grad() + def compute_attentions_spatial(self, ret): + assert ( + len(ret.shape) == 5 + ), "Verify that you use method=`head` and not method=`head_no_spatial`" # [b, n, m, h, d] + assert ( + self.spatial + ), "Verify that you use method=`head` and not method=`head_no_spatial`" + bias_term = self.model.visual.transformer.resblocks[ + self.current_layer + ].attn.out_proj.bias + self.current_layer += 1 + return_value = ret[:, 0] # This is only for the cls token + self.attentions.append( + return_value + + bias_term[np.newaxis, np.newaxis, np.newaxis] + / (return_value.shape[1] * return_value.shape[2]) + ) # [b, n, h, d] + return ret + + @torch.no_grad() + def compute_attentions_non_spatial(self, ret): + assert ( + len(ret.shape) == 4 + ), "Verify that you use method=`head_no_spatial` and not method=`head`" # [b, n, h, d] + assert ( + not self.spatial + ), "Verify that you use method=`head_no_spatial` and not method=`head`" + bias_term = self.model.visual.transformer.resblocks[ + self.current_layer + ].attn.out_proj.bias + self.current_layer += 1 + # return_value = ret[:, 0] # This is only for the cls token + return_value = ret + self.attentions.append( + return_value + bias_term / (return_value.shape[-2]) + ) # [b, h, d] + return ret + + @torch.no_grad() + def compute_k(self, ret): + self.ks.append(ret) # [b, n, h, d] + return ret + + @torch.no_grad() + def compute_q(self, ret): + self.qs.append(ret) + return ret + + @torch.no_grad() + def compute_v(self, ret): + self.vs.append(ret) + return ret + + @torch.no_grad() + def compute_attn_mat(self, ret): + self.attn_mats.append(ret) + return ret + + @torch.no_grad() + def compute_mlps(self, ret): + # self.mlps.append(ret[:, 0]) # [b, d] + self.mlps.append(ret) # [b, d] + return ret + + @torch.no_grad() + def log_post_ln_mean(self, ret): + self.post_ln_mean = ret # [b, 1] + return ret + + @torch.no_grad() + def log_post_ln_std(self, ret): + self.post_ln_std = ret # [b, 1] + return ret + + def _normalize_mlps(self): + len_intermediates = self.attentions.shape[1] + self.mlps.shape[1] + # This is just the normalization layer: + mean_centered = ( + self.mlps + - self.post_ln_mean[:, :, np.newaxis].to(self.device) / len_intermediates + ) + weighted_mean_centered = ( + self.model.visual.ln_post.weight.detach().to(self.device) * mean_centered + ) + weighted_mean_by_std = weighted_mean_centered / self.post_ln_std[ + :, :, np.newaxis + ].to(self.device) + bias_term = ( + self.model.visual.ln_post.bias.detach().to(self.device) / len_intermediates + ) + post_ln = weighted_mean_by_std + bias_term + return post_ln @ self.model.visual.proj.detach().to(self.device) + + def _normalize_attentions_spatial(self): + len_intermediates = self.attentions.shape[1] + self.mlps.shape[1] # 2*l + 1 + normalization_term = ( + self.attentions.shape[2] * self.attentions.shape[3] + ) # n * h + # This is just the normalization layer: + mean_centered = self.attentions - self.post_ln_mean[ + :, :, np.newaxis, np.newaxis, np.newaxis + ].to(self.device) / (len_intermediates * normalization_term) + weighted_mean_centered = ( + self.model.visual.ln_post.weight.detach().to(self.device) * mean_centered + ) + weighted_mean_by_std = weighted_mean_centered / self.post_ln_std[ + :, :, np.newaxis, np.newaxis, np.newaxis + ].to(self.device) + bias_term = self.model.visual.ln_post.bias.detach().to(self.device) / ( + len_intermediates * normalization_term + ) + post_ln = weighted_mean_by_std + bias_term + return post_ln @ self.model.visual.proj.detach().to(self.device) + + def _normalize_attentions_non_spatial(self): + len_intermediates = self.attentions.shape[1] + self.mlps.shape[1] # 2*l + 1 + normalization_term = self.attentions.shape[2] # h + # This is just the normalization layer: + mean_centered = self.attentions - self.post_ln_mean[ + :, :, np.newaxis, np.newaxis + ].to(self.device) / (len_intermediates * normalization_term) + weighted_mean_centered = ( + self.model.visual.ln_post.weight.detach().to(self.device) * mean_centered + ) + weighted_mean_by_std = weighted_mean_centered / self.post_ln_std[ + :, :, np.newaxis, np.newaxis + ].to(self.device) + bias_term = self.model.visual.ln_post.bias.detach().to(self.device) / ( + len_intermediates * normalization_term + ) + post_ln = weighted_mean_by_std + bias_term + return post_ln @ self.model.visual.proj.detach().to(self.device) + + @torch.no_grad() + def finalize(self, representation): + """We calculate the post-ln scaling, project it and normalize by the last norm.""" + self.attentions = torch.stack(self.attentions, axis=1).to( + self.device + ) # [b, l, n, h, d] + self.mlps = torch.stack(self.mlps, axis=1).to(self.device) # [b, l + 1, d] + if self.spatial: + projected_attentions = self._normalize_attentions_spatial() + else: + projected_attentions = self._normalize_attentions_non_spatial() + projected_mlps = self._normalize_mlps() + norm = representation.norm(dim=-1).detach() + if self.spatial: + return ( + projected_attentions + / norm[:, np.newaxis, np.newaxis, np.newaxis, np.newaxis], + projected_mlps / norm[:, np.newaxis, np.newaxis], + ) + return ( + projected_attentions / norm[:, np.newaxis, np.newaxis, np.newaxis], + projected_mlps / norm[:, np.newaxis, np.newaxis], + ) + + def reinit(self): + self.current_layer = 0 + self.attentions = [] + self.mlps = [] + self.ks = [] + self.qs = [] + self.vs = [] + self.attn_mats = [] + self.post_ln_mean = None + self.post_ln_std = None + torch.cuda.empty_cache() + + +def hook_prs_logger(model, device, spatial: bool = True): + """Hooks a projected residual stream logger to the model.""" + prs = PRSLogger(model, device, spatial=spatial) + if spatial: + model.hook_manager.register( + "visual.transformer.resblocks.*.attn.out.post", + prs.compute_attentions_spatial, + ) + else: + model.hook_manager.register( + "visual.transformer.resblocks.*.attn.out.post", + prs.compute_attentions_non_spatial, + ) + model.hook_manager.register( + "visual.transformer.resblocks.*.mlp.c_proj.post", prs.compute_mlps + ) + # model.hook_manager.register("visual.transformer.resblocks.*.attn.in_k.post", prs.compute_k) + # model.hook_manager.register("visual.transformer.resblocks.*.attn.in_q.post", prs.compute_q) + # model.hook_manager.register("visual.transformer.resblocks.*.attn.in_v.post", prs.compute_v) + model.hook_manager.register( + "visual.transformer.resblocks.*.attn.attention.pre_mask", prs.compute_attn_mat + ) + model.hook_manager.register("visual.ln_pre_post", prs.compute_mlps) + model.hook_manager.register("visual.ln_post.mean", prs.log_post_ln_mean) + model.hook_manager.register("visual.ln_post.sqrt_var", prs.log_post_ln_std) + return prs diff --git a/utils/__init__.py b/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b1e55e3310b5416223deafc9bb1ffc92f9ae6a96 --- /dev/null +++ b/utils/__init__.py @@ -0,0 +1,841 @@ +from utils.constants import OPENAI_DATASET_MEAN, OPENAI_DATASET_STD +from utils.factory import create_model, create_model_and_transforms, create_model_from_pretrained, get_tokenizer, create_loss +from utils.factory import list_models, add_model_config, get_model_config, load_checkpoint +from utils.pretrained import list_pretrained, list_pretrained_models_by_tag, list_pretrained_tags_by_model, \ + get_pretrained_url, download_pretrained_from_url, is_pretrained_cfg, get_pretrained_cfg, download_pretrained +from utils.tokenizer import SimpleTokenizer, tokenize, decode +from utils.transform import image_transform, AugmentationCfg +from utils.openai_templates import OPENAI_IMAGENET_TEMPLATES + + +# from DiNOv1 + +# Copyright (c) Facebook, Inc. and its affiliates. +# +# 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. +""" +Misc functions. + +Mostly copy-paste from torchvision references or other public repos like DETR: +https://github.com/facebookresearch/detr/blob/master/util/misc.py +""" +import os +import sys +import time +import math +import random +import datetime +import subprocess +from collections import defaultdict, deque + +import numpy as np +import torch +from torch import nn +import torch.distributed as dist +from PIL import ImageFilter, ImageOps + + +class GaussianBlur(object): + """ + Apply Gaussian Blur to the PIL image. + """ + def __init__(self, p=0.5, radius_min=0.1, radius_max=2.): + self.prob = p + self.radius_min = radius_min + self.radius_max = radius_max + + def __call__(self, img): + do_it = random.random() <= self.prob + if not do_it: + return img + + return img.filter( + ImageFilter.GaussianBlur( + radius=random.uniform(self.radius_min, self.radius_max) + ) + ) + + +class Solarization(object): + """ + Apply Solarization to the PIL image. + """ + def __init__(self, p): + self.p = p + + def __call__(self, img): + if random.random() < self.p: + return ImageOps.solarize(img) + else: + return img + + +def load_pretrained_weights(model, pretrained_weights, checkpoint_key, model_name, patch_size): + if os.path.isfile(pretrained_weights): + state_dict = torch.load(pretrained_weights, map_location="cpu") + if checkpoint_key is not None and checkpoint_key in state_dict: + print(f"Take key {checkpoint_key} in provided checkpoint dict") + state_dict = state_dict[checkpoint_key] + # remove `module.` prefix + state_dict = {k.replace("module.", ""): v for k, v in state_dict.items()} + # remove `backbone.` prefix induced by multicrop wrapper + state_dict = {k.replace("backbone.", ""): v for k, v in state_dict.items()} + msg = model.load_state_dict(state_dict, strict=False) + print('Pretrained weights found at {} and loaded with msg: {}'.format(pretrained_weights, msg)) + else: + print("Please use the `--pretrained_weights` argument to indicate the path of the checkpoint to evaluate.") + url = None + if model_name == "vit_small" and patch_size == 16: + url = "dino_deitsmall16_pretrain/dino_deitsmall16_pretrain.pth" + elif model_name == "vit_small" and patch_size == 8: + url = "dino_deitsmall8_pretrain/dino_deitsmall8_pretrain.pth" + elif model_name == "vit_base" and patch_size == 16: + url = "dino_vitbase16_pretrain/dino_vitbase16_pretrain.pth" + elif model_name == "vit_base" and patch_size == 8: + url = "dino_vitbase8_pretrain/dino_vitbase8_pretrain.pth" + elif model_name == "xcit_small_12_p16": + url = "dino_xcit_small_12_p16_pretrain/dino_xcit_small_12_p16_pretrain.pth" + elif model_name == "xcit_small_12_p8": + url = "dino_xcit_small_12_p8_pretrain/dino_xcit_small_12_p8_pretrain.pth" + elif model_name == "xcit_medium_24_p16": + url = "dino_xcit_medium_24_p16_pretrain/dino_xcit_medium_24_p16_pretrain.pth" + elif model_name == "xcit_medium_24_p8": + url = "dino_xcit_medium_24_p8_pretrain/dino_xcit_medium_24_p8_pretrain.pth" + elif model_name == "resnet50": + url = "dino_resnet50_pretrain/dino_resnet50_pretrain.pth" + if url is not None: + print("Since no pretrained weights have been provided, we load the reference pretrained DINO weights.") + state_dict = torch.hub.load_state_dict_from_url(url="https://dl.fbaipublicfiles.com/dino/" + url) + model.load_state_dict(state_dict, strict=True) + else: + print("There is no reference weights available for this model => We use random weights.") + + +def load_pretrained_linear_weights(linear_classifier, model_name, patch_size): + url = None + if model_name == "vit_small" and patch_size == 16: + url = "dino_deitsmall16_pretrain/dino_deitsmall16_linearweights.pth" + elif model_name == "vit_small" and patch_size == 8: + url = "dino_deitsmall8_pretrain/dino_deitsmall8_linearweights.pth" + elif model_name == "vit_base" and patch_size == 16: + url = "dino_vitbase16_pretrain/dino_vitbase16_linearweights.pth" + elif model_name == "vit_base" and patch_size == 8: + url = "dino_vitbase8_pretrain/dino_vitbase8_linearweights.pth" + elif model_name == "resnet50": + url = "dino_resnet50_pretrain/dino_resnet50_linearweights.pth" + if url is not None: + print("We load the reference pretrained linear weights.") + state_dict = torch.hub.load_state_dict_from_url(url="https://dl.fbaipublicfiles.com/dino/" + url)["state_dict"] + linear_classifier.load_state_dict(state_dict, strict=True) + else: + print("We use random linear weights.") + + +def clip_gradients(model, clip): + norms = [] + for name, p in model.named_parameters(): + if p.grad is not None: + param_norm = p.grad.data.norm(2) + norms.append(param_norm.item()) + clip_coef = clip / (param_norm + 1e-6) + if clip_coef < 1: + p.grad.data.mul_(clip_coef) + return norms + + +def cancel_gradients_last_layer(epoch, model, freeze_last_layer): + if epoch >= freeze_last_layer: + return + for n, p in model.named_parameters(): + if "last_layer" in n: + p.grad = None + + +def restart_from_checkpoint(ckp_path, run_variables=None, **kwargs): + """ + Re-start from checkpoint + """ + if not os.path.isfile(ckp_path): + return + print("Found checkpoint at {}".format(ckp_path)) + + # open checkpoint file + checkpoint = torch.load(ckp_path, map_location="cpu") + + # key is what to look for in the checkpoint file + # value is the object to load + # example: {'state_dict': model} + for key, value in kwargs.items(): + if key in checkpoint and value is not None: + try: + msg = value.load_state_dict(checkpoint[key], strict=False) + print("=> loaded '{}' from checkpoint '{}' with msg {}".format(key, ckp_path, msg)) + except TypeError: + try: + msg = value.load_state_dict(checkpoint[key]) + print("=> loaded '{}' from checkpoint: '{}'".format(key, ckp_path)) + except ValueError: + print("=> failed to load '{}' from checkpoint: '{}'".format(key, ckp_path)) + else: + print("=> key '{}' not found in checkpoint: '{}'".format(key, ckp_path)) + + # re load variable important for the run + if run_variables is not None: + for var_name in run_variables: + if var_name in checkpoint: + run_variables[var_name] = checkpoint[var_name] + + +def cosine_scheduler(base_value, final_value, epochs, niter_per_ep, warmup_epochs=0, start_warmup_value=0): + warmup_schedule = np.array([]) + warmup_iters = warmup_epochs * niter_per_ep + if warmup_epochs > 0: + warmup_schedule = np.linspace(start_warmup_value, base_value, warmup_iters) + + iters = np.arange(epochs * niter_per_ep - warmup_iters) + schedule = final_value + 0.5 * (base_value - final_value) * (1 + np.cos(np.pi * iters / len(iters))) + + schedule = np.concatenate((warmup_schedule, schedule)) + assert len(schedule) == epochs * niter_per_ep + return schedule + + +def bool_flag(s): + """ + Parse boolean arguments from the command line. + """ + FALSY_STRINGS = {"off", "false", "0"} + TRUTHY_STRINGS = {"on", "true", "1"} + if s.lower() in FALSY_STRINGS: + return False + elif s.lower() in TRUTHY_STRINGS: + return True + else: + raise argparse.ArgumentTypeError("invalid value for a boolean flag") + + +def fix_random_seeds(seed=31): + """ + Fix random seeds. + """ + torch.manual_seed(seed) + torch.cuda.manual_seed_all(seed) + np.random.seed(seed) + + +class SmoothedValue(object): + """Track a series of values and provide access to smoothed values over a + window or the global series average. + """ + + def __init__(self, window_size=20, fmt=None): + if fmt is None: + fmt = "{median:.6f} ({global_avg:.6f})" + self.deque = deque(maxlen=window_size) + self.total = 0.0 + self.count = 0 + self.fmt = fmt + + def update(self, value, n=1): + self.deque.append(value) + self.count += n + self.total += value * n + + def synchronize_between_processes(self): + """ + Warning: does not synchronize the deque! + """ + if not is_dist_avail_and_initialized(): + return + t = torch.tensor([self.count, self.total], dtype=torch.float64, device='cuda') + dist.barrier() + dist.all_reduce(t) + t = t.tolist() + self.count = int(t[0]) + self.total = t[1] + + @property + def median(self): + d = torch.tensor(list(self.deque)) + return d.median().item() + + @property + def avg(self): + d = torch.tensor(list(self.deque), dtype=torch.float32) + return d.mean().item() + + @property + def global_avg(self): + return self.total / self.count + + @property + def max(self): + return max(self.deque) + + @property + def value(self): + return self.deque[-1] + + def __str__(self): + return self.fmt.format( + median=self.median, + avg=self.avg, + global_avg=self.global_avg, + max=self.max, + value=self.value) + + +def reduce_dict(input_dict, average=True): + """ + Args: + input_dict (dict): all the values will be reduced + average (bool): whether to do average or sum + Reduce the values in the dictionary from all processes so that all processes + have the averaged results. Returns a dict with the same fields as + input_dict, after reduction. + """ + world_size = get_world_size() + if world_size < 2: + return input_dict + with torch.no_grad(): + names = [] + values = [] + # sort the keys so that they are consistent across processes + for k in sorted(input_dict.keys()): + names.append(k) + values.append(input_dict[k]) + values = torch.stack(values, dim=0) + dist.all_reduce(values) + if average: + values /= world_size + reduced_dict = {k: v for k, v in zip(names, values)} + return reduced_dict + + +class MetricLogger(object): + def __init__(self, delimiter="\t"): + self.meters = defaultdict(SmoothedValue) + self.delimiter = delimiter + + def update(self, **kwargs): + for k, v in kwargs.items(): + if isinstance(v, torch.Tensor): + v = v.item() + assert isinstance(v, (float, int)) + self.meters[k].update(v) + + def __getattr__(self, attr): + if attr in self.meters: + return self.meters[attr] + if attr in self.__dict__: + return self.__dict__[attr] + raise AttributeError("'{}' object has no attribute '{}'".format( + type(self).__name__, attr)) + + def __str__(self): + loss_str = [] + for name, meter in self.meters.items(): + loss_str.append( + "{}: {}".format(name, str(meter)) + ) + return self.delimiter.join(loss_str) + + def synchronize_between_processes(self): + for meter in self.meters.values(): + meter.synchronize_between_processes() + + def add_meter(self, name, meter): + self.meters[name] = meter + + def log_every(self, iterable, print_freq, header=None): + i = 0 + if not header: + header = '' + start_time = time.time() + end = time.time() + iter_time = SmoothedValue(fmt='{avg:.6f}') + data_time = SmoothedValue(fmt='{avg:.6f}') + space_fmt = ':' + str(len(str(len(iterable)))) + 'd' + if torch.cuda.is_available(): + log_msg = self.delimiter.join([ + header, + '[{0' + space_fmt + '}/{1}]', + 'eta: {eta}', + '{meters}', + 'time: {time}', + 'data: {data}', + 'max mem: {memory:.0f}' + ]) + else: + log_msg = self.delimiter.join([ + header, + '[{0' + space_fmt + '}/{1}]', + 'eta: {eta}', + '{meters}', + 'time: {time}', + 'data: {data}' + ]) + MB = 1024.0 * 1024.0 + for obj in iterable: + data_time.update(time.time() - end) + yield obj + iter_time.update(time.time() - end) + if i % print_freq == 0 or i == len(iterable) - 1: + eta_seconds = iter_time.global_avg * (len(iterable) - i) + eta_string = str(datetime.timedelta(seconds=int(eta_seconds))) + if torch.cuda.is_available(): + print(log_msg.format( + i, len(iterable), eta=eta_string, + meters=str(self), + time=str(iter_time), data=str(data_time), + memory=torch.cuda.max_memory_allocated() / MB)) + else: + print(log_msg.format( + i, len(iterable), eta=eta_string, + meters=str(self), + time=str(iter_time), data=str(data_time))) + i += 1 + end = time.time() + total_time = time.time() - start_time + total_time_str = str(datetime.timedelta(seconds=int(total_time))) + print('{} Total time: {} ({:.6f} s / it)'.format( + header, total_time_str, total_time / len(iterable))) + + +def get_sha(): + cwd = os.path.dirname(os.path.abspath(__file__)) + + def _run(command): + return subprocess.check_output(command, cwd=cwd).decode('ascii').strip() + sha = 'N/A' + diff = "clean" + branch = 'N/A' + try: + sha = _run(['git', 'rev-parse', 'HEAD']) + subprocess.check_output(['git', 'diff'], cwd=cwd) + diff = _run(['git', 'diff-index', 'HEAD']) + diff = "has uncommited changes" if diff else "clean" + branch = _run(['git', 'rev-parse', '--abbrev-ref', 'HEAD']) + except Exception: + pass + message = f"sha: {sha}, status: {diff}, branch: {branch}" + return message + + +def is_dist_avail_and_initialized(): + if not dist.is_available(): + return False + if not dist.is_initialized(): + return False + return True + + +def get_world_size(): + if not is_dist_avail_and_initialized(): + return 1 + return dist.get_world_size() + + +def get_rank(): + if not is_dist_avail_and_initialized(): + return 0 + return dist.get_rank() + + +def is_main_process(): + return get_rank() == 0 + + +def save_on_master(*args, **kwargs): + if is_main_process(): + torch.save(*args, **kwargs) + + +def setup_for_distributed(is_master): + """ + This function disables printing when not in master process + """ + import builtins as __builtin__ + builtin_print = __builtin__.print + + def print(*args, **kwargs): + force = kwargs.pop('force', False) + if is_master or force: + builtin_print(*args, **kwargs) + + __builtin__.print = print + + +def init_distributed_mode(args): + # launched with torch.distributed.launch + if 'RANK' in os.environ and 'WORLD_SIZE' in os.environ: + args.rank = int(os.environ["RANK"]) + args.world_size = int(os.environ['WORLD_SIZE']) + args.gpu = int(os.environ['LOCAL_RANK']) + # launched with submitit on a slurm cluster + elif 'SLURM_PROCID' in os.environ: + args.rank = int(os.environ['SLURM_PROCID']) + args.gpu = args.rank % torch.cuda.device_count() + # launched naively with `python main_dino.py` + # we manually add MASTER_ADDR and MASTER_PORT to env variables + elif torch.cuda.is_available(): + print('Will run the code on one GPU.') + args.rank, args.gpu, args.world_size = 0, 0, 1 + os.environ['MASTER_ADDR'] = '127.0.0.1' + os.environ['MASTER_PORT'] = '29500' + else: + print('Does not support training without GPU.') + sys.exit(1) + + dist.init_process_group( + backend="nccl", + init_method=args.dist_url, + world_size=args.world_size, + rank=args.rank, + ) + + torch.cuda.set_device(args.gpu) + print('| distributed init (rank {}): {}'.format( + args.rank, args.dist_url), flush=True) + dist.barrier() + setup_for_distributed(args.rank == 0) + + +def accuracy(output, target, topk=(1,)): + """Computes the accuracy over the k top predictions for the specified values of k""" + maxk = max(topk) + batch_size = target.size(0) + _, pred = output.topk(maxk, 1, True, True) + pred = pred.t() + correct = pred.eq(target.reshape(1, -1).expand_as(pred)) + return [correct[:k].reshape(-1).float().sum(0) * 100. / batch_size for k in topk] + + +def _no_grad_trunc_normal_(tensor, mean, std, a, b): + # Cut & paste from PyTorch official master until it's in a few official releases - RW + # Method based on https://people.sc.fsu.edu/~jburkardt/presentations/truncated_normal.pdf + def norm_cdf(x): + # Computes standard normal cumulative distribution function + return (1. + math.erf(x / math.sqrt(2.))) / 2. + + if (mean < a - 2 * std) or (mean > b + 2 * std): + warnings.warn("mean is more than 2 std from [a, b] in nn.init.trunc_normal_. " + "The distribution of values may be incorrect.", + stacklevel=2) + + with torch.no_grad(): + # Values are generated by using a truncated uniform distribution and + # then using the inverse CDF for the normal distribution. + # Get upper and lower cdf values + l = norm_cdf((a - mean) / std) + u = norm_cdf((b - mean) / std) + + # Uniformly fill tensor with values from [l, u], then translate to + # [2l-1, 2u-1]. + tensor.uniform_(2 * l - 1, 2 * u - 1) + + # Use inverse cdf transform for normal distribution to get truncated + # standard normal + tensor.erfinv_() + + # Transform to proper mean, std + tensor.mul_(std * math.sqrt(2.)) + tensor.add_(mean) + + # Clamp to ensure it's in the proper range + tensor.clamp_(min=a, max=b) + return tensor + + +def trunc_normal_(tensor, mean=0., std=1., a=-2., b=2.): + # type: (Tensor, float, float, float, float) -> Tensor + return _no_grad_trunc_normal_(tensor, mean, std, a, b) + + +class LARS(torch.optim.Optimizer): + """ + Almost copy-paste from https://github.com/facebookresearch/barlowtwins/blob/main/main.py + """ + def __init__(self, params, lr=0, weight_decay=0, momentum=0.9, eta=0.001, + weight_decay_filter=None, lars_adaptation_filter=None): + defaults = dict(lr=lr, weight_decay=weight_decay, momentum=momentum, + eta=eta, weight_decay_filter=weight_decay_filter, + lars_adaptation_filter=lars_adaptation_filter) + super().__init__(params, defaults) + + @torch.no_grad() + def step(self): + for g in self.param_groups: + for p in g['params']: + dp = p.grad + + if dp is None: + continue + + if p.ndim != 1: + dp = dp.add(p, alpha=g['weight_decay']) + + if p.ndim != 1: + param_norm = torch.norm(p) + update_norm = torch.norm(dp) + one = torch.ones_like(param_norm) + q = torch.where(param_norm > 0., + torch.where(update_norm > 0, + (g['eta'] * param_norm / update_norm), one), one) + dp = dp.mul(q) + + param_state = self.state[p] + if 'mu' not in param_state: + param_state['mu'] = torch.zeros_like(p) + mu = param_state['mu'] + mu.mul_(g['momentum']).add_(dp) + + p.add_(mu, alpha=-g['lr']) + + +class MultiCropWrapper(nn.Module): + """ + Perform forward pass separately on each resolution input. + The inputs corresponding to a single resolution are clubbed and single + forward is run on the same resolution inputs. Hence we do several + forward passes = number of different resolutions used. We then + concatenate all the output features and run the head forward on these + concatenated features. + """ + def __init__(self, backbone, head): + super(MultiCropWrapper, self).__init__() + # disable layers dedicated to ImageNet labels classification + backbone.fc, backbone.head = nn.Identity(), nn.Identity() + self.backbone = backbone + self.head = head + + def forward(self, x): + # convert to list + if not isinstance(x, list): + x = [x] + idx_crops = torch.cumsum(torch.unique_consecutive( + torch.tensor([inp.shape[-1] for inp in x]), + return_counts=True, + )[1], 0) + start_idx, output = 0, torch.empty(0).to(x[0].device) + for end_idx in idx_crops: + _out = self.backbone(torch.cat(x[start_idx: end_idx])) + # The output is a tuple with XCiT model. See: + # https://github.com/facebookresearch/xcit/blob/master/xcit.py#L404-L405 + if isinstance(_out, tuple): + _out = _out[0] + # accumulate outputs + output = torch.cat((output, _out)) + start_idx = end_idx + # Run the head forward on the concatenated features. + return self.head(output) + + +def get_params_groups(model): + regularized = [] + not_regularized = [] + for name, param in model.named_parameters(): + if not param.requires_grad: + continue + # we do not regularize biases nor Norm parameters + if name.endswith(".bias") or len(param.shape) == 1: + not_regularized.append(param) + else: + regularized.append(param) + return [{'params': regularized}, {'params': not_regularized, 'weight_decay': 0.}] + + +def has_batchnorms(model): + bn_types = (nn.BatchNorm1d, nn.BatchNorm2d, nn.BatchNorm3d, nn.SyncBatchNorm) + for name, module in model.named_modules(): + if isinstance(module, bn_types): + return True + return False + + +class PCA(): + """ + Class to compute and apply PCA. + """ + def __init__(self, dim=256, whit=0.5): + self.dim = dim + self.whit = whit + self.mean = None + + def train_pca(self, cov): + """ + Takes a covariance matrix (np.ndarray) as input. + """ + d, v = np.linalg.eigh(cov) + eps = d.max() * 1e-5 + n_0 = (d < eps).sum() + if n_0 > 0: + d[d < eps] = eps + + # total energy + totenergy = d.sum() + + # sort eigenvectors with eigenvalues order + idx = np.argsort(d)[::-1][:self.dim] + d = d[idx] + v = v[:, idx] + + print("keeping %.2f %% of the energy" % (d.sum() / totenergy * 100.0)) + + # for the whitening + d = np.diag(1. / d**self.whit) + + # principal components + self.dvt = np.dot(d, v.T) + + def apply(self, x): + # input is from numpy + if isinstance(x, np.ndarray): + if self.mean is not None: + x -= self.mean + return np.dot(self.dvt, x.T).T + + # input is from torch and is on GPU + if x.is_cuda: + if self.mean is not None: + x -= torch.cuda.FloatTensor(self.mean) + return torch.mm(torch.cuda.FloatTensor(self.dvt), x.transpose(0, 1)).transpose(0, 1) + + # input if from torch, on CPU + if self.mean is not None: + x -= torch.FloatTensor(self.mean) + return torch.mm(torch.FloatTensor(self.dvt), x.transpose(0, 1)).transpose(0, 1) + + +def compute_ap(ranks, nres): + """ + Computes average precision for given ranked indexes. + Arguments + --------- + ranks : zerro-based ranks of positive images + nres : number of positive images + Returns + ------- + ap : average precision + """ + + # number of images ranked by the system + nimgranks = len(ranks) + + # accumulate trapezoids in PR-plot + ap = 0 + + recall_step = 1. / nres + + for j in np.arange(nimgranks): + rank = ranks[j] + + if rank == 0: + precision_0 = 1. + else: + precision_0 = float(j) / rank + + precision_1 = float(j + 1) / (rank + 1) + + ap += (precision_0 + precision_1) * recall_step / 2. + + return ap + + +def compute_map(ranks, gnd, kappas=[]): + """ + Computes the mAP for a given set of returned results. + Usage: + map = compute_map (ranks, gnd) + computes mean average precsion (map) only + map, aps, pr, prs = compute_map (ranks, gnd, kappas) + computes mean average precision (map), average precision (aps) for each query + computes mean precision at kappas (pr), precision at kappas (prs) for each query + Notes: + 1) ranks starts from 0, ranks.shape = db_size X #queries + 2) The junk results (e.g., the query itself) should be declared in the gnd stuct array + 3) If there are no positive images for some query, that query is excluded from the evaluation + """ + + map = 0. + nq = len(gnd) # number of queries + aps = np.zeros(nq) + pr = np.zeros(len(kappas)) + prs = np.zeros((nq, len(kappas))) + nempty = 0 + + for i in np.arange(nq): + qgnd = np.array(gnd[i]['ok']) + + # no positive images, skip from the average + if qgnd.shape[0] == 0: + aps[i] = float('nan') + prs[i, :] = float('nan') + nempty += 1 + continue + + try: + qgndj = np.array(gnd[i]['junk']) + except: + qgndj = np.empty(0) + + # sorted positions of positive and junk images (0 based) + pos = np.arange(ranks.shape[0])[np.in1d(ranks[:,i], qgnd)] + junk = np.arange(ranks.shape[0])[np.in1d(ranks[:,i], qgndj)] + + k = 0; + ij = 0; + if len(junk): + # decrease positions of positives based on the number of + # junk images appearing before them + ip = 0 + while (ip < len(pos)): + while (ij < len(junk) and pos[ip] > junk[ij]): + k += 1 + ij += 1 + pos[ip] = pos[ip] - k + ip += 1 + + # compute ap + ap = compute_ap(pos, len(qgnd)) + map = map + ap + aps[i] = ap + + # compute precision @ k + pos += 1 # get it to 1-based + for j in np.arange(len(kappas)): + kq = min(max(pos), kappas[j]); + prs[i, j] = (pos <= kq).sum() / kq + pr = pr + prs[i, :] + + map = map / (nq - nempty) + pr = pr / (nq - nempty) + + return map, aps, pr, prs + + +def multi_scale(samples, model): + v = None + for s in [1, 1/2**(1/2), 1/2]: # we use 3 different scales + if s == 1: + inp = samples.clone() + else: + inp = nn.functional.interpolate(samples, scale_factor=s, mode='bilinear', align_corners=False) + feats = model(inp).clone() + if v is None: + v = feats + else: + v += feats + v /= 3 + v /= v.norm() + return v \ No newline at end of file diff --git a/utils/__pycache__/__init__.cpython-38.pyc b/utils/__pycache__/__init__.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..14c766e5c2c4345f123d0a1fce0c07f3032535fd Binary files /dev/null and b/utils/__pycache__/__init__.cpython-38.pyc differ diff --git a/utils/__pycache__/constants.cpython-38.pyc b/utils/__pycache__/constants.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..199635afde2a172abacced5e8569b4ac304ac65b Binary files /dev/null and b/utils/__pycache__/constants.cpython-38.pyc differ diff --git a/utils/__pycache__/factory.cpython-38.pyc b/utils/__pycache__/factory.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cd6118f79511563eb17063667e71d917139adb98 Binary files /dev/null and b/utils/__pycache__/factory.cpython-38.pyc differ diff --git a/utils/__pycache__/hook.cpython-38.pyc b/utils/__pycache__/hook.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..310c09d1a512b5b829ffeeb75c30dc6aef456e4f Binary files /dev/null and b/utils/__pycache__/hook.cpython-38.pyc differ diff --git a/utils/__pycache__/imagenet_segmentation.cpython-38.pyc b/utils/__pycache__/imagenet_segmentation.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dcc21490b35ad94ef25f0fa577984ba526b6ae5b Binary files /dev/null and b/utils/__pycache__/imagenet_segmentation.cpython-38.pyc differ diff --git a/utils/__pycache__/misc.cpython-38.pyc b/utils/__pycache__/misc.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6e2608749ddc130f2970b2f3bdf0017324015b58 Binary files /dev/null and b/utils/__pycache__/misc.cpython-38.pyc differ diff --git a/utils/__pycache__/model.cpython-38.pyc b/utils/__pycache__/model.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..265d9e52b6cf437b3c601ba925d21e5ab4c63b45 Binary files /dev/null and b/utils/__pycache__/model.cpython-38.pyc differ diff --git a/utils/__pycache__/modified_resnet.cpython-38.pyc b/utils/__pycache__/modified_resnet.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a2c4cf86e8d63c3d1afd2596265088cfa2f15525 Binary files /dev/null and b/utils/__pycache__/modified_resnet.cpython-38.pyc differ diff --git a/utils/__pycache__/openai_models.cpython-38.pyc b/utils/__pycache__/openai_models.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e607ab5a02fab293a0c6e4ed72cd659100173afc Binary files /dev/null and b/utils/__pycache__/openai_models.cpython-38.pyc differ diff --git a/utils/__pycache__/openai_templates.cpython-38.pyc b/utils/__pycache__/openai_templates.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..afab77d2ff5ad85f05100d47475738d827ca3f65 Binary files /dev/null and b/utils/__pycache__/openai_templates.cpython-38.pyc differ diff --git a/utils/__pycache__/pretrained.cpython-38.pyc b/utils/__pycache__/pretrained.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8a9c15bbdbd40c8e28b538b2f57da497953bf3e8 Binary files /dev/null and b/utils/__pycache__/pretrained.cpython-38.pyc differ diff --git a/utils/__pycache__/segmentation_utils.cpython-38.pyc b/utils/__pycache__/segmentation_utils.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..098e650b49159034a75bdaae7a9d4359d2d4487a Binary files /dev/null and b/utils/__pycache__/segmentation_utils.cpython-38.pyc differ diff --git a/utils/__pycache__/timm_model.cpython-38.pyc b/utils/__pycache__/timm_model.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f4fd8b5ace0d4bdebfb966de574a13fa11d03a27 Binary files /dev/null and b/utils/__pycache__/timm_model.cpython-38.pyc differ diff --git a/utils/__pycache__/tokenizer.cpython-38.pyc b/utils/__pycache__/tokenizer.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c477ef9f1b644d35246d5775355541d0aacc19a7 Binary files /dev/null and b/utils/__pycache__/tokenizer.cpython-38.pyc differ diff --git a/utils/__pycache__/transform.cpython-38.pyc b/utils/__pycache__/transform.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8459edc3cdbc81486b73220d65c4fc37a41d1783 Binary files /dev/null and b/utils/__pycache__/transform.cpython-38.pyc differ diff --git a/utils/__pycache__/transformer.cpython-38.pyc b/utils/__pycache__/transformer.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6bed340588a8ec30972adceb07f8092a8371b505 Binary files /dev/null and b/utils/__pycache__/transformer.cpython-38.pyc differ diff --git a/utils/__pycache__/visualization.cpython-38.pyc b/utils/__pycache__/visualization.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ae8536af5506120e0f36bc0fafde8f8d74bff354 Binary files /dev/null and b/utils/__pycache__/visualization.cpython-38.pyc differ diff --git a/utils/binary_waterbirds.py b/utils/binary_waterbirds.py new file mode 100644 index 0000000000000000000000000000000000000000..2d0a37e4fdcf79ec4260275dd97e45b1d9b183cc --- /dev/null +++ b/utils/binary_waterbirds.py @@ -0,0 +1,52 @@ +import os +import os.path +from typing import Any, Callable, cast, Dict, List, Optional, Tuple +from typing import Union + +from PIL import Image +import pandas as pd +from torchvision.datasets import VisionDataset +import torch + + +def pil_loader(path: str) -> Image.Image: + # open path as file to avoid ResourceWarning (https://github.com/python-pillow/Pillow/issues/835) + with open(path, "rb") as f: + img = Image.open(f) + return img.convert("RGB") + +class BinaryWaterbirds(VisionDataset): + def __init__( + self, + root: str, + split: str, + loader: Callable[[str], Any] = pil_loader, + transform: Optional[Callable] = None, + target_transform: Optional[Callable] = None, + ) -> None: + super().__init__(root, transform=transform, target_transform=target_transform) + + self.loader = loader + csv = pd.read_csv(os.path.join(root, 'metadata.csv')) + split = {'test': 2, 'valid': 1, 'train': 0}[split] + csv = csv[csv['split'] == split] + self.samples = [(os.path.join(root, csv.iloc[i]['img_filename']), csv.iloc[i]['y']) for i in range(len(csv))] + + def __getitem__(self, index: int) -> Tuple[Any, Any]: + """ + Args: + index (int): Index + Returns: + tuple: (sample, target) where target is class_index of the target class. + """ + path, target = self.samples[index] + sample = self.loader(path) + if self.transform is not None: + sample = self.transform(sample) + if self.target_transform is not None: + target = self.target_transform(target) + + return sample, target + + def __len__(self) -> int: + return len(self.samples) diff --git a/utils/constants.py b/utils/constants.py new file mode 100644 index 0000000000000000000000000000000000000000..bdd90dc5ff9139d62345aabf611b1f4861b66de5 --- /dev/null +++ b/utils/constants.py @@ -0,0 +1,2 @@ +OPENAI_DATASET_MEAN = (0.48145466, 0.4578275, 0.40821073) +OPENAI_DATASET_STD = (0.26862954, 0.26130258, 0.27577711) \ No newline at end of file diff --git a/utils/cub_classes.py b/utils/cub_classes.py new file mode 100644 index 0000000000000000000000000000000000000000..b27ebcd4ae0af5152411933797499dc092adaace --- /dev/null +++ b/utils/cub_classes.py @@ -0,0 +1,2 @@ +cub_classes = ['Black footed Albatross', 'Laysan Albatross', 'Sooty Albatross', 'Groove billed Ani', 'Crested Auklet', 'Least Auklet', 'Parakeet Auklet', 'Rhinoceros Auklet', 'Brewer Blackbird', 'Red winged Blackbird', 'Rusty Blackbird', 'Yellow headed Blackbird', 'Bobolink', 'Indigo Bunting', 'Lazuli Bunting', 'Painted Bunting', 'Cardinal', 'Spotted Catbird', 'Gray Catbird', 'Yellow breasted Chat', 'Eastern Towhee', 'Chuck will Widow', 'Brandt Cormorant', 'Red faced Cormorant', 'Pelagic Cormorant', 'Bronzed Cowbird', 'Shiny Cowbird', 'Brown Creeper', 'American Crow', 'Fish Crow', 'Black billed Cuckoo', 'Mangrove Cuckoo', 'Yellow billed Cuckoo', 'Gray crowned Rosy Finch', 'Purple Finch', 'Northern Flicker', 'Acadian Flycatcher', 'Great Crested Flycatcher', 'Least Flycatcher', 'Olive sided Flycatcher', 'Scissor tailed Flycatcher', 'Vermilion Flycatcher', 'Yellow bellied Flycatcher', 'Frigatebird', 'Northern Fulmar', 'Gadwall', 'American Goldfinch', 'European Goldfinch', 'Boat tailed Grackle', 'Eared Grebe', 'Horned Grebe', 'Pied billed Grebe', 'Western Grebe', 'Blue Grosbeak', 'Evening Grosbeak', 'Pine Grosbeak', 'Rose breasted Grosbeak', 'Pigeon Guillemot', 'California Gull', 'Glaucous winged Gull', 'Heermann Gull', 'Herring Gull', 'Ivory Gull', 'Ring billed Gull', 'Slaty backed Gull', 'Western Gull', 'Anna Hummingbird', 'Ruby throated Hummingbird', 'Rufous Hummingbird', 'Green Violetear', 'Long tailed Jaeger', 'Pomarine Jaeger', 'Blue Jay', 'Florida Jay', 'Green Jay', 'Dark eyed Junco', 'Tropical Kingbird', 'Gray Kingbird', 'Belted Kingfisher', 'Green Kingfisher', 'Pied Kingfisher', 'Ringed Kingfisher', 'White breasted Kingfisher', 'Red legged Kittiwake', 'Horned Lark', 'Pacific Loon', 'Mallard', 'Western Meadowlark', 'Hooded Merganser', 'Red breasted Merganser', 'Mockingbird', 'Nighthawk', 'Clark Nutcracker', 'White breasted Nuthatch', 'Baltimore Oriole', 'Hooded Oriole', 'Orchard Oriole', 'Scott Oriole', 'Ovenbird', 'Brown Pelican', 'White Pelican', 'Western Wood Pewee', 'Sayornis', 'American Pipit', 'Whip poor Will', 'Horned Puffin', 'Common Raven', 'White necked Raven', 'American Redstart', 'Geococcyx', 'Loggerhead Shrike', 'Great Grey Shrike', 'Baird Sparrow', 'Black throated Sparrow', 'Brewer Sparrow', 'Chipping Sparrow', 'Clay colored Sparrow', 'House Sparrow', 'Field Sparrow', 'Fox Sparrow', 'Grasshopper Sparrow', 'Harris Sparrow', 'Henslow Sparrow', 'Le Conte Sparrow', 'Lincoln Sparrow', 'Nelson Sharp tailed Sparrow', 'Savannah Sparrow', 'Seaside Sparrow', 'Song Sparrow', 'Tree Sparrow', 'Vesper Sparrow', 'White crowned Sparrow', 'White throated Sparrow', 'Cape Glossy Starling', 'Bank Swallow', 'Barn Swallow', 'Cliff Swallow', 'Tree Swallow', 'Scarlet Tanager', 'Summer Tanager', 'Artic Tern', 'Black Tern', 'Caspian Tern', 'Common Tern', 'Elegant Tern', 'Forsters Tern', 'Least Tern', 'Green tailed Towhee', 'Brown Thrasher', 'Sage Thrasher', 'Black capped Vireo', 'Blue headed Vireo', 'Philadelphia Vireo', 'Red eyed Vireo', 'Warbling Vireo', 'White eyed Vireo', 'Yellow throated Vireo', 'Bay breasted Warbler', 'Black and white Warbler', 'Black throated Blue Warbler', 'Blue winged Warbler', 'Canada Warbler', 'Cape May Warbler', 'Cerulean Warbler', 'Chestnut sided Warbler', 'Golden winged Warbler', 'Hooded Warbler', 'Kentucky Warbler', 'Magnolia Warbler', 'Mourning Warbler', 'Myrtle Warbler', 'Nashville Warbler', 'Orange crowned Warbler', 'Palm Warbler', 'Pine Warbler', 'Prairie Warbler', 'Prothonotary Warbler', 'Swainson Warbler', 'Tennessee Warbler', 'Wilson Warbler', 'Worm eating Warbler', 'Yellow Warbler', 'Northern Waterthrush', 'Louisiana Waterthrush', 'Bohemian Waxwing', 'Cedar Waxwing', 'American Three toed Woodpecker', 'Pileated Woodpecker', 'Red bellied Woodpecker', 'Red cockaded Woodpecker', 'Red headed Woodpecker', 'Downy Woodpecker', 'Bewick Wren', 'Cactus Wren', 'Carolina Wren', 'House Wren', 'Marsh Wren', 'Rock Wren', 'Winter Wren', 'Common Yellowthroat'] +waterbird_classes = ['landbird', 'waterbird'] \ No newline at end of file diff --git a/utils/factory.py b/utils/factory.py new file mode 100644 index 0000000000000000000000000000000000000000..bdd90c1c12c0d901173806eef1dc4346d9a6f7a9 --- /dev/null +++ b/utils/factory.py @@ -0,0 +1,382 @@ +import json +import logging +import os +import pathlib +import re +from copy import deepcopy +from pathlib import Path +from typing import Any, Dict, Optional, Tuple, Union + +import torch + +from utils.constants import OPENAI_DATASET_MEAN, OPENAI_DATASET_STD +from utils.model import CLIP, convert_to_custom_text_state_dict,\ + resize_pos_embed, get_cast_dtype +from utils.openai_models import load_openai_model +from utils.pretrained import is_pretrained_cfg, get_pretrained_cfg, download_pretrained,\ + list_pretrained_tags_by_model, download_pretrained_from_hf +from utils.transform import image_transform, AugmentationCfg +from utils.tokenizer import HFTokenizer, tokenize + + +HF_HUB_PREFIX = 'hf-hub:' +_MODEL_CONFIG_PATHS = [Path(__file__).parent / f"model_configs/"] +_MODEL_CONFIGS = {} # directory (model_name: config) of model architecture configs + + +def _natural_key(string_): + return [int(s) if s.isdigit() else s for s in re.split(r'(\d+)', string_.lower())] + + +def _rescan_model_configs(): + global _MODEL_CONFIGS + + config_ext = ('.json',) + config_files = [] + for config_path in _MODEL_CONFIG_PATHS: + if config_path.is_file() and config_path.suffix in config_ext: + config_files.append(config_path) + elif config_path.is_dir(): + for ext in config_ext: + config_files.extend(config_path.glob(f'*{ext}')) + + for cf in config_files: + with open(cf, 'r') as f: + model_cfg = json.load(f) + if all(a in model_cfg for a in ('embed_dim', 'vision_cfg', 'text_cfg')): + _MODEL_CONFIGS[cf.stem] = model_cfg + + _MODEL_CONFIGS = {k: v for k, v in sorted(_MODEL_CONFIGS.items(), key=lambda x: _natural_key(x[0]))} + + +_rescan_model_configs() # initial populate of model config registry + + +def list_models(): + """ enumerate available model architectures based on config files """ + return list(_MODEL_CONFIGS.keys()) + + +def add_model_config(path): + """ add model config path or file and update registry """ + if not isinstance(path, Path): + path = Path(path) + _MODEL_CONFIG_PATHS.append(path) + _rescan_model_configs() + + +def get_model_config(model_name): + if model_name in _MODEL_CONFIGS: + return deepcopy(_MODEL_CONFIGS[model_name]) + else: + return None + + +def get_tokenizer(model_name): + if model_name.startswith(HF_HUB_PREFIX): + tokenizer = HFTokenizer(model_name[len(HF_HUB_PREFIX):]) + else: + config = get_model_config(model_name) + tokenizer = HFTokenizer( + config['text_cfg']['hf_tokenizer_name']) if 'hf_tokenizer_name' in config['text_cfg'] else tokenize + return tokenizer + + +def load_state_dict(checkpoint_path: str, map_location='cpu'): + checkpoint = torch.load(checkpoint_path, map_location=map_location) + if isinstance(checkpoint, dict) and 'state_dict' in checkpoint: + state_dict = checkpoint['state_dict'] + else: + state_dict = checkpoint + if next(iter(state_dict.items()))[0].startswith('module'): + state_dict = {k[7:]: v for k, v in state_dict.items()} + return state_dict + + +def load_checkpoint(model, checkpoint_path, strict=True): + state_dict = load_state_dict(checkpoint_path) + # detect old format and make compatible with new format + if 'positional_embedding' in state_dict and not hasattr(model, 'positional_embedding'): + state_dict = convert_to_custom_text_state_dict(state_dict) + resize_pos_embed(state_dict, model) + incompatible_keys = model.load_state_dict(state_dict, strict=strict) + return incompatible_keys + + +def create_model( + model_name: str, + pretrained: Optional[str] = None, + precision: str = 'fp32', + device: Union[str, torch.device] = 'cpu', + jit: bool = False, + force_quick_gelu: bool = False, + force_custom_text: bool = False, + force_patch_dropout: Optional[float] = None, + force_image_size: Optional[Union[int, Tuple[int, int]]] = None, + pretrained_image: bool = False, + pretrained_hf: bool = True, + cache_dir: Optional[str] = None, + output_dict: Optional[bool] = None, + require_pretrained: bool = False, +): + has_hf_hub_prefix = model_name.startswith(HF_HUB_PREFIX) + if has_hf_hub_prefix: + model_id = model_name[len(HF_HUB_PREFIX):] + checkpoint_path = download_pretrained_from_hf(model_id, cache_dir=cache_dir) + config_path = download_pretrained_from_hf(model_id, filename='open_clip_config.json', cache_dir=cache_dir) + + with open(config_path, 'r', encoding='utf-8') as f: + config = json.load(f) + pretrained_cfg = config['preprocess_cfg'] + model_cfg = config['model_cfg'] + else: + model_name = model_name.replace('/', '-') # for callers using old naming with / in ViT names + checkpoint_path = None + pretrained_cfg = {} + model_cfg = None + + if isinstance(device, str): + device = torch.device(device) + + if pretrained and pretrained.lower() == 'openai': + logging.info(f'Loading pretrained {model_name} from OpenAI.') + model = load_openai_model( + model_name, + precision=precision, + device=device, + cache_dir=cache_dir, + ) + else: + model_cfg = model_cfg or get_model_config(model_name) + if model_cfg is not None: + logging.info(f'Loaded {model_name} model config.') + else: + logging.error(f'Model config for {model_name} not found; available models {list_models()}.') + raise RuntimeError(f'Model config for {model_name} not found.') + + if force_quick_gelu: + # override for use of QuickGELU on non-OpenAI transformer models + model_cfg["quick_gelu"] = True + + if force_patch_dropout is not None: + # override the default patch dropout value + model_cfg["vision_cfg"]["patch_dropout"] = force_patch_dropout + + if force_image_size is not None: + # override model config's image size + model_cfg["vision_cfg"]["image_size"] = force_image_size + + is_timm_model = 'timm_model_name' in model_cfg.get('vision_cfg', {}) + if pretrained_image: + if is_timm_model: + # pretrained weight loading for timm models set via vision_cfg + model_cfg['vision_cfg']['timm_model_pretrained'] = True + else: + assert False, 'pretrained image towers currently only supported for timm models' + + # cast_dtype set for fp16 and bf16 (manual mixed-precision), not set for 'amp' or 'pure' modes + cast_dtype = get_cast_dtype(precision) + is_hf_model = 'hf_model_name' in model_cfg.get('text_cfg', {}) + custom_text = model_cfg.pop('custom_text', False) or force_custom_text or is_hf_model + + if custom_text: + if is_hf_model: + model_cfg['text_cfg']['hf_model_pretrained'] = pretrained_hf + if "coca" in model_name: + raise ValueError('Coca is not implemented') + model = CoCa(**model_cfg, cast_dtype=cast_dtype) + else: + raise ValueError('CustomTextCLIP is not implemented') + model = CustomTextCLIP(**model_cfg, cast_dtype=cast_dtype) + else: + model = CLIP(**model_cfg, cast_dtype=cast_dtype) + + if precision in ("fp16", "bf16"): + dtype = torch.float16 if 'fp16' in precision else torch.bfloat16 + # manual mixed precision that matches original OpenAI behaviour + if is_timm_model: + # FIXME this is a bit janky, create timm based model in low-precision and + # then cast only LayerNormFp32 instances back to float32 so they don't break. + # Why? The convert_weights_to_lp fn only works with native models. + model.to(device=device, dtype=dtype) + from transformer import LayerNormFp32 + def _convert_ln(m): + if isinstance(m, LayerNormFp32): + m.weight.data = m.weight.data.to(torch.float32) + m.bias.data = m.bias.data.to(torch.float32) + model.apply(_convert_ln) + else: + model.to(device=device) + convert_weights_to_lp(model, dtype=dtype) + elif precision in ("pure_fp16", "pure_bf16"): + dtype = torch.float16 if 'fp16' in precision else torch.bfloat16 + model.to(device=device, dtype=dtype) + else: + model.to(device=device) + + pretrained_loaded = False + if pretrained: + checkpoint_path = '' + pretrained_cfg = get_pretrained_cfg(model_name, pretrained) + if pretrained_cfg: + checkpoint_path = download_pretrained(pretrained_cfg, cache_dir=cache_dir) + elif os.path.exists(pretrained): + checkpoint_path = pretrained + + if checkpoint_path: + logging.info(f'Loading pretrained {model_name} weights ({pretrained}).') + load_checkpoint(model, checkpoint_path) + else: + error_str = ( + f'Pretrained weights ({pretrained}) not found for model {model_name}.' + f'Available pretrained tags ({list_pretrained_tags_by_model(model_name)}.') + logging.warning(error_str) + raise RuntimeError(error_str) + pretrained_loaded = True + elif has_hf_hub_prefix: + logging.info(f'Loading pretrained {model_name} weights ({pretrained}).') + load_checkpoint(model, checkpoint_path) + pretrained_loaded = True + + if require_pretrained and not pretrained_loaded: + # callers of create_model_from_pretrained always expect pretrained weights + raise RuntimeError( + f'Pretrained weights were required for (model: {model_name}, pretrained: {pretrained}) but not loaded.') + + # set image / mean metadata from pretrained_cfg if available, or use default + model.visual.image_mean = pretrained_cfg.get('mean', None) or OPENAI_DATASET_MEAN + model.visual.image_std = pretrained_cfg.get('std', None) or OPENAI_DATASET_STD + + if output_dict and hasattr(model, "output_dict"): + model.output_dict = True + + if jit: + model = torch.jit.script(model) + + return model + + +def create_loss(args): + if args.distill: + return DistillClipLoss( + local_loss=args.local_loss, + gather_with_grad=args.gather_with_grad, + cache_labels=True, + rank=args.rank, + world_size=args.world_size, + use_horovod=args.horovod, + ) + elif "coca" in args.model.lower(): + return CoCaLoss( + caption_loss_weight=args.coca_caption_loss_weight, + clip_loss_weight=args.coca_contrastive_loss_weight, + local_loss=args.local_loss, + gather_with_grad=args.gather_with_grad, + cache_labels=True, + rank=args.rank, + world_size=args.world_size, + use_horovod=args.horovod, + ) + return ClipLoss( + local_loss=args.local_loss, + gather_with_grad=args.gather_with_grad, + cache_labels=True, + rank=args.rank, + world_size=args.world_size, + use_horovod=args.horovod, + ) + + +def create_model_and_transforms( + model_name: str, + pretrained: Optional[str] = None, + precision: str = 'fp32', + device: Union[str, torch.device] = 'cpu', + jit: bool = False, + force_quick_gelu: bool = False, + force_custom_text: bool = False, + force_patch_dropout: Optional[float] = None, + force_image_size: Optional[Union[int, Tuple[int, int]]] = None, + pretrained_image: bool = False, + pretrained_hf: bool = True, + image_mean: Optional[Tuple[float, ...]] = None, + image_std: Optional[Tuple[float, ...]] = None, + aug_cfg: Optional[Union[Dict[str, Any], AugmentationCfg]] = None, + cache_dir: Optional[str] = None, + output_dict: Optional[bool] = None, +): + model = create_model( + model_name, + pretrained, + precision=precision, + device=device, + jit=jit, + force_quick_gelu=force_quick_gelu, + force_custom_text=force_custom_text, + force_patch_dropout=force_patch_dropout, + force_image_size=force_image_size, + pretrained_image=pretrained_image, + pretrained_hf=pretrained_hf, + cache_dir=cache_dir, + output_dict=output_dict, + ) + + image_mean = image_mean or getattr(model.visual, 'image_mean', None) + image_std = image_std or getattr(model.visual, 'image_std', None) + preprocess_train = image_transform( + model.visual.image_size, + is_train=True, + mean=image_mean, + std=image_std, + aug_cfg=aug_cfg, + ) + preprocess_val = image_transform( + model.visual.image_size, + is_train=False, + mean=image_mean, + std=image_std, + ) + + return model, preprocess_train, preprocess_val + + +def create_model_from_pretrained( + model_name: str, + pretrained: Optional[str] = None, + precision: str = 'fp32', + device: Union[str, torch.device] = 'cpu', + jit: bool = False, + force_quick_gelu: bool = False, + force_custom_text: bool = False, + force_image_size: Optional[Union[int, Tuple[int, int]]] = None, + return_transform: bool = True, + image_mean: Optional[Tuple[float, ...]] = None, + image_std: Optional[Tuple[float, ...]] = None, + cache_dir: Optional[str] = None, +): + model = create_model( + model_name, + pretrained, + precision=precision, + device=device, + jit=jit, + force_quick_gelu=force_quick_gelu, + force_custom_text=force_custom_text, + force_image_size=force_image_size, + cache_dir=cache_dir, + require_pretrained=True, + ) + + if not return_transform: + return model + + image_mean = image_mean or getattr(model.visual, 'image_mean', None) + image_std = image_std or getattr(model.visual, 'image_std', None) + preprocess = image_transform( + model.visual.image_size, + is_train=False, + mean=image_mean, + std=image_std, + ) + + return model, preprocess \ No newline at end of file diff --git a/utils/hook.py b/utils/hook.py new file mode 100644 index 0000000000000000000000000000000000000000..7901d2a1a7c58a41f3ef97ac4983e41084cf4841 --- /dev/null +++ b/utils/hook.py @@ -0,0 +1,87 @@ +from typing import Dict, Text, Callable, List +from collections import defaultdict + + +class HookManager(object): + def __init__(self, hook_dict: Dict[Text, List[Callable]] = None): + self.hook_dict = hook_dict or defaultdict(list) + self.called = defaultdict(int) + self.forks = dict() + + def register(self, name: Text, func: Callable): + assert name + found_successor = False + for header, d in self.forks.items(): + if name.startswith(header.split('.')[0]+'.'): + next_ = name[len(header.split('.')[0]+'.'):].split('.')[0] + prev_ = header.split('.')[0] + if next_.isnumeric() and prev_ + '.' + next_ == header: + d.register(name[len(header)+1:], func) + elif next_ == '*': + d.register(name[len(prev_ + '.*')+1:], func) + else: + d.register(name[len(header)+1:], func) + found_successor = True + if not found_successor: + self.hook_dict[name].append(func) + + def unregister(self, name: Text, func: Callable): + assert name + found_successor = False + for header, d in self.forks.items(): + if name.startswith(header.split('.')[0]+'.'): + next_ = name[len(header.split('.')[0]+'.'):].split('.')[0] + prev_ = header.split('.')[0] + if next_.isnumeric() and prev_ + '.' + next_ == header: + d.register(name[len(header)+1:], func) + elif next_ == '*': + d.register(name[len(prev_ + '.*')+1:], func) + else: + d.register(name[len(header)+1:], func) + found_successor = True + if not found_successor and func in self.hook_dict[name]: + self.hook_dict[name].remove(func) + + def __call__(self, name: Text, **kwargs): + if name in self.hook_dict: + self.called[name] += 1 + for function in self.hook_dict[name]: + ret = function(**kwargs) + if len(self.hook_dict[name]) > 1: + last = self.hook_dict[name][-1] + # print(f'The last returned value comes from func {last}') + return ret + else: + return kwargs['ret'] + + def fork(self, name): + if name in self.forks: + raise ValueError(f'Forking with the same name is not allowed. Already forked with {name}.') + filtered_hooks = [(k[len(name)+1:], v) for k, v in self.hook_dict.items() if k.startswith(name+'.')] + filtered_hooks_d = defaultdict(list) + for i, j in filtered_hooks: + if isinstance(j, list): + filtered_hooks_d[i].extend(j) + else: + filtered_hooks_d[i].append(j) + new_hook = HookManager(filtered_hooks_d) + self.forks[name] = new_hook + return new_hook + + def fork_iterative(self, name, iteration): + filtered_hooks = [(k[len(name+'.'+str(iteration))+1:], v) for k, v in self.hook_dict.items() if k.startswith(name+'.'+str(iteration)+'.')] + filtered_hooks += [(k[len(name+'.*')+1:], v) for k, v in self.hook_dict.items() if k.startswith(name+'.*.')] + filtered_hooks_d = defaultdict(list) + for i, j in filtered_hooks: + if isinstance(j, list): + filtered_hooks_d[i].extend(j) + else: + filtered_hooks_d[i].append(j) + new_hook = HookManager(filtered_hooks_d) + self.forks[name+'.'+str(iteration)] = new_hook + return new_hook + + def finalize(self): + for name in self.hook_dict.keys(): + if self.called[name] == 0: + raise ValueError(f'Hook {name} was registered but never used!') \ No newline at end of file diff --git a/utils/imagenet_classes.py b/utils/imagenet_classes.py new file mode 100644 index 0000000000000000000000000000000000000000..1d34f838cd365ba63e55396e878d470f49b0478d --- /dev/null +++ b/utils/imagenet_classes.py @@ -0,0 +1 @@ +imagenet_classes = ["tench", "goldfish", "great white shark", "tiger shark", "hammerhead shark", "electric ray", "stingray", "rooster", "hen", "ostrich", "brambling", "goldfinch", "house finch", "junco", "indigo bunting", "American robin", "bulbul", "jay", "magpie", "chickadee", "American dipper", "kite (bird of prey)", "bald eagle", "vulture", "great grey owl", "fire salamander", "smooth newt", "newt", "spotted salamander", "axolotl", "American bullfrog", "tree frog", "tailed frog", "loggerhead sea turtle", "leatherback sea turtle", "mud turtle", "terrapin", "box turtle", "banded gecko", "green iguana", "Carolina anole", "desert grassland whiptail lizard", "agama", "frilled-necked lizard", "alligator lizard", "Gila monster", "European green lizard", "chameleon", "Komodo dragon", "Nile crocodile", "American alligator", "triceratops", "worm snake", "ring-necked snake", "eastern hog-nosed snake", "smooth green snake", "kingsnake", "garter snake", "water snake", "vine snake", "night snake", "boa constrictor", "African rock python", "Indian cobra", "green mamba", "sea snake", "Saharan horned viper", "eastern diamondback rattlesnake", "sidewinder rattlesnake", "trilobite", "harvestman", "scorpion", "yellow garden spider", "barn spider", "European garden spider", "southern black widow", "tarantula", "wolf spider", "tick", "centipede", "black grouse", "ptarmigan", "ruffed grouse", "prairie grouse", "peafowl", "quail", "partridge", "african grey parrot", "macaw", "sulphur-crested cockatoo", "lorikeet", "coucal", "bee eater", "hornbill", "hummingbird", "jacamar", "toucan", "duck", "red-breasted merganser", "goose", "black swan", "tusker", "echidna", "platypus", "wallaby", "koala", "wombat", "jellyfish", "sea anemone", "brain coral", "flatworm", "nematode", "conch", "snail", "slug", "sea slug", "chiton", "chambered nautilus", "Dungeness crab", "rock crab", "fiddler crab", "red king crab", "American lobster", "spiny lobster", "crayfish", "hermit crab", "isopod", "white stork", "black stork", "spoonbill", "flamingo", "little blue heron", "great egret", "bittern bird", "crane bird", "limpkin", "common gallinule", "American coot", "bustard", "ruddy turnstone", "dunlin", "common redshank", "dowitcher", "oystercatcher", "pelican", "king penguin", "albatross", "grey whale", "killer whale", "dugong", "sea lion", "Chihuahua", "Japanese Chin", "Maltese", "Pekingese", "Shih Tzu", "King Charles Spaniel", "Papillon", "toy terrier", "Rhodesian Ridgeback", "Afghan Hound", "Basset Hound", "Beagle", "Bloodhound", "Bluetick Coonhound", "Black and Tan Coonhound", "Treeing Walker Coonhound", "English foxhound", "Redbone Coonhound", "borzoi", "Irish Wolfhound", "Italian Greyhound", "Whippet", "Ibizan Hound", "Norwegian Elkhound", "Otterhound", "Saluki", "Scottish Deerhound", "Weimaraner", "Staffordshire Bull Terrier", "American Staffordshire Terrier", "Bedlington Terrier", "Border Terrier", "Kerry Blue Terrier", "Irish Terrier", "Norfolk Terrier", "Norwich Terrier", "Yorkshire Terrier", "Wire Fox Terrier", "Lakeland Terrier", "Sealyham Terrier", "Airedale Terrier", "Cairn Terrier", "Australian Terrier", "Dandie Dinmont Terrier", "Boston Terrier", "Miniature Schnauzer", "Giant Schnauzer", "Standard Schnauzer", "Scottish Terrier", "Tibetan Terrier", "Australian Silky Terrier", "Soft-coated Wheaten Terrier", "West Highland White Terrier", "Lhasa Apso", "Flat-Coated Retriever", "Curly-coated Retriever", "Golden Retriever", "Labrador Retriever", "Chesapeake Bay Retriever", "German Shorthaired Pointer", "Vizsla", "English Setter", "Irish Setter", "Gordon Setter", "Brittany dog", "Clumber Spaniel", "English Springer Spaniel", "Welsh Springer Spaniel", "Cocker Spaniel", "Sussex Spaniel", "Irish Water Spaniel", "Kuvasz", "Schipperke", "Groenendael dog", "Malinois", "Briard", "Australian Kelpie", "Komondor", "Old English Sheepdog", "Shetland Sheepdog", "collie", "Border Collie", "Bouvier des Flandres dog", "Rottweiler", "German Shepherd Dog", "Dobermann", "Miniature Pinscher", "Greater Swiss Mountain Dog", "Bernese Mountain Dog", "Appenzeller Sennenhund", "Entlebucher Sennenhund", "Boxer", "Bullmastiff", "Tibetan Mastiff", "French Bulldog", "Great Dane", "St. Bernard", "husky", "Alaskan Malamute", "Siberian Husky", "Dalmatian", "Affenpinscher", "Basenji", "pug", "Leonberger", "Newfoundland dog", "Great Pyrenees dog", "Samoyed", "Pomeranian", "Chow Chow", "Keeshond", "brussels griffon", "Pembroke Welsh Corgi", "Cardigan Welsh Corgi", "Toy Poodle", "Miniature Poodle", "Standard Poodle", "Mexican hairless dog (xoloitzcuintli)", "grey wolf", "Alaskan tundra wolf", "red wolf or maned wolf", "coyote", "dingo", "dhole", "African wild dog", "hyena", "red fox", "kit fox", "Arctic fox", "grey fox", "tabby cat", "tiger cat", "Persian cat", "Siamese cat", "Egyptian Mau", "cougar", "lynx", "leopard", "snow leopard", "jaguar", "lion", "tiger", "cheetah", "brown bear", "American black bear", "polar bear", "sloth bear", "mongoose", "meerkat", "tiger beetle", "ladybug", "ground beetle", "longhorn beetle", "leaf beetle", "dung beetle", "rhinoceros beetle", "weevil", "fly", "bee", "ant", "grasshopper", "cricket insect", "stick insect", "cockroach", "praying mantis", "cicada", "leafhopper", "lacewing", "dragonfly", "damselfly", "red admiral butterfly", "ringlet butterfly", "monarch butterfly", "small white butterfly", "sulphur butterfly", "gossamer-winged butterfly", "starfish", "sea urchin", "sea cucumber", "cottontail rabbit", "hare", "Angora rabbit", "hamster", "porcupine", "fox squirrel", "marmot", "beaver", "guinea pig", "common sorrel horse", "zebra", "pig", "wild boar", "warthog", "hippopotamus", "ox", "water buffalo", "bison", "ram (adult male sheep)", "bighorn sheep", "Alpine ibex", "hartebeest", "impala (antelope)", "gazelle", "arabian camel", "llama", "weasel", "mink", "European polecat", "black-footed ferret", "otter", "skunk", "badger", "armadillo", "three-toed sloth", "orangutan", "gorilla", "chimpanzee", "gibbon", "siamang", "guenon", "patas monkey", "baboon", "macaque", "langur", "black-and-white colobus", "proboscis monkey", "marmoset", "white-headed capuchin", "howler monkey", "titi monkey", "Geoffroy's spider monkey", "common squirrel monkey", "ring-tailed lemur", "indri", "Asian elephant", "African bush elephant", "red panda", "giant panda", "snoek fish", "eel", "silver salmon", "rock beauty fish", "clownfish", "sturgeon", "gar fish", "lionfish", "pufferfish", "abacus", "abaya", "academic gown", "accordion", "acoustic guitar", "aircraft carrier", "airliner", "airship", "altar", "ambulance", "amphibious vehicle", "analog clock", "apiary", "apron", "trash can", "assault rifle", "backpack", "bakery", "balance beam", "balloon", "ballpoint pen", "Band-Aid", "banjo", "baluster / handrail", "barbell", "barber chair", "barbershop", "barn", "barometer", "barrel", "wheelbarrow", "baseball", "basketball", "bassinet", "bassoon", "swimming cap", "bath towel", "bathtub", "station wagon", "lighthouse", "beaker", "military hat (bearskin or shako)", "beer bottle", "beer glass", "bell tower", "baby bib", "tandem bicycle", "bikini", "ring binder", "binoculars", "birdhouse", "boathouse", "bobsleigh", "bolo tie", "poke bonnet", "bookcase", "bookstore", "bottle cap", "hunting bow", "bow tie", "brass memorial plaque", "bra", "breakwater", "breastplate", "broom", "bucket", "buckle", "bulletproof vest", "high-speed train", "butcher shop", "taxicab", "cauldron", "candle", "cannon", "canoe", "can opener", "cardigan", "car mirror", "carousel", "tool kit", "cardboard box / carton", "car wheel", "automated teller machine", "cassette", "cassette player", "castle", "catamaran", "CD player", "cello", "mobile phone", "chain", "chain-link fence", "chain mail", "chainsaw", "storage chest", "chiffonier", "bell or wind chime", "china cabinet", "Christmas stocking", "church", "movie theater", "cleaver", "cliff dwelling", "cloak", "clogs", "cocktail shaker", "coffee mug", "coffeemaker", "spiral or coil", "combination lock", "computer keyboard", "candy store", "container ship", "convertible", "corkscrew", "cornet", "cowboy boot", "cowboy hat", "cradle", "construction crane", "crash helmet", "crate", "infant bed", "Crock Pot", "croquet ball", "crutch", "cuirass", "dam", "desk", "desktop computer", "rotary dial telephone", "diaper", "digital clock", "digital watch", "dining table", "dishcloth", "dishwasher", "disc brake", "dock", "dog sled", "dome", "doormat", "drilling rig", "drum", "drumstick", "dumbbell", "Dutch oven", "electric fan", "electric guitar", "electric locomotive", "entertainment center", "envelope", "espresso machine", "face powder", "feather boa", "filing cabinet", "fireboat", "fire truck", "fire screen", "flagpole", "flute", "folding chair", "football helmet", "forklift", "fountain", "fountain pen", "four-poster bed", "freight car", "French horn", "frying pan", "fur coat", "garbage truck", "gas mask or respirator", "gas pump", "goblet", "go-kart", "golf ball", "golf cart", "gondola", "gong", "gown", "grand piano", "greenhouse", "radiator grille", "grocery store", "guillotine", "hair clip", "hair spray", "half-track", "hammer", "hamper", "hair dryer", "hand-held computer", "handkerchief", "hard disk drive", "harmonica", "harp", "combine harvester", "hatchet", "holster", "home theater", "honeycomb", "hook", "hoop skirt", "gymnastic horizontal bar", "horse-drawn vehicle", "hourglass", "iPod", "clothes iron", "carved pumpkin", "jeans", "jeep", "T-shirt", "jigsaw puzzle", "rickshaw", "joystick", "kimono", "knee pad", "knot", "lab coat", "ladle", "lampshade", "laptop computer", "lawn mower", "lens cap", "letter opener", "library", "lifeboat", "lighter", "limousine", "ocean liner", "lipstick", "slip-on shoe", "lotion", "music speaker", "loupe magnifying glass", "sawmill", "magnetic compass", "messenger bag", "mailbox", "tights", "one-piece bathing suit", "manhole cover", "maraca", "marimba", "mask", "matchstick", "maypole", "maze", "measuring cup", "medicine cabinet", "megalith", "microphone", "microwave oven", "military uniform", "milk can", "minibus", "miniskirt", "minivan", "missile", "mitten", "mixing bowl", "mobile home", "ford model t", "modem", "monastery", "monitor", "moped", "mortar and pestle", "graduation cap", "mosque", "mosquito net", "vespa", "mountain bike", "tent", "computer mouse", "mousetrap", "moving van", "muzzle", "metal nail", "neck brace", "necklace", "baby pacifier", "notebook computer", "obelisk", "oboe", "ocarina", "odometer", "oil filter", "pipe organ", "oscilloscope", "overskirt", "bullock cart", "oxygen mask", "product packet / packaging", "paddle", "paddle wheel", "padlock", "paintbrush", "pajamas", "palace", "pan flute", "paper towel", "parachute", "parallel bars", "park bench", "parking meter", "railroad car", "patio", "payphone", "pedestal", "pencil case", "pencil sharpener", "perfume", "Petri dish", "photocopier", "plectrum", "Pickelhaube", "picket fence", "pickup truck", "pier", "piggy bank", "pill bottle", "pillow", "ping-pong ball", "pinwheel", "pirate ship", "drink pitcher", "block plane", "planetarium", "plastic bag", "plate rack", "farm plow", "plunger", "Polaroid camera", "pole", "police van", "poncho", "pool table", "soda bottle", "plant pot", "potter's wheel", "power drill", "prayer rug", "printer", "prison", "missile", "projector", "hockey puck", "punching bag", "purse", "quill", "quilt", "race car", "racket", "radiator", "radio", "radio telescope", "rain barrel", "recreational vehicle", "fishing casting reel", "reflex camera", "refrigerator", "remote control", "restaurant", "revolver", "rifle", "rocking chair", "rotisserie", "eraser", "rugby ball", "ruler measuring stick", "sneaker", "safe", "safety pin", "salt shaker", "sandal", "sarong", "saxophone", "scabbard", "weighing scale", "school bus", "schooner", "scoreboard", "CRT monitor", "screw", "screwdriver", "seat belt", "sewing machine", "shield", "shoe store", "shoji screen / room divider", "shopping basket", "shopping cart", "shovel", "shower cap", "shower curtain", "ski", "balaclava ski mask", "sleeping bag", "slide rule", "sliding door", "slot machine", "snorkel", "snowmobile", "snowplow", "soap dispenser", "soccer ball", "sock", "solar thermal collector", "sombrero", "soup bowl", "keyboard space bar", "space heater", "space shuttle", "spatula", "motorboat", "spider web", "spindle", "sports car", "spotlight", "stage", "steam locomotive", "through arch bridge", "steel drum", "stethoscope", "scarf", "stone wall", "stopwatch", "stove", "strainer", "tram", "stretcher", "couch", "stupa", "submarine", "suit", "sundial", "sunglasses", "sunglasses", "sunscreen", "suspension bridge", "mop", "sweatshirt", "swim trunks / shorts", "swing", "electrical switch", "syringe", "table lamp", "tank", "tape player", "teapot", "teddy bear", "television", "tennis ball", "thatched roof", "front curtain", "thimble", "threshing machine", "throne", "tile roof", "toaster", "tobacco shop", "toilet seat", "torch", "totem pole", "tow truck", "toy store", "tractor", "semi-trailer truck", "tray", "trench coat", "tricycle", "trimaran", "tripod", "triumphal arch", "trolleybus", "trombone", "hot tub", "turnstile", "typewriter keyboard", "umbrella", "unicycle", "upright piano", "vacuum cleaner", "vase", "vaulted or arched ceiling", "velvet fabric", "vending machine", "vestment", "viaduct", "violin", "volleyball", "waffle iron", "wall clock", "wallet", "wardrobe", "military aircraft", "sink", "washing machine", "water bottle", "water jug", "water tower", "whiskey jug", "whistle", "hair wig", "window screen", "window shade", "Windsor tie", "wine bottle", "airplane wing", "wok", "wooden spoon", "wool", "split-rail fence", "shipwreck", "sailboat", "yurt", "website", "comic book", "crossword", "traffic or street sign", "traffic light", "dust jacket", "menu", "plate", "guacamole", "consomme", "hot pot", "trifle", "ice cream", "popsicle", "baguette", "bagel", "pretzel", "cheeseburger", "hot dog", "mashed potatoes", "cabbage", "broccoli", "cauliflower", "zucchini", "spaghetti squash", "acorn squash", "butternut squash", "cucumber", "artichoke", "bell pepper", "cardoon", "mushroom", "Granny Smith apple", "strawberry", "orange", "lemon", "fig", "pineapple", "banana", "jackfruit", "cherimoya (custard apple)", "pomegranate", "hay", "carbonara", "chocolate syrup", "dough", "meatloaf", "pizza", "pot pie", "burrito", "red wine", "espresso", "tea cup", "eggnog", "mountain", "bubble", "cliff", "coral reef", "geyser", "lakeshore", "promontory", "sandbar", "beach", "valley", "volcano", "baseball player", "bridegroom", "scuba diver", "rapeseed", "daisy", "yellow lady's slipper", "corn", "acorn", "rose hip", "horse chestnut seed", "coral fungus", "agaric", "gyromitra", "stinkhorn mushroom", "earth star fungus", "hen of the woods mushroom", "bolete", "corn cob", "toilet paper"] \ No newline at end of file diff --git a/utils/imagenet_segmentation.py b/utils/imagenet_segmentation.py new file mode 100644 index 0000000000000000000000000000000000000000..50501fa8da3f5a6c531640b21f2ab747c8de9f6c --- /dev/null +++ b/utils/imagenet_segmentation.py @@ -0,0 +1,50 @@ +import os +import torch +import torch.utils.data as data +import numpy as np + +from torchvision.datasets import ImageNet + +from PIL import Image, ImageFilter +import h5py +from glob import glob + + +class ImagenetSegmentation(data.Dataset): + CLASSES = 2 + + def __init__(self, + path, + transform=None, + target_transform=None): + self.path = path + self.transform = transform + self.target_transform = target_transform + self.h5py = None + tmp = h5py.File(path, 'r') + self.data_length = len(tmp['/value/img']) + tmp.close() + del tmp + + def __getitem__(self, index): + + if self.h5py is None: + self.h5py = h5py.File(self.path, 'r') + + img = np.array(self.h5py[self.h5py['/value/img'][index, 0]]).transpose((2, 1, 0)) + target = np.array(self.h5py[self.h5py[self.h5py['/value/gt'][index, 0]][0, 0]]).transpose((1, 0)) + + img = Image.fromarray(img).convert('RGB') + target = Image.fromarray(target) + + if self.transform is not None: + img = self.transform(img) + + if self.target_transform is not None: + target = np.array(self.target_transform(target)).astype('int32') + target = torch.from_numpy(target).long() + + return img, target + + def __len__(self): + return self.data_length diff --git a/utils/misc.py b/utils/misc.py new file mode 100644 index 0000000000000000000000000000000000000000..515e352282201079e7545f1993d05a2bf401b1ac --- /dev/null +++ b/utils/misc.py @@ -0,0 +1,114 @@ +from itertools import repeat +import collections.abc + +import torch +from torch import nn as nn +from torchvision.ops.misc import FrozenBatchNorm2d + + +def freeze_batch_norm_2d(module, module_match={}, name=''): + """ + Converts all `BatchNorm2d` and `SyncBatchNorm` layers of provided module into `FrozenBatchNorm2d`. If `module` is + itself an instance of either `BatchNorm2d` or `SyncBatchNorm`, it is converted into `FrozenBatchNorm2d` and + returned. Otherwise, the module is walked recursively and submodules are converted in place. + + Args: + module (torch.nn.Module): Any PyTorch module. + module_match (dict): Dictionary of full module names to freeze (all if empty) + name (str): Full module name (prefix) + + Returns: + torch.nn.Module: Resulting module + + Inspired by https://github.com/pytorch/pytorch/blob/a5895f85be0f10212791145bfedc0261d364f103/torch/nn/modules/batchnorm.py#L762 + """ + res = module + is_match = True + if module_match: + is_match = name in module_match + if is_match and isinstance(module, (nn.modules.batchnorm.BatchNorm2d, nn.modules.batchnorm.SyncBatchNorm)): + res = FrozenBatchNorm2d(module.num_features) + res.num_features = module.num_features + res.affine = module.affine + if module.affine: + res.weight.data = module.weight.data.clone().detach() + res.bias.data = module.bias.data.clone().detach() + res.running_mean.data = module.running_mean.data + res.running_var.data = module.running_var.data + res.eps = module.eps + else: + for child_name, child in module.named_children(): + full_child_name = '.'.join([name, child_name]) if name else child_name + new_child = freeze_batch_norm_2d(child, module_match, full_child_name) + if new_child is not child: + res.add_module(child_name, new_child) + return res + + +# From PyTorch internals +def _ntuple(n): + def parse(x): + if isinstance(x, collections.abc.Iterable): + return x + return tuple(repeat(x, n)) + return parse + + +to_1tuple = _ntuple(1) +to_2tuple = _ntuple(2) +to_3tuple = _ntuple(3) +to_4tuple = _ntuple(4) +to_ntuple = lambda n, x: _ntuple(n)(x) + +# Replaces all linear layers with linear_replacement +# TODO: add int8 support for other linear layers including attn and convnets +def replace_linear(model, linear_replacement, include_modules=['c_fc', 'c_proj'], copy_weights=True): + for name, module in model.named_children(): + if len(list(module.children())) > 0: + replace_linear(module, linear_replacement, include_modules, copy_weights) + + if isinstance(module, torch.nn.Linear) and name in include_modules: + old_module = model._modules[name] + model._modules[name] = linear_replacement( + module.in_features, + module.out_features, + module.bias is not None, + ) + if copy_weights: + model._modules[name].weight.data.copy_(old_module.weight.data) + if model._modules[name].bias is not None: + model._modules[name].bias.data.copy_(old_module.bias) + + return model + +def convert_int8_model_to_inference_mode(model): + for m in model.modules(): + if hasattr(m, 'prepare_for_eval'): + int8_original_dtype = m.weight.dtype + m.prepare_for_eval() + m.int8_original_dtype = int8_original_dtype + + +def accuracy(output, target, topk=(1,)): + """ + Compute top-k accuracy + + output: torch.Tensor + shape (N, C) where N is the number of examples, C the number of classes. + these are the logits. + + target: torch.Tensor + shape (N,) where N is the number of examples. Groundtruth class id of each example. + + topk: tuple + which topk to compute, e.g., topk=(1,5) will compute top-1 and top-5 accuracies + + Returns + ------- + + list of top-k accuracies in the same order as `topk` + """ + pred = output.topk(max(topk), 1, True, True)[1].t() + correct = pred.eq(target.view(1, -1).expand_as(pred)) + n = len(target) + return [float(correct[:k].reshape(-1).float().sum(0, keepdim=True).cpu().numpy()) / n for k in topk] diff --git a/utils/model.py b/utils/model.py new file mode 100644 index 0000000000000000000000000000000000000000..779cb8f326a281b7e4bfff97d25eac72f8c8fc03 --- /dev/null +++ b/utils/model.py @@ -0,0 +1,413 @@ +""" CLIP Model + +Adapted from https://github.com/openai/CLIP. Originally MIT License, Copyright (c) 2021 OpenAI. +""" +from dataclasses import dataclass +import logging +import math +from typing import Optional, Tuple, Union, Text + +import numpy as np +import torch +import torch.nn.functional as F +from torch import nn +from torch.utils.checkpoint import checkpoint + + +from utils.modified_resnet import ModifiedResNet +from utils.timm_model import TimmModel +from utils.transformer import LayerNorm, QuickGELU, VisionTransformer, TextTransformer, Attention +from utils.misc import to_2tuple +from utils.hook import HookManager + + +@dataclass +class CLIPVisionCfg: + layers: Union[Tuple[int, int, int, int], int] = 12 + width: int = 768 + head_width: int = 64 + mlp_ratio: float = 4.0 + patch_size: int = 16 + image_size: Union[Tuple[int, int], int] = 224 + + ls_init_value: Optional[float] = None # layer scale initial value + patch_dropout: float = 0. # what fraction of patches to dropout during training (0 would mean disabled and no patches dropped) - 0.5 to 0.75 recommended in the paper for optimal results + input_patchnorm: bool = False # whether to use dual patchnorm - would only apply the input layernorm on each patch, as post-layernorm already exist in original clip vit design + global_average_pool: bool = False # whether to global average pool the last embedding layer, instead of using CLS token (https://arxiv.org/abs/2205.01580) + attentional_pool: bool = False # whether to use attentional pooler in the last embedding layer + n_queries: int = 256 # n_queries for attentional pooler + attn_pooler_heads: int = 8 # n heads for attentional_pooling + output_tokens: bool = False + + timm_model_name: str = None # a valid model name overrides layers, width, patch_size + timm_model_pretrained: bool = False # use (imagenet) pretrained weights for named model + timm_pool: str = 'avg' # feature pooling for timm model ('abs_attn', 'rot_attn', 'avg', '') + timm_proj: str = 'linear' # linear projection for timm model output ('linear', 'mlp', '') + timm_proj_bias: bool = False # enable bias final projection + timm_drop: float = 0. # head dropout + timm_drop_path: Optional[float] = None # backbone stochastic depth + + + + +def convert_weights_to_lp(model: nn.Module, dtype=torch.float16): + """Convert applicable model parameters to low-precision (bf16 or fp16)""" + + def _convert_weights(l): + if isinstance(l, (nn.Conv1d, nn.Conv2d, nn.Linear)): + l.weight.data = l.weight.data.to(dtype) + if l.bias is not None: + l.bias.data = l.bias.data.to(dtype) + + if isinstance(l, (nn.MultiheadAttention, Attention)): + for attr in [*[f"{s}_proj_weight" for s in ["in", "q", "k", "v"]], "in_proj_bias", "bias_k", "bias_v"]: + tensor = getattr(l, attr) + if tensor is not None: + tensor.data = tensor.data.to(dtype) + + if isinstance(l, (CLIP, TextTransformer)): + # convert text nn.Parameter projections + attr = getattr(l, "text_projection", None) + if attr is not None: + attr.data = attr.data.to(dtype) + + if isinstance(l, VisionTransformer): + # convert vision nn.Parameter projections + attr = getattr(l, "proj", None) + if attr is not None: + attr.data = attr.data.to(dtype) + + model.apply(_convert_weights) + +convert_weights_to_fp16 = convert_weights_to_lp # backwards compat + + +@dataclass +class CLIPTextCfg: + context_length: int = 77 + vocab_size: int = 49408 + width: int = 512 + heads: int = 8 + layers: int = 12 + ls_init_value: Optional[float] = None # layer scale initial value + hf_model_name: str = None + hf_tokenizer_name: str = None + hf_model_pretrained: bool = True + proj: str = 'mlp' + pooler_type: str = 'mean_pooler' + embed_cls: bool = False + pad_id: int = 0 + output_tokens: bool = False + + +def get_cast_dtype(precision: str): + cast_dtype = None + if precision == 'bf16': + cast_dtype = torch.bfloat16 + elif precision == 'fp16': + cast_dtype = torch.float16 + return cast_dtype + + +def get_input_dtype(precision: str): + input_dtype = None + if precision in ('bf16', 'pure_bf16'): + input_dtype = torch.bfloat16 + elif precision in ('fp16', 'pure_fp16'): + input_dtype = torch.float16 + return input_dtype + + +def _build_vision_tower( + embed_dim: int, + vision_cfg: CLIPVisionCfg, + quick_gelu: bool = False, + cast_dtype: Optional[torch.dtype] = None, + hook: Optional[HookManager]= None, +): + if isinstance(vision_cfg, dict): + vision_cfg = CLIPVisionCfg(**vision_cfg) + + # OpenAI models are pretrained w/ QuickGELU but native nn.GELU is both faster and more + # memory efficient in recent PyTorch releases (>= 1.10). + # NOTE: timm models always use native GELU regardless of quick_gelu flag. + act_layer = QuickGELU if quick_gelu else nn.GELU + + if vision_cfg.timm_model_name: + visual = TimmModel( + vision_cfg.timm_model_name, + pretrained=vision_cfg.timm_model_pretrained, + pool=vision_cfg.timm_pool, + proj=vision_cfg.timm_proj, + proj_bias=vision_cfg.timm_proj_bias, + drop=vision_cfg.timm_drop, + drop_path=vision_cfg.timm_drop_path, + patch_drop=vision_cfg.patch_dropout if vision_cfg.patch_dropout > 0 else None, + embed_dim=embed_dim, + image_size=vision_cfg.image_size, + hook=hook, + ) + elif isinstance(vision_cfg.layers, (tuple, list)): + vision_heads = vision_cfg.width * 32 // vision_cfg.head_width + visual = ModifiedResNet( + layers=vision_cfg.layers, + output_dim=embed_dim, + heads=vision_heads, + image_size=vision_cfg.image_size, + width=vision_cfg.width, + hook=hook, + ) + else: + vision_heads = vision_cfg.width // vision_cfg.head_width + norm_layer = LayerNormFp32 if cast_dtype in (torch.float16, torch.bfloat16) else LayerNorm + visual = VisionTransformer( + image_size=vision_cfg.image_size, + patch_size=vision_cfg.patch_size, + width=vision_cfg.width, + layers=vision_cfg.layers, + heads=vision_heads, + mlp_ratio=vision_cfg.mlp_ratio, + ls_init_value=vision_cfg.ls_init_value, + patch_dropout=vision_cfg.patch_dropout, + input_patchnorm=vision_cfg.input_patchnorm, + global_average_pool=vision_cfg.global_average_pool, + attentional_pool=vision_cfg.attentional_pool, + n_queries=vision_cfg.n_queries, + attn_pooler_heads=vision_cfg.attn_pooler_heads, + output_tokens=vision_cfg.output_tokens, + output_dim=embed_dim, + act_layer=act_layer, + norm_layer=norm_layer, + hook=hook, + ) + + return visual + + +def _build_text_tower( + embed_dim: int, + text_cfg: CLIPTextCfg, + quick_gelu: bool = False, + cast_dtype: Optional[torch.dtype] = None, + hook: Optional[HookManager] = None, +): + if isinstance(text_cfg, dict): + text_cfg = CLIPTextCfg(**text_cfg) + + if text_cfg.hf_model_name: + from hf_model import HFTextEncoder + text = HFTextEncoder( + text_cfg.hf_model_name, + output_dim=embed_dim, + proj=text_cfg.proj, + pooler_type=text_cfg.pooler_type, + pretrained=text_cfg.hf_model_pretrained, + output_tokens=text_cfg.output_tokens, + ) + else: + act_layer = QuickGELU if quick_gelu else nn.GELU + norm_layer = LayerNormFp32 if cast_dtype in (torch.float16, torch.bfloat16) else LayerNorm + + text = TextTransformer( + context_length=text_cfg.context_length, + vocab_size=text_cfg.vocab_size, + width=text_cfg.width, + heads=text_cfg.heads, + layers=text_cfg.layers, + ls_init_value=text_cfg.ls_init_value, + output_dim=embed_dim, + embed_cls=text_cfg.embed_cls, + output_tokens=text_cfg.output_tokens, + pad_id=text_cfg.pad_id, + act_layer=act_layer, + norm_layer=norm_layer, + ) + return text + + +class CLIP(nn.Module): + output_dict: torch.jit.Final[bool] + + def __init__( + self, + embed_dim: int, + vision_cfg: CLIPVisionCfg, + text_cfg: CLIPTextCfg, + quick_gelu: bool = False, + cast_dtype: Optional[torch.dtype] = None, + output_dict: bool = False, + hook: Optional[HookManager] = None, + ): + super().__init__() + self.hook_manager = hook or HookManager() + self.output_dict = output_dict + self.visual = _build_vision_tower(embed_dim, vision_cfg, quick_gelu, cast_dtype, self.hook_manager.fork('visual')) + + text = _build_text_tower(embed_dim, text_cfg, quick_gelu, cast_dtype, self.hook_manager.fork('textual')) + self.transformer = text.transformer + self.context_length = text.context_length + self.vocab_size = text.vocab_size + self.token_embedding = text.token_embedding + self.positional_embedding = text.positional_embedding + self.ln_final = text.ln_final + self.text_projection = text.text_projection + self.register_buffer('attn_mask', text.attn_mask, persistent=False) + + self.logit_scale = nn.Parameter(torch.ones([]) * np.log(1 / 0.07)) + + @torch.jit.ignore + def set_grad_checkpointing(self, enable=True): + self.visual.set_grad_checkpointing(enable) + self.transformer.grad_checkpointing = enable + + def encode_image(self, image, normalize: bool = False, attn_method: Text = 'direct'): + features = self.visual(image, attn_method=attn_method) + return F.normalize(features, dim=-1) if normalize else features + + def encode_text(self, text, normalize: bool = False, full_sentence: bool = False, projection: bool = True): + cast_dtype = self.transformer.get_cast_dtype() + + x = self.token_embedding(text).to(cast_dtype) # [batch_size, n_ctx, d_model] + + x = x + self.positional_embedding.to(cast_dtype) + # x = x.permute(1, 0, 2) # NLD -> LND + x = self.transformer(x, attn_mask=self.attn_mask) + # x = x.permute(1, 0, 2) # LND -> NLD + x = self.ln_final(x) # [batch_size, n_ctx, transformer.width] + if full_sentence: + if projection: + x = x @ self.text_projection + else: + x = x + else: + # take features from the eot embedding (eot_token is the highest number in each sequence) + x = x[torch.arange(x.shape[0]), text.argmax(dim=-1)] @ self.text_projection + return F.normalize(x, dim=-1) if normalize else x + + def forward( + self, + image: Optional[torch.Tensor] = None, + text: Optional[torch.Tensor] = None, + ): + image_features = self.encode_image(image, normalize=True) if image is not None else None + text_features = self.encode_text(text, normalize=True) if text is not None else None + if self.output_dict: + return { + "image_features": image_features, + "text_features": text_features, + "logit_scale": self.logit_scale.exp() + } + return image_features, text_features, self.logit_scale.exp() + + +# used to maintain checkpoint compatibility +def convert_to_custom_text_state_dict(state_dict: dict): + if 'text_projection' in state_dict: + # old format state_dict, move text tower -> .text + new_state_dict = {} + for k, v in state_dict.items(): + if any(k.startswith(p) for p in ( + 'text_projection', + 'positional_embedding', + 'token_embedding', + 'transformer', + 'ln_final', + )): + k = 'text.' + k + new_state_dict[k] = v + return new_state_dict + return state_dict + + +def build_model_from_openai_state_dict( + state_dict: dict, + quick_gelu=True, + cast_dtype=torch.float16, +): + vit = "visual.proj" in state_dict + + if vit: + vision_width = state_dict["visual.conv1.weight"].shape[0] + vision_layers = len( + [k for k in state_dict.keys() if k.startswith("visual.") and k.endswith(".attn.in_proj_weight")]) + vision_patch_size = state_dict["visual.conv1.weight"].shape[-1] + grid_size = round((state_dict["visual.positional_embedding"].shape[0] - 1) ** 0.5) + image_size = vision_patch_size * grid_size + else: + counts: list = [ + len(set(k.split(".")[2] for k in state_dict if k.startswith(f"visual.layer{b}"))) for b in [1, 2, 3, 4]] + vision_layers = tuple(counts) + vision_width = state_dict["visual.layer1.0.conv1.weight"].shape[0] + output_width = round((state_dict["visual.attnpool.positional_embedding"].shape[0] - 1) ** 0.5) + vision_patch_size = None + assert output_width ** 2 + 1 == state_dict["visual.attnpool.positional_embedding"].shape[0] + image_size = output_width * 32 + + embed_dim = state_dict["text_projection"].shape[1] + context_length = state_dict["positional_embedding"].shape[0] + vocab_size = state_dict["token_embedding.weight"].shape[0] + transformer_width = state_dict["ln_final.weight"].shape[0] + transformer_heads = transformer_width // 64 + transformer_layers = len(set(k.split(".")[2] for k in state_dict if k.startswith(f"transformer.resblocks"))) + + vision_cfg = CLIPVisionCfg( + layers=vision_layers, + width=vision_width, + patch_size=vision_patch_size, + image_size=image_size, + ) + text_cfg = CLIPTextCfg( + context_length=context_length, + vocab_size=vocab_size, + width=transformer_width, + heads=transformer_heads, + layers=transformer_layers, + ) + model = CLIP( + embed_dim, + vision_cfg=vision_cfg, + text_cfg=text_cfg, + quick_gelu=quick_gelu, # OpenAI models were trained with QuickGELU + cast_dtype=cast_dtype, + ) + + for key in ["input_resolution", "context_length", "vocab_size"]: + state_dict.pop(key, None) + + convert_weights_to_fp16(model) # OpenAI state dicts are partially converted to float16 + model.load_state_dict(state_dict) + return model.eval() + + +def resize_pos_embed(state_dict, model, interpolation: str = 'bicubic', antialias: bool = True): + # Rescale the grid of position embeddings when loading from state_dict + old_pos_embed = state_dict.get('visual.positional_embedding', None) + if old_pos_embed is None or not hasattr(model.visual, 'grid_size'): + return + grid_size = to_2tuple(model.visual.grid_size) + extra_tokens = 1 # FIXME detect different token configs (ie no class token, or more) + new_seq_len = grid_size[0] * grid_size[1] + extra_tokens + if new_seq_len == old_pos_embed.shape[0]: + return + + if extra_tokens: + pos_emb_tok, pos_emb_img = old_pos_embed[:extra_tokens], old_pos_embed[extra_tokens:] + else: + pos_emb_tok, pos_emb_img = None, old_pos_embed + old_grid_size = to_2tuple(int(math.sqrt(len(pos_emb_img)))) + + logging.info('Resizing position embedding grid-size from %s to %s', old_grid_size, grid_size) + pos_emb_img = pos_emb_img.reshape(1, old_grid_size[0], old_grid_size[1], -1).permute(0, 3, 1, 2) + pos_emb_img = F.interpolate( + pos_emb_img, + size=grid_size, + mode=interpolation, + antialias=antialias, + align_corners=False, + ) + pos_emb_img = pos_emb_img.permute(0, 2, 3, 1).reshape(1, grid_size[0] * grid_size[1], -1)[0] + if pos_emb_tok is not None: + new_pos_embed = torch.cat([pos_emb_tok, pos_emb_img], dim=0) + else: + new_pos_embed = pos_emb_img + state_dict['visual.positional_embedding'] = new_pos_embed \ No newline at end of file diff --git a/utils/model_configs/EVA01-g-14-plus.json b/utils/model_configs/EVA01-g-14-plus.json new file mode 100644 index 0000000000000000000000000000000000000000..73f46a71e664fce987218b8eb48903e7bd895f41 --- /dev/null +++ b/utils/model_configs/EVA01-g-14-plus.json @@ -0,0 +1,18 @@ +{ + "embed_dim": 1024, + "vision_cfg": { + "image_size": 224, + "timm_model_name": "eva_giant_patch14_224", + "timm_model_pretrained": false, + "timm_pool": "token", + "timm_proj": null + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 1024, + "heads": 16, + "layers": 24 + }, + "custom_text": true +} \ No newline at end of file diff --git a/utils/model_configs/EVA01-g-14.json b/utils/model_configs/EVA01-g-14.json new file mode 100644 index 0000000000000000000000000000000000000000..9d0e80f290d9491b7c46fafd576201b1258165aa --- /dev/null +++ b/utils/model_configs/EVA01-g-14.json @@ -0,0 +1,18 @@ +{ + "embed_dim": 1024, + "vision_cfg": { + "image_size": 224, + "timm_model_name": "eva_giant_patch14_224", + "timm_model_pretrained": false, + "timm_pool": "token", + "timm_proj": null + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 768, + "heads": 12, + "layers": 12 + }, + "custom_text": true +} \ No newline at end of file diff --git a/utils/model_configs/EVA02-B-16.json b/utils/model_configs/EVA02-B-16.json new file mode 100644 index 0000000000000000000000000000000000000000..3f92357287e1f6600da1e7f391cb6370d7f66de4 --- /dev/null +++ b/utils/model_configs/EVA02-B-16.json @@ -0,0 +1,18 @@ +{ + "embed_dim": 512, + "vision_cfg": { + "image_size": 224, + "timm_model_name": "eva02_base_patch16_clip_224", + "timm_model_pretrained": false, + "timm_pool": "token", + "timm_proj": null + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 512, + "heads": 8, + "layers": 12 + }, + "custom_text": true +} \ No newline at end of file diff --git a/utils/model_configs/EVA02-E-14-plus.json b/utils/model_configs/EVA02-E-14-plus.json new file mode 100644 index 0000000000000000000000000000000000000000..e250c2a404c86ff168c54cfcf71bc2492be1b74c --- /dev/null +++ b/utils/model_configs/EVA02-E-14-plus.json @@ -0,0 +1,18 @@ +{ + "embed_dim": 1024, + "vision_cfg": { + "image_size": 224, + "timm_model_name": "eva02_enormous_patch14_clip_224", + "timm_model_pretrained": false, + "timm_pool": "token", + "timm_proj": null + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 1280, + "heads": 20, + "layers": 32 + }, + "custom_text": true +} \ No newline at end of file diff --git a/utils/model_configs/EVA02-E-14.json b/utils/model_configs/EVA02-E-14.json new file mode 100644 index 0000000000000000000000000000000000000000..4b6648e25092b151a9095e0a66956c7ebf835b16 --- /dev/null +++ b/utils/model_configs/EVA02-E-14.json @@ -0,0 +1,18 @@ +{ + "embed_dim": 1024, + "vision_cfg": { + "image_size": 224, + "timm_model_name": "eva02_enormous_patch14_clip_224", + "timm_model_pretrained": false, + "timm_pool": "token", + "timm_proj": null + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 1024, + "heads": 16, + "layers": 24 + }, + "custom_text": true +} \ No newline at end of file diff --git a/utils/model_configs/EVA02-L-14-336.json b/utils/model_configs/EVA02-L-14-336.json new file mode 100644 index 0000000000000000000000000000000000000000..2bb07f3c082fd88c4e86131b272163aaacfaef9e --- /dev/null +++ b/utils/model_configs/EVA02-L-14-336.json @@ -0,0 +1,18 @@ +{ + "embed_dim": 768, + "vision_cfg": { + "image_size": 336, + "timm_model_name": "eva02_large_patch14_clip_336", + "timm_model_pretrained": false, + "timm_pool": "token", + "timm_proj": null + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 768, + "heads": 12, + "layers": 12 + }, + "custom_text": true +} \ No newline at end of file diff --git a/utils/model_configs/EVA02-L-14.json b/utils/model_configs/EVA02-L-14.json new file mode 100644 index 0000000000000000000000000000000000000000..b4c7f377bc543aa92a145358f2630a58ae9be989 --- /dev/null +++ b/utils/model_configs/EVA02-L-14.json @@ -0,0 +1,18 @@ +{ + "embed_dim": 768, + "vision_cfg": { + "image_size": 224, + "timm_model_name": "eva02_large_patch14_clip_224", + "timm_model_pretrained": false, + "timm_pool": "token", + "timm_proj": null + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 768, + "heads": 12, + "layers": 12 + }, + "custom_text": true +} \ No newline at end of file diff --git a/utils/model_configs/ViT-B-16-plus-240.json b/utils/model_configs/ViT-B-16-plus-240.json new file mode 100644 index 0000000000000000000000000000000000000000..5bbd12bcd01f64d6d0a0aa8316b129327a0d169a --- /dev/null +++ b/utils/model_configs/ViT-B-16-plus-240.json @@ -0,0 +1,16 @@ +{ + "embed_dim": 640, + "vision_cfg": { + "image_size": 240, + "layers": 12, + "width": 896, + "patch_size": 16 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 640, + "heads": 10, + "layers": 12 + } +} \ No newline at end of file diff --git a/utils/model_configs/ViT-B-16-plus.json b/utils/model_configs/ViT-B-16-plus.json new file mode 100644 index 0000000000000000000000000000000000000000..5dc1e09baccef2b15055c1bffeb9903e760101c6 --- /dev/null +++ b/utils/model_configs/ViT-B-16-plus.json @@ -0,0 +1,16 @@ +{ + "embed_dim": 640, + "vision_cfg": { + "image_size": 224, + "layers": 12, + "width": 896, + "patch_size": 16 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 640, + "heads": 10, + "layers": 12 + } +} \ No newline at end of file diff --git a/utils/model_configs/ViT-B-16.json b/utils/model_configs/ViT-B-16.json new file mode 100644 index 0000000000000000000000000000000000000000..395eea77ec3907c0611531aba63459b193e67b9c --- /dev/null +++ b/utils/model_configs/ViT-B-16.json @@ -0,0 +1,16 @@ +{ + "embed_dim": 512, + "vision_cfg": { + "image_size": 224, + "layers": 12, + "width": 768, + "patch_size": 16 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 512, + "heads": 8, + "layers": 12 + } +} \ No newline at end of file diff --git a/utils/model_configs/ViT-B-32-plus-256.json b/utils/model_configs/ViT-B-32-plus-256.json new file mode 100644 index 0000000000000000000000000000000000000000..2f09c857de9a4c01ae51297a7e2451984879f9de --- /dev/null +++ b/utils/model_configs/ViT-B-32-plus-256.json @@ -0,0 +1,16 @@ +{ + "embed_dim": 640, + "vision_cfg": { + "image_size": 256, + "layers": 12, + "width": 896, + "patch_size": 32 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 640, + "heads": 10, + "layers": 12 + } +} \ No newline at end of file diff --git a/utils/model_configs/ViT-B-32-quickgelu.json b/utils/model_configs/ViT-B-32-quickgelu.json new file mode 100644 index 0000000000000000000000000000000000000000..ce6bd923593293ed50dfcfb28b73ca7403bcf3c5 --- /dev/null +++ b/utils/model_configs/ViT-B-32-quickgelu.json @@ -0,0 +1,17 @@ +{ + "embed_dim": 512, + "quick_gelu": true, + "vision_cfg": { + "image_size": 224, + "layers": 12, + "width": 768, + "patch_size": 32 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 512, + "heads": 8, + "layers": 12 + } +} \ No newline at end of file diff --git a/utils/model_configs/ViT-B-32.json b/utils/model_configs/ViT-B-32.json new file mode 100644 index 0000000000000000000000000000000000000000..07c8e28eb06fa1813ba932fe4eec668262d1c47f --- /dev/null +++ b/utils/model_configs/ViT-B-32.json @@ -0,0 +1,16 @@ +{ + "embed_dim": 512, + "vision_cfg": { + "image_size": 224, + "layers": 12, + "width": 768, + "patch_size": 32 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 512, + "heads": 8, + "layers": 12 + } +} \ No newline at end of file diff --git a/utils/model_configs/ViT-H-14.json b/utils/model_configs/ViT-H-14.json new file mode 100644 index 0000000000000000000000000000000000000000..3e3a7e934e7f02e41f4829996c4950e05f015a74 --- /dev/null +++ b/utils/model_configs/ViT-H-14.json @@ -0,0 +1,17 @@ +{ + "embed_dim": 1024, + "vision_cfg": { + "image_size": 224, + "layers": 32, + "width": 1280, + "head_width": 80, + "patch_size": 14 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 1024, + "heads": 16, + "layers": 24 + } +} \ No newline at end of file diff --git a/utils/model_configs/ViT-H-16.json b/utils/model_configs/ViT-H-16.json new file mode 100644 index 0000000000000000000000000000000000000000..588485455fdf8193ec16474450b94e31c91ea93c --- /dev/null +++ b/utils/model_configs/ViT-H-16.json @@ -0,0 +1,17 @@ +{ + "embed_dim": 1024, + "vision_cfg": { + "image_size": 224, + "layers": 32, + "width": 1280, + "head_width": 80, + "patch_size": 16 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 1024, + "heads": 16, + "layers": 24 + } +} \ No newline at end of file diff --git a/utils/model_configs/ViT-L-14-280.json b/utils/model_configs/ViT-L-14-280.json new file mode 100644 index 0000000000000000000000000000000000000000..2262deaefa82792d35d73c0d7c8e620525092581 --- /dev/null +++ b/utils/model_configs/ViT-L-14-280.json @@ -0,0 +1,16 @@ +{ + "embed_dim": 768, + "vision_cfg": { + "image_size": 280, + "layers": 24, + "width": 1024, + "patch_size": 14 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 768, + "heads": 12, + "layers": 12 + } +} \ No newline at end of file diff --git a/utils/model_configs/ViT-L-14-336.json b/utils/model_configs/ViT-L-14-336.json new file mode 100644 index 0000000000000000000000000000000000000000..8d1f74c2639c3a3705df9865b9c08215675ddc97 --- /dev/null +++ b/utils/model_configs/ViT-L-14-336.json @@ -0,0 +1,16 @@ +{ + "embed_dim": 768, + "vision_cfg": { + "image_size": 336, + "layers": 24, + "width": 1024, + "patch_size": 14 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 768, + "heads": 12, + "layers": 12 + } +} \ No newline at end of file diff --git a/utils/model_configs/ViT-L-14.json b/utils/model_configs/ViT-L-14.json new file mode 100644 index 0000000000000000000000000000000000000000..d4a4bbb1dd4ed4edb317d3ace4f3ad13b211c241 --- /dev/null +++ b/utils/model_configs/ViT-L-14.json @@ -0,0 +1,16 @@ +{ + "embed_dim": 768, + "vision_cfg": { + "image_size": 224, + "layers": 24, + "width": 1024, + "patch_size": 14 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 768, + "heads": 12, + "layers": 12 + } +} \ No newline at end of file diff --git a/utils/model_configs/ViT-L-16-320.json b/utils/model_configs/ViT-L-16-320.json new file mode 100644 index 0000000000000000000000000000000000000000..fc2d13ca9ec7f0b56a886ddaf66c4a7ba7a442ba --- /dev/null +++ b/utils/model_configs/ViT-L-16-320.json @@ -0,0 +1,16 @@ +{ + "embed_dim": 768, + "vision_cfg": { + "image_size": 320, + "layers": 24, + "width": 1024, + "patch_size": 16 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 768, + "heads": 12, + "layers": 12 + } +} \ No newline at end of file diff --git a/utils/model_configs/ViT-L-16.json b/utils/model_configs/ViT-L-16.json new file mode 100644 index 0000000000000000000000000000000000000000..82a1cedfa290adacbbdc02bc5d589734c22d41d3 --- /dev/null +++ b/utils/model_configs/ViT-L-16.json @@ -0,0 +1,16 @@ +{ + "embed_dim": 768, + "vision_cfg": { + "image_size": 224, + "layers": 24, + "width": 1024, + "patch_size": 16 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 768, + "heads": 12, + "layers": 12 + } +} \ No newline at end of file diff --git a/utils/model_configs/ViT-M-16-alt.json b/utils/model_configs/ViT-M-16-alt.json new file mode 100644 index 0000000000000000000000000000000000000000..1a317aad8e02d9c26d2decc7cc49a18dfdf9e0d8 --- /dev/null +++ b/utils/model_configs/ViT-M-16-alt.json @@ -0,0 +1,17 @@ +{ + "embed_dim": 384, + "vision_cfg": { + "image_size": 224, + "layers": 12, + "width": 512, + "patch_size": 16, + "ls_init_value": 1e-4 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 384, + "heads": 6, + "layers": 12 + } +} \ No newline at end of file diff --git a/utils/model_configs/ViT-M-16.json b/utils/model_configs/ViT-M-16.json new file mode 100644 index 0000000000000000000000000000000000000000..f2f3225a46e09237730a151d161f70c86b985172 --- /dev/null +++ b/utils/model_configs/ViT-M-16.json @@ -0,0 +1,16 @@ +{ + "embed_dim": 512, + "vision_cfg": { + "image_size": 224, + "layers": 12, + "width": 512, + "patch_size": 16 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 512, + "heads": 8, + "layers": 12 + } +} \ No newline at end of file diff --git a/utils/model_configs/ViT-M-32-alt.json b/utils/model_configs/ViT-M-32-alt.json new file mode 100644 index 0000000000000000000000000000000000000000..fd222aeac0f582ef6a1a33f1b3fec70a5b386ac0 --- /dev/null +++ b/utils/model_configs/ViT-M-32-alt.json @@ -0,0 +1,16 @@ +{ + "embed_dim": 384, + "vision_cfg": { + "image_size": 224, + "layers": 12, + "width": 512, + "patch_size": 32 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 384, + "heads": 6, + "layers": 12 + } +} \ No newline at end of file diff --git a/utils/model_configs/ViT-M-32.json b/utils/model_configs/ViT-M-32.json new file mode 100644 index 0000000000000000000000000000000000000000..4f718642821035d9776d1e006817d65ede074366 --- /dev/null +++ b/utils/model_configs/ViT-M-32.json @@ -0,0 +1,16 @@ +{ + "embed_dim": 512, + "vision_cfg": { + "image_size": 224, + "layers": 12, + "width": 512, + "patch_size": 32 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 512, + "heads": 8, + "layers": 12 + } +} \ No newline at end of file diff --git a/utils/model_configs/ViT-S-16-alt.json b/utils/model_configs/ViT-S-16-alt.json new file mode 100644 index 0000000000000000000000000000000000000000..a8c056555e4da3ba0d1475a61fc316362ecce76f --- /dev/null +++ b/utils/model_configs/ViT-S-16-alt.json @@ -0,0 +1,16 @@ +{ + "embed_dim": 256, + "vision_cfg": { + "image_size": 224, + "layers": 12, + "width": 384, + "patch_size": 16 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 256, + "heads": 4, + "layers": 10 + } +} \ No newline at end of file diff --git a/utils/model_configs/ViT-S-16.json b/utils/model_configs/ViT-S-16.json new file mode 100644 index 0000000000000000000000000000000000000000..1d8504e59658803f3093e5b05de45f30a09b8185 --- /dev/null +++ b/utils/model_configs/ViT-S-16.json @@ -0,0 +1,16 @@ +{ + "embed_dim": 384, + "vision_cfg": { + "image_size": 224, + "layers": 12, + "width": 384, + "patch_size": 16 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 384, + "heads": 6, + "layers": 12 + } +} \ No newline at end of file diff --git a/utils/model_configs/ViT-S-32-alt.json b/utils/model_configs/ViT-S-32-alt.json new file mode 100644 index 0000000000000000000000000000000000000000..e1dfdec9824df09a2010e991ccfa1d9ee2f45807 --- /dev/null +++ b/utils/model_configs/ViT-S-32-alt.json @@ -0,0 +1,16 @@ +{ + "embed_dim": 256, + "vision_cfg": { + "image_size": 224, + "layers": 12, + "width": 384, + "patch_size": 32 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 256, + "heads": 4, + "layers": 10 + } +} \ No newline at end of file diff --git a/utils/model_configs/ViT-S-32.json b/utils/model_configs/ViT-S-32.json new file mode 100644 index 0000000000000000000000000000000000000000..9b8b4191b268de267268cfcb90fc01c6b9df07d8 --- /dev/null +++ b/utils/model_configs/ViT-S-32.json @@ -0,0 +1,16 @@ +{ + "embed_dim": 384, + "vision_cfg": { + "image_size": 224, + "layers": 12, + "width": 384, + "patch_size": 32 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 384, + "heads": 6, + "layers": 12 + } +} \ No newline at end of file diff --git a/utils/model_configs/ViT-bigG-14.json b/utils/model_configs/ViT-bigG-14.json new file mode 100644 index 0000000000000000000000000000000000000000..2cfba479a2e8f3737e71ce240732bf3bc743d8b7 --- /dev/null +++ b/utils/model_configs/ViT-bigG-14.json @@ -0,0 +1,18 @@ +{ + "embed_dim": 1280, + "vision_cfg": { + "image_size": 224, + "layers": 48, + "width": 1664, + "head_width": 104, + "mlp_ratio": 4.9231, + "patch_size": 14 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 1280, + "heads": 20, + "layers": 32 + } +} \ No newline at end of file diff --git a/utils/model_configs/ViT-e-14.json b/utils/model_configs/ViT-e-14.json new file mode 100644 index 0000000000000000000000000000000000000000..91a0fe14d25a107fb8ec48dd7faae313fd26ed7b --- /dev/null +++ b/utils/model_configs/ViT-e-14.json @@ -0,0 +1,18 @@ +{ + "embed_dim": 1280, + "vision_cfg": { + "image_size": 224, + "layers": 56, + "width": 1792, + "head_width": 112, + "mlp_ratio": 8.5715, + "patch_size": 14 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 1280, + "heads": 20, + "layers": 36 + } +} \ No newline at end of file diff --git a/utils/model_configs/ViT-g-14.json b/utils/model_configs/ViT-g-14.json new file mode 100644 index 0000000000000000000000000000000000000000..8c4b7325cc75b6112be7107d36ae2cb5762d9091 --- /dev/null +++ b/utils/model_configs/ViT-g-14.json @@ -0,0 +1,18 @@ +{ + "embed_dim": 1024, + "vision_cfg": { + "image_size": 224, + "layers": 40, + "width": 1408, + "head_width": 88, + "mlp_ratio": 4.3637, + "patch_size": 14 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 1024, + "heads": 16, + "layers": 24 + } +} \ No newline at end of file diff --git a/utils/model_configs/coca_ViT-B-32.json b/utils/model_configs/coca_ViT-B-32.json new file mode 100644 index 0000000000000000000000000000000000000000..7e7eb520a6a0096e5602d509ecd6186e278f4725 --- /dev/null +++ b/utils/model_configs/coca_ViT-B-32.json @@ -0,0 +1,30 @@ +{ + "embed_dim": 512, + "vision_cfg": { + "image_size": 224, + "layers": 12, + "width": 768, + "patch_size": 32, + "attentional_pool": true, + "attn_pooler_heads": 8, + "output_tokens": true + }, + "text_cfg": { + "context_length": 76, + "vocab_size": 49408, + "width": 512, + "heads": 8, + "layers": 12, + "embed_cls": true, + "output_tokens": true + }, + "multimodal_cfg": { + "context_length": 76, + "vocab_size": 49408, + "width": 512, + "heads": 8, + "layers": 12, + "attn_pooler_heads": 8 + }, + "custom_text": true +} \ No newline at end of file diff --git a/utils/model_configs/coca_ViT-L-14.json b/utils/model_configs/coca_ViT-L-14.json new file mode 100644 index 0000000000000000000000000000000000000000..3d5ca4ca2338540f06852df5ff35ea6277e64555 --- /dev/null +++ b/utils/model_configs/coca_ViT-L-14.json @@ -0,0 +1,30 @@ +{ + "embed_dim": 768, + "vision_cfg": { + "image_size": 224, + "layers": 24, + "width": 1024, + "patch_size": 14, + "attentional_pool": true, + "attn_pooler_heads": 8, + "output_tokens": true + }, + "text_cfg": { + "context_length": 76, + "vocab_size": 49408, + "width": 768, + "heads": 12, + "layers": 12, + "embed_cls": true, + "output_tokens": true + }, + "multimodal_cfg": { + "context_length": 76, + "vocab_size": 49408, + "width": 768, + "heads": 12, + "layers": 12, + "attn_pooler_heads": 12 + }, + "custom_text": true +} diff --git a/utils/model_configs/coca_base.json b/utils/model_configs/coca_base.json new file mode 100644 index 0000000000000000000000000000000000000000..cf8c6cecb78a49d7e7140145a0307cbd561077c2 --- /dev/null +++ b/utils/model_configs/coca_base.json @@ -0,0 +1,31 @@ +{ + "embed_dim": 512, + "multimodal_cfg": { + "width": 768, + "context_length": 76, + "vocab_size": 64000, + "mlp_ratio": 4, + "layers": 12, + "dim_head": 64, + "heads": 12, + "n_queries": 256, + "attn_pooler_heads": 8 + }, + "vision_cfg": { + "image_size": 288, + "layers": 12, + "width": 768, + "patch_size": 18, + "output_tokens": true + }, + "text_cfg": { + "context_length": 76, + "vocab_size": 64000, + "layers": 12, + "heads": 12, + "width": 768, + "embed_cls": true, + "output_tokens": true + }, + "custom_text": true +} \ No newline at end of file diff --git a/utils/model_configs/coca_roberta-ViT-B-32.json b/utils/model_configs/coca_roberta-ViT-B-32.json new file mode 100644 index 0000000000000000000000000000000000000000..fb46354b95a17a46d7fcfd9d504e917ee6c1608c --- /dev/null +++ b/utils/model_configs/coca_roberta-ViT-B-32.json @@ -0,0 +1,24 @@ +{ + "embed_dim": 512, + "vision_cfg": { + "image_size": 224, + "layers": 12, + "width": 768, + "patch_size": 32, + "output_tokens": true + }, + "text_cfg": { + "hf_model_name": "roberta-base", + "hf_tokenizer_name": "roberta-base", + "proj": "linear", + "width": 768, + "output_tokens": true + }, + "multimodal_cfg": { + "context_length": 76, + "width": 768, + "heads": 8, + "layers": 12 + }, + "custom_text": true +} diff --git a/utils/model_configs/mt5-base-ViT-B-32.json b/utils/model_configs/mt5-base-ViT-B-32.json new file mode 100644 index 0000000000000000000000000000000000000000..58cad89cf0f446bbe15e4e25b1ac43424a828017 --- /dev/null +++ b/utils/model_configs/mt5-base-ViT-B-32.json @@ -0,0 +1,15 @@ +{ + "embed_dim": 512, + "vision_cfg": { + "image_size": 224, + "layers": 12, + "width": 768, + "patch_size": 32 + }, + "text_cfg": { + "hf_model_name": "google/mt5-base", + "hf_tokenizer_name": "google/mt5-base", + "proj": "mlp", + "pooler_type": "mean_pooler" + } +} diff --git a/utils/model_configs/mt5-xl-ViT-H-14.json b/utils/model_configs/mt5-xl-ViT-H-14.json new file mode 100644 index 0000000000000000000000000000000000000000..b432810777ba7269dbb0e89edfe65cdd27e7d255 --- /dev/null +++ b/utils/model_configs/mt5-xl-ViT-H-14.json @@ -0,0 +1,16 @@ +{ + "embed_dim": 1024, + "vision_cfg": { + "image_size": 224, + "layers": 32, + "width": 1280, + "head_width": 80, + "patch_size": 14 + }, + "text_cfg": { + "hf_model_name": "google/mt5-xl", + "hf_tokenizer_name": "google/mt5-xl", + "proj": "mlp", + "pooler_type": "mean_pooler" + } +} diff --git a/utils/model_configs/roberta-ViT-B-32.json b/utils/model_configs/roberta-ViT-B-32.json new file mode 100644 index 0000000000000000000000000000000000000000..ed687d472a73bb2ac96025f355f80437ab14c260 --- /dev/null +++ b/utils/model_configs/roberta-ViT-B-32.json @@ -0,0 +1,16 @@ +{ + "embed_dim": 512, + "quick_gelu": true, + "vision_cfg": { + "image_size": 224, + "layers": 12, + "width": 768, + "patch_size": 32 + }, + "text_cfg": { + "hf_model_name": "roberta-base", + "hf_tokenizer_name": "roberta-base", + "proj": "mlp", + "pooler_type": "mean_pooler" + } +} diff --git a/utils/model_configs/swin_base_patch4_window7_224.json b/utils/model_configs/swin_base_patch4_window7_224.json new file mode 100644 index 0000000000000000000000000000000000000000..bd6820f0cf2aa655e0a2723287f4b78895a58e6a --- /dev/null +++ b/utils/model_configs/swin_base_patch4_window7_224.json @@ -0,0 +1,17 @@ +{ + "embed_dim": 640, + "vision_cfg": { + "timm_model_name": "swin_base_patch4_window7_224", + "timm_model_pretrained": false, + "timm_pool": "", + "timm_proj": "linear", + "image_size": 224 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 640, + "heads": 10, + "layers": 12 + } +} \ No newline at end of file diff --git a/utils/model_configs/vit_medium_patch16_gap_256.json b/utils/model_configs/vit_medium_patch16_gap_256.json new file mode 100644 index 0000000000000000000000000000000000000000..8843eaf08cad16c3e7b5f496fd650715c9573f65 --- /dev/null +++ b/utils/model_configs/vit_medium_patch16_gap_256.json @@ -0,0 +1,17 @@ +{ + "embed_dim": 512, + "vision_cfg": { + "timm_model_name": "vit_medium_patch16_gap_256", + "timm_model_pretrained": false, + "timm_pool": "", + "timm_proj": "linear", + "image_size": 256 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 512, + "heads": 8, + "layers": 12 + } +} \ No newline at end of file diff --git a/utils/model_configs/vit_relpos_medium_patch16_cls_224.json b/utils/model_configs/vit_relpos_medium_patch16_cls_224.json new file mode 100644 index 0000000000000000000000000000000000000000..ed217b202d5e6071c5307f4547c97ff4cfe2abd1 --- /dev/null +++ b/utils/model_configs/vit_relpos_medium_patch16_cls_224.json @@ -0,0 +1,17 @@ +{ + "embed_dim": 512, + "vision_cfg": { + "timm_model_name": "vit_relpos_medium_patch16_cls_224", + "timm_model_pretrained": false, + "timm_pool": "", + "timm_proj": "linear", + "image_size": 224 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 512, + "heads": 8, + "layers": 12 + } +} \ No newline at end of file diff --git a/utils/model_configs/xlm-roberta-base-ViT-B-32.json b/utils/model_configs/xlm-roberta-base-ViT-B-32.json new file mode 100644 index 0000000000000000000000000000000000000000..751bccc2c6fc41bc4ff20182de88d86739d518d9 --- /dev/null +++ b/utils/model_configs/xlm-roberta-base-ViT-B-32.json @@ -0,0 +1,15 @@ +{ + "embed_dim": 512, + "vision_cfg": { + "image_size": 224, + "layers": 12, + "width": 768, + "patch_size": 32 + }, + "text_cfg": { + "hf_model_name": "xlm-roberta-base", + "hf_tokenizer_name": "xlm-roberta-base", + "proj": "mlp", + "pooler_type": "mean_pooler" + } +} diff --git a/utils/model_configs/xlm-roberta-large-ViT-H-14.json b/utils/model_configs/xlm-roberta-large-ViT-H-14.json new file mode 100644 index 0000000000000000000000000000000000000000..31f271faa9bbb7a9da53900b483a4c00a16f3c4a --- /dev/null +++ b/utils/model_configs/xlm-roberta-large-ViT-H-14.json @@ -0,0 +1,16 @@ +{ + "embed_dim": 1024, + "vision_cfg": { + "image_size": 224, + "layers": 32, + "width": 1280, + "head_width": 80, + "patch_size": 14 + }, + "text_cfg": { + "hf_model_name": "xlm-roberta-large", + "hf_tokenizer_name": "xlm-roberta-large", + "proj": "mlp", + "pooler_type": "mean_pooler" + } +} diff --git a/utils/modified_resnet.py b/utils/modified_resnet.py new file mode 100644 index 0000000000000000000000000000000000000000..3e220c232a464754d55ac8a49bd868b8fbb40153 --- /dev/null +++ b/utils/modified_resnet.py @@ -0,0 +1,181 @@ +from collections import OrderedDict + +import torch +from torch import nn +from torch.nn import functional as F + +from utils.misc import freeze_batch_norm_2d + + +class Bottleneck(nn.Module): + expansion = 4 + + def __init__(self, inplanes, planes, stride=1): + super().__init__() + + # all conv layers have stride 1. an avgpool is performed after the second convolution when stride > 1 + self.conv1 = nn.Conv2d(inplanes, planes, 1, bias=False) + self.bn1 = nn.BatchNorm2d(planes) + self.act1 = nn.ReLU(inplace=True) + + self.conv2 = nn.Conv2d(planes, planes, 3, padding=1, bias=False) + self.bn2 = nn.BatchNorm2d(planes) + self.act2 = nn.ReLU(inplace=True) + + self.avgpool = nn.AvgPool2d(stride) if stride > 1 else nn.Identity() + + self.conv3 = nn.Conv2d(planes, planes * self.expansion, 1, bias=False) + self.bn3 = nn.BatchNorm2d(planes * self.expansion) + self.act3 = nn.ReLU(inplace=True) + + self.downsample = None + self.stride = stride + + if stride > 1 or inplanes != planes * Bottleneck.expansion: + # downsampling layer is prepended with an avgpool, and the subsequent convolution has stride 1 + self.downsample = nn.Sequential(OrderedDict([ + ("-1", nn.AvgPool2d(stride)), + ("0", nn.Conv2d(inplanes, planes * self.expansion, 1, stride=1, bias=False)), + ("1", nn.BatchNorm2d(planes * self.expansion)) + ])) + + def forward(self, x: torch.Tensor): + identity = x + + out = self.act1(self.bn1(self.conv1(x))) + out = self.act2(self.bn2(self.conv2(out))) + out = self.avgpool(out) + out = self.bn3(self.conv3(out)) + + if self.downsample is not None: + identity = self.downsample(x) + + out += identity + out = self.act3(out) + return out + + +class AttentionPool2d(nn.Module): + def __init__(self, spacial_dim: int, embed_dim: int, num_heads: int, output_dim: int = None): + super().__init__() + self.positional_embedding = nn.Parameter(torch.randn(spacial_dim ** 2 + 1, embed_dim) / embed_dim ** 0.5) + self.k_proj = nn.Linear(embed_dim, embed_dim) + self.q_proj = nn.Linear(embed_dim, embed_dim) + self.v_proj = nn.Linear(embed_dim, embed_dim) + self.c_proj = nn.Linear(embed_dim, output_dim or embed_dim) + self.num_heads = num_heads + + def forward(self, x): + x = x.reshape(x.shape[0], x.shape[1], x.shape[2] * x.shape[3]).permute(2, 0, 1) # NCHW -> (HW)NC + x = torch.cat([x.mean(dim=0, keepdim=True), x], dim=0) # (HW+1)NC + x = x + self.positional_embedding[:, None, :].to(x.dtype) # (HW+1)NC + x, _ = F.multi_head_attention_forward( + query=x, key=x, value=x, + embed_dim_to_check=x.shape[-1], + num_heads=self.num_heads, + q_proj_weight=self.q_proj.weight, + k_proj_weight=self.k_proj.weight, + v_proj_weight=self.v_proj.weight, + in_proj_weight=None, + in_proj_bias=torch.cat([self.q_proj.bias, self.k_proj.bias, self.v_proj.bias]), + bias_k=None, + bias_v=None, + add_zero_attn=False, + dropout_p=0., + out_proj_weight=self.c_proj.weight, + out_proj_bias=self.c_proj.bias, + use_separate_proj_weight=True, + training=self.training, + need_weights=False + ) + + return x[0] + + +class ModifiedResNet(nn.Module): + """ + A ResNet class that is similar to torchvision's but contains the following changes: + - There are now 3 "stem" convolutions as opposed to 1, with an average pool instead of a max pool. + - Performs anti-aliasing strided convolutions, where an avgpool is prepended to convolutions with stride > 1 + - The final pooling layer is a QKV attention instead of an average pool + """ + + def __init__(self, layers, output_dim, heads, image_size=224, width=64): + super().__init__() + self.output_dim = output_dim + self.image_size = image_size + + # the 3-layer stem + self.conv1 = nn.Conv2d(3, width // 2, kernel_size=3, stride=2, padding=1, bias=False) + self.bn1 = nn.BatchNorm2d(width // 2) + self.act1 = nn.ReLU(inplace=True) + self.conv2 = nn.Conv2d(width // 2, width // 2, kernel_size=3, padding=1, bias=False) + self.bn2 = nn.BatchNorm2d(width // 2) + self.act2 = nn.ReLU(inplace=True) + self.conv3 = nn.Conv2d(width // 2, width, kernel_size=3, padding=1, bias=False) + self.bn3 = nn.BatchNorm2d(width) + self.act3 = nn.ReLU(inplace=True) + self.avgpool = nn.AvgPool2d(2) + + # residual layers + self._inplanes = width # this is a *mutable* variable used during construction + self.layer1 = self._make_layer(width, layers[0]) + self.layer2 = self._make_layer(width * 2, layers[1], stride=2) + self.layer3 = self._make_layer(width * 4, layers[2], stride=2) + self.layer4 = self._make_layer(width * 8, layers[3], stride=2) + + embed_dim = width * 32 # the ResNet feature dimension + self.attnpool = AttentionPool2d(image_size // 32, embed_dim, heads, output_dim) + + self.init_parameters() + + def _make_layer(self, planes, blocks, stride=1): + layers = [Bottleneck(self._inplanes, planes, stride)] + + self._inplanes = planes * Bottleneck.expansion + for _ in range(1, blocks): + layers.append(Bottleneck(self._inplanes, planes)) + + return nn.Sequential(*layers) + + def init_parameters(self): + if self.attnpool is not None: + std = self.attnpool.c_proj.in_features ** -0.5 + nn.init.normal_(self.attnpool.q_proj.weight, std=std) + nn.init.normal_(self.attnpool.k_proj.weight, std=std) + nn.init.normal_(self.attnpool.v_proj.weight, std=std) + nn.init.normal_(self.attnpool.c_proj.weight, std=std) + + for resnet_block in [self.layer1, self.layer2, self.layer3, self.layer4]: + for name, param in resnet_block.named_parameters(): + if name.endswith("bn3.weight"): + nn.init.zeros_(param) + + def lock(self, unlocked_groups=0, freeze_bn_stats=False): + assert unlocked_groups == 0, 'partial locking not currently supported for this model' + for param in self.parameters(): + param.requires_grad = False + if freeze_bn_stats: + freeze_batch_norm_2d(self) + + @torch.jit.ignore + def set_grad_checkpointing(self, enable=True): + # FIXME support for non-transformer + pass + + def stem(self, x): + x = self.act1(self.bn1(self.conv1(x))) + x = self.act2(self.bn2(self.conv2(x))) + x = self.act3(self.bn3(self.conv3(x))) + x = self.avgpool(x) + return x + + def forward(self, x): + x = self.stem(x) + x = self.layer1(x) + x = self.layer2(x) + x = self.layer3(x) + x = self.layer4(x) + x = self.attnpool(x) + + return x \ No newline at end of file diff --git a/utils/openai_models.py b/utils/openai_models.py new file mode 100644 index 0000000000000000000000000000000000000000..f87bd0b0272b66600f69905a2a53a1ab4bf38e72 --- /dev/null +++ b/utils/openai_models.py @@ -0,0 +1,90 @@ +""" OpenAI pretrained model functions + +Adapted from https://github.com/openai/CLIP. Originally MIT License, Copyright (c) 2021 OpenAI. +""" + +import os +import warnings +from typing import List, Optional, Union + +import torch + +from utils.constants import OPENAI_DATASET_MEAN, OPENAI_DATASET_STD +from utils.model import build_model_from_openai_state_dict, get_cast_dtype +from utils.pretrained import * + +__all__ = ["list_openai_models", "load_openai_model"] + + +def list_openai_models() -> List[str]: + """Returns the names of available CLIP models""" + return list_pretrained_models_by_tag('openai') + + +def load_openai_model( + name: str, + precision: Optional[str] = None, + device: Optional[Union[str, torch.device]] = None, + cache_dir: Optional[str] = None, +): + """Load a CLIP model + + Parameters + ---------- + name : str + A model name listed by `clip.available_models()`, or the path to a model checkpoint containing the state_dict + precision: str + Model precision, if None defaults to 'fp32' if device == 'cpu' else 'fp16'. + device : Union[str, torch.device] + The device to put the loaded model + cache_dir : Optional[str] + The directory to cache the downloaded model weights + + Returns + ------- + model : torch.nn.Module + The CLIP model + preprocess : Callable[[PIL.Image], torch.Tensor] + A torchvision transform that converts a PIL image into a tensor that the returned model can take as its input + """ + if device is None: + device = "cuda" if torch.cuda.is_available() else "cpu" + if precision is None: + precision = 'fp32' if device == 'cpu' else 'fp16' + + if get_pretrained_url(name, 'openai'): + model_path = download_pretrained_from_url(get_pretrained_url(name, 'openai'), cache_dir=cache_dir) + elif os.path.isfile(name): + model_path = name + else: + raise RuntimeError(f"Model {name} not found; available models = {list_openai_models()}") + + try: + # loading JIT archive + model = torch.jit.load(model_path, map_location="cpu").eval() + state_dict = None + except RuntimeError: + # loading saved state dict + state_dict = torch.load(model_path, map_location="cpu") + + # Build a non-jit model from the OpenAI jitted model state dict + cast_dtype = get_cast_dtype(precision) + try: + model = build_model_from_openai_state_dict(state_dict or model.state_dict(), cast_dtype=cast_dtype) + except KeyError: + sd = {k[7:]: v for k, v in state_dict["state_dict"].items()} + model = build_model_from_openai_state_dict(sd, cast_dtype=cast_dtype) + + # model from OpenAI state dict is in manually cast fp16 mode, must be converted for AMP/fp32/bf16 use + model = model.to(device) + # FIXME support pure fp16/bf16 precision modes + if precision != 'fp16': + model.float() + if precision == 'bf16': + # for bf16, convert back to low-precision + convert_weights_to_lp(model, dtype=torch.bfloat16) + + # add mean / std attributes for consistency with OpenCLIP models + model.visual.image_mean = OPENAI_DATASET_MEAN + model.visual.image_std = OPENAI_DATASET_STD + return model \ No newline at end of file diff --git a/utils/openai_templates.py b/utils/openai_templates.py new file mode 100644 index 0000000000000000000000000000000000000000..66d9faa9bd814967266c7edf41ccc258a182b1c7 --- /dev/null +++ b/utils/openai_templates.py @@ -0,0 +1,84 @@ + +OPENAI_IMAGENET_TEMPLATES = ( + lambda c: f'a bad photo of a {c}.', + lambda c: f'a photo of many {c}.', + lambda c: f'a sculpture of a {c}.', + lambda c: f'a photo of the hard to see {c}.', + lambda c: f'a low resolution photo of the {c}.', + lambda c: f'a rendering of a {c}.', + lambda c: f'graffiti of a {c}.', + lambda c: f'a bad photo of the {c}.', + lambda c: f'a cropped photo of the {c}.', + lambda c: f'a tattoo of a {c}.', + lambda c: f'the embroidered {c}.', + lambda c: f'a photo of a hard to see {c}.', + lambda c: f'a bright photo of a {c}.', + lambda c: f'a photo of a clean {c}.', + lambda c: f'a photo of a dirty {c}.', + lambda c: f'a dark photo of the {c}.', + lambda c: f'a drawing of a {c}.', + lambda c: f'a photo of my {c}.', + lambda c: f'the plastic {c}.', + lambda c: f'a photo of the cool {c}.', + lambda c: f'a close-up photo of a {c}.', + lambda c: f'a black and white photo of the {c}.', + lambda c: f'a painting of the {c}.', + lambda c: f'a painting of a {c}.', + lambda c: f'a pixelated photo of the {c}.', + lambda c: f'a sculpture of the {c}.', + lambda c: f'a bright photo of the {c}.', + lambda c: f'a cropped photo of a {c}.', + lambda c: f'a plastic {c}.', + lambda c: f'a photo of the dirty {c}.', + lambda c: f'a jpeg corrupted photo of a {c}.', + lambda c: f'a blurry photo of the {c}.', + lambda c: f'a photo of the {c}.', + lambda c: f'a good photo of the {c}.', + lambda c: f'a rendering of the {c}.', + lambda c: f'a {c} in a video game.', + lambda c: f'a photo of one {c}.', + lambda c: f'a doodle of a {c}.', + lambda c: f'a close-up photo of the {c}.', + lambda c: f'a photo of a {c}.', + lambda c: f'the origami {c}.', + lambda c: f'the {c} in a video game.', + lambda c: f'a sketch of a {c}.', + lambda c: f'a doodle of the {c}.', + lambda c: f'a origami {c}.', + lambda c: f'a low resolution photo of a {c}.', + lambda c: f'the toy {c}.', + lambda c: f'a rendition of the {c}.', + lambda c: f'a photo of the clean {c}.', + lambda c: f'a photo of a large {c}.', + lambda c: f'a rendition of a {c}.', + lambda c: f'a photo of a nice {c}.', + lambda c: f'a photo of a weird {c}.', + lambda c: f'a blurry photo of a {c}.', + lambda c: f'a cartoon {c}.', + lambda c: f'art of a {c}.', + lambda c: f'a sketch of the {c}.', + lambda c: f'a embroidered {c}.', + lambda c: f'a pixelated photo of a {c}.', + lambda c: f'itap of the {c}.', + lambda c: f'a jpeg corrupted photo of the {c}.', + lambda c: f'a good photo of a {c}.', + lambda c: f'a plushie {c}.', + lambda c: f'a photo of the nice {c}.', + lambda c: f'a photo of the small {c}.', + lambda c: f'a photo of the weird {c}.', + lambda c: f'the cartoon {c}.', + lambda c: f'art of the {c}.', + lambda c: f'a drawing of the {c}.', + lambda c: f'a photo of the large {c}.', + lambda c: f'a black and white photo of a {c}.', + lambda c: f'the plushie {c}.', + lambda c: f'a dark photo of a {c}.', + lambda c: f'itap of a {c}.', + lambda c: f'graffiti of the {c}.', + lambda c: f'a toy {c}.', + lambda c: f'itap of my {c}.', + lambda c: f'a photo of a cool {c}.', + lambda c: f'a photo of a small {c}.', + lambda c: f'a tattoo of the {c}.', +) + diff --git a/utils/pretrained.py b/utils/pretrained.py new file mode 100644 index 0000000000000000000000000000000000000000..48567fd1a46147c5c0c091a8731bd430042bd3cc --- /dev/null +++ b/utils/pretrained.py @@ -0,0 +1,426 @@ +import hashlib +import os +import urllib +import warnings +from functools import partial +from typing import Dict, Union + +from tqdm import tqdm + + +try: + from huggingface_hub import hf_hub_download + hf_hub_download = partial(hf_hub_download, library_name="open_clip", library_version='2.20.0') + _has_hf_hub = True +except ImportError: + hf_hub_download = None + _has_hf_hub = False + + +def _pcfg(url='', hf_hub='', mean=None, std=None): + return dict( + url=url, + hf_hub=hf_hub, + mean=mean, + std=std, + ) + + +_RN50 = dict( + openai=_pcfg( + "https://openaipublic.azureedge.net/clip/models/afeb0e10f9e5a86da6080e35cf09123aca3b358a0c3e3b6c78a7b63bc04b6762/RN50.pt"), + yfcc15m=_pcfg( + "https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/rn50-quickgelu-yfcc15m-455df137.pt"), + cc12m=_pcfg( + "https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/rn50-quickgelu-cc12m-f000538c.pt"), +) + +_RN50_quickgelu = dict( + openai=_pcfg( + "https://openaipublic.azureedge.net/clip/models/afeb0e10f9e5a86da6080e35cf09123aca3b358a0c3e3b6c78a7b63bc04b6762/RN50.pt"), + yfcc15m=_pcfg( + "https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/rn50-quickgelu-yfcc15m-455df137.pt"), + cc12m=_pcfg( + "https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/rn50-quickgelu-cc12m-f000538c.pt"), +) + +_RN101 = dict( + openai=_pcfg( + "https://openaipublic.azureedge.net/clip/models/8fa8567bab74a42d41c5915025a8e4538c3bdbe8804a470a72f30b0d94fab599/RN101.pt"), + yfcc15m=_pcfg( + "https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/rn101-quickgelu-yfcc15m-3e04b30e.pt"), +) + +_RN101_quickgelu = dict( + openai=_pcfg( + "https://openaipublic.azureedge.net/clip/models/8fa8567bab74a42d41c5915025a8e4538c3bdbe8804a470a72f30b0d94fab599/RN101.pt"), + yfcc15m=_pcfg( + "https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/rn101-quickgelu-yfcc15m-3e04b30e.pt"), +) + +_RN50x4 = dict( + openai=_pcfg( + "https://openaipublic.azureedge.net/clip/models/7e526bd135e493cef0776de27d5f42653e6b4c8bf9e0f653bb11773263205fdd/RN50x4.pt"), +) + +_RN50x16 = dict( + openai=_pcfg( + "https://openaipublic.azureedge.net/clip/models/52378b407f34354e150460fe41077663dd5b39c54cd0bfd2b27167a4a06ec9aa/RN50x16.pt"), +) + +_RN50x64 = dict( + openai=_pcfg( + "https://openaipublic.azureedge.net/clip/models/be1cfb55d75a9666199fb2206c106743da0f6468c9d327f3e0d0a543a9919d9c/RN50x64.pt"), +) + +_VITB32 = dict( + openai=_pcfg( + "https://openaipublic.azureedge.net/clip/models/40d365715913c9da98579312b702a82c18be219cc2a73407c4526f58eba950af/ViT-B-32.pt"), + laion400m_e31=_pcfg( + "https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/vit_b_32-quickgelu-laion400m_e31-d867053b.pt"), + laion400m_e32=_pcfg( + "https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/vit_b_32-quickgelu-laion400m_e32-46683a32.pt"), + laion2b_e16=_pcfg( + "https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/vit_b_32-laion2b_e16-af8dbd0c.pth"), + laion2b_s34b_b79k=_pcfg(hf_hub='laion/CLIP-ViT-B-32-laion2B-s34B-b79K/'), + # DataComp-M models + datacomp_m_s128m_b4k=_pcfg(hf_hub='laion/CLIP-ViT-B-32-DataComp.M-s128M-b4K/'), + commonpool_m_clip_s128m_b4k=_pcfg(hf_hub='laion/CLIP-ViT-B-32-CommonPool.M.clip-s128M-b4K/'), + commonpool_m_laion_s128m_b4k=_pcfg(hf_hub='laion/CLIP-ViT-B-32-CommonPool.M.laion-s128M-b4K/'), + commonpool_m_image_s128m_b4k=_pcfg(hf_hub='laion/CLIP-ViT-B-32-CommonPool.M.image-s128M-b4K/'), + commonpool_m_text_s128m_b4k=_pcfg(hf_hub='laion/CLIP-ViT-B-32-CommonPool.M.text-s128M-b4K/'), + commonpool_m_basic_s128m_b4k=_pcfg(hf_hub='laion/CLIP-ViT-B-32-CommonPool.M.basic-s128M-b4K/'), + commonpool_m_s128m_b4k=_pcfg(hf_hub='laion/CLIP-ViT-B-32-CommonPool.M-s128M-b4K/'), + # DataComp-S models + datacomp_s_s13m_b4k=_pcfg(hf_hub='laion/CLIP-ViT-B-32-DataComp.S-s13M-b4K/'), + commonpool_s_clip_s13m_b4k=_pcfg(hf_hub='laion/CLIP-ViT-B-32-CommonPool.S.clip-s13M-b4K/'), + commonpool_s_laion_s13m_b4k=_pcfg(hf_hub='laion/CLIP-ViT-B-32-CommonPool.S.laion-s13M-b4K/'), + commonpool_s_image_s13m_b4k=_pcfg(hf_hub='laion/CLIP-ViT-B-32-CommonPool.S.image-s13M-b4K/'), + commonpool_s_text_s13m_b4k=_pcfg(hf_hub='laion/CLIP-ViT-B-32-CommonPool.S.text-s13M-b4K/'), + commonpool_s_basic_s13m_b4k=_pcfg(hf_hub='laion/CLIP-ViT-B-32-CommonPool.S.basic-s13M-b4K/'), + commonpool_s_s13m_b4k=_pcfg(hf_hub='laion/CLIP-ViT-B-32-CommonPool.S-s13M-b4K/'), +) + +_VITB32_quickgelu = dict( + openai=_pcfg( + "https://openaipublic.azureedge.net/clip/models/40d365715913c9da98579312b702a82c18be219cc2a73407c4526f58eba950af/ViT-B-32.pt"), + laion400m_e31=_pcfg( + "https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/vit_b_32-quickgelu-laion400m_e31-d867053b.pt"), + laion400m_e32=_pcfg( + "https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/vit_b_32-quickgelu-laion400m_e32-46683a32.pt"), +) + +_VITB16 = dict( + openai=_pcfg( + "https://openaipublic.azureedge.net/clip/models/5806e77cd80f8b59890b7e101eabd078d9fb84e6937f9e85e4ecb61988df416f/ViT-B-16.pt"), + laion400m_e31=_pcfg( + "https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/vit_b_16-laion400m_e31-00efa78f.pt"), + laion400m_e32=_pcfg( + "https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/vit_b_16-laion400m_e32-55e67d44.pt"), + laion2b_s34b_b88k=_pcfg(hf_hub='laion/CLIP-ViT-B-16-laion2B-s34B-b88K/'), + # DataComp-L models + datacomp_l_s1b_b8k=_pcfg(hf_hub='laion/CLIP-ViT-B-16-DataComp.L-s1B-b8K/'), + commonpool_l_clip_s1b_b8k=_pcfg(hf_hub='laion/CLIP-ViT-B-16-CommonPool.L.clip-s1B-b8K/'), + commonpool_l_laion_s1b_b8k=_pcfg(hf_hub='laion/CLIP-ViT-B-16-CommonPool.L.laion-s1B-b8K/'), + commonpool_l_image_s1b_b8k=_pcfg(hf_hub='laion/CLIP-ViT-B-16-CommonPool.L.image-s1B-b8K/'), + commonpool_l_text_s1b_b8k=_pcfg(hf_hub='laion/CLIP-ViT-B-16-CommonPool.L.text-s1B-b8K/'), + commonpool_l_basic_s1b_b8k=_pcfg(hf_hub='laion/CLIP-ViT-B-16-CommonPool.L.basic-s1B-b8K/'), + commonpool_l_s1b_b8k=_pcfg(hf_hub='laion/CLIP-ViT-B-16-CommonPool.L-s1B-b8K/'), +) + +_VITB16_PLUS_240 = dict( + laion400m_e31=_pcfg( + "https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/vit_b_16_plus_240-laion400m_e31-8fb26589.pt"), + laion400m_e32=_pcfg( + "https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/vit_b_16_plus_240-laion400m_e32-699c4b84.pt"), +) + +_VITL14 = dict( + openai=_pcfg( + "https://openaipublic.azureedge.net/clip/models/b8cca3fd41ae0c99ba7e8951adf17d267cdb84cd88be6f7c2e0eca1737a03836/ViT-L-14.pt"), + laion400m_e31=_pcfg( + "https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/vit_l_14-laion400m_e31-69988bb6.pt"), + laion400m_e32=_pcfg( + "https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/vit_l_14-laion400m_e32-3d133497.pt"), + laion2b_s32b_b82k=_pcfg( + hf_hub='laion/CLIP-ViT-L-14-laion2B-s32B-b82K/', + mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5)), + # DataComp-XL models + datacomp_xl_s13b_b90k=_pcfg(hf_hub='laion/CLIP-ViT-L-14-DataComp.XL-s13B-b90K/'), + commonpool_xl_clip_s13b_b90k=_pcfg(hf_hub='laion/CLIP-ViT-L-14-CommonPool.XL.clip-s13B-b90K/'), + commonpool_xl_laion_s13b_b90k=_pcfg(hf_hub='laion/CLIP-ViT-L-14-CommonPool.XL.laion-s13B-b90K/'), + commonpool_xl_s13b_b90k=_pcfg(hf_hub='laion/CLIP-ViT-L-14-CommonPool.XL-s13B-b90K/'), +) + +_VITL14_336 = dict( + openai=_pcfg( + "https://openaipublic.azureedge.net/clip/models/3035c92b350959924f9f00213499208652fc7ea050643e8b385c2dac08641f02/ViT-L-14-336px.pt"), +) + +_VITH14 = dict( + laion2b_s32b_b79k=_pcfg(hf_hub='laion/CLIP-ViT-H-14-laion2B-s32B-b79K/'), +) + +_VITg14 = dict( + laion2b_s12b_b42k=_pcfg(hf_hub='laion/CLIP-ViT-g-14-laion2B-s12B-b42K/'), + laion2b_s34b_b88k=_pcfg(hf_hub='laion/CLIP-ViT-g-14-laion2B-s34B-b88K/'), +) + +_VITbigG14 = dict( + laion2b_s39b_b160k=_pcfg(hf_hub='laion/CLIP-ViT-bigG-14-laion2B-39B-b160k/'), +) + +_robertaViTB32 = dict( + laion2b_s12b_b32k=_pcfg(hf_hub='laion/CLIP-ViT-B-32-roberta-base-laion2B-s12B-b32k/'), +) + +_xlmRobertaBaseViTB32 = dict( + laion5b_s13b_b90k=_pcfg(hf_hub='laion/CLIP-ViT-B-32-xlm-roberta-base-laion5B-s13B-b90k/'), +) + +_xlmRobertaLargeFrozenViTH14 = dict( + frozen_laion5b_s13b_b90k=_pcfg(hf_hub='laion/CLIP-ViT-H-14-frozen-xlm-roberta-large-laion5B-s13B-b90k/'), +) + +_convnext_base = dict( + laion400m_s13b_b51k=_pcfg(hf_hub='laion/CLIP-convnext_base-laion400M-s13B-b51K/'), +) + +_convnext_base_w = dict( + laion2b_s13b_b82k=_pcfg(hf_hub='laion/CLIP-convnext_base_w-laion2B-s13B-b82K/'), + laion2b_s13b_b82k_augreg=_pcfg(hf_hub='laion/CLIP-convnext_base_w-laion2B-s13B-b82K-augreg/'), + laion_aesthetic_s13b_b82k=_pcfg(hf_hub='laion/CLIP-convnext_base_w-laion_aesthetic-s13B-b82K/'), +) + +_convnext_base_w_320 = dict( + laion_aesthetic_s13b_b82k=_pcfg(hf_hub='laion/CLIP-convnext_base_w_320-laion_aesthetic-s13B-b82K/'), + laion_aesthetic_s13b_b82k_augreg=_pcfg(hf_hub='laion/CLIP-convnext_base_w_320-laion_aesthetic-s13B-b82K-augreg/'), +) + +_convnext_large_d = dict( + laion2b_s26b_b102k_augreg=_pcfg(hf_hub='laion/CLIP-convnext_large_d.laion2B-s26B-b102K-augreg/'), +) + +_convnext_large_d_320 = dict( + laion2b_s29b_b131k_ft=_pcfg(hf_hub='laion/CLIP-convnext_large_d_320.laion2B-s29B-b131K-ft/'), + laion2b_s29b_b131k_ft_soup=_pcfg(hf_hub='laion/CLIP-convnext_large_d_320.laion2B-s29B-b131K-ft-soup/'), +) + +_convnext_xxlarge = dict( + laion2b_s34b_b82k_augreg=_pcfg(hf_hub='laion/CLIP-convnext_xxlarge-laion2B-s34B-b82K-augreg/'), + laion2b_s34b_b82k_augreg_rewind=_pcfg(hf_hub='laion/CLIP-convnext_xxlarge-laion2B-s34B-b82K-augreg-rewind/'), + laion2b_s34b_b82k_augreg_soup=_pcfg(hf_hub='laion/CLIP-convnext_xxlarge-laion2B-s34B-b82K-augreg-soup/'), +) + +_coca_VITB32 = dict( + laion2b_s13b_b90k=_pcfg(hf_hub='laion/CoCa-ViT-B-32-laion2B-s13B-b90k/'), + mscoco_finetuned_laion2b_s13b_b90k=_pcfg(hf_hub='laion/mscoco_finetuned_CoCa-ViT-B-32-laion2B-s13B-b90k/') +) + +_coca_VITL14 = dict( + laion2b_s13b_b90k=_pcfg(hf_hub='laion/CoCa-ViT-L-14-laion2B-s13B-b90k/'), + mscoco_finetuned_laion2b_s13b_b90k=_pcfg(hf_hub='laion/mscoco_finetuned_CoCa-ViT-L-14-laion2B-s13B-b90k/') +) + + +_PRETRAINED = { + "RN50": _RN50, + "RN50-quickgelu": _RN50_quickgelu, + "RN101": _RN101, + "RN101-quickgelu": _RN101_quickgelu, + "RN50x4": _RN50x4, + "RN50x16": _RN50x16, + "RN50x64": _RN50x64, + "ViT-B-32": _VITB32, + "ViT-B-32-quickgelu": _VITB32_quickgelu, + "ViT-B-16": _VITB16, + "ViT-B-16-plus-240": _VITB16_PLUS_240, + "ViT-L-14": _VITL14, + "ViT-L-14-336": _VITL14_336, + "ViT-H-14": _VITH14, + "ViT-g-14": _VITg14, + "ViT-bigG-14": _VITbigG14, + "roberta-ViT-B-32": _robertaViTB32, + "xlm-roberta-base-ViT-B-32": _xlmRobertaBaseViTB32, + "xlm-roberta-large-ViT-H-14": _xlmRobertaLargeFrozenViTH14, + "convnext_base": _convnext_base, + "convnext_base_w": _convnext_base_w, + "convnext_base_w_320": _convnext_base_w_320, + "convnext_large_d": _convnext_large_d, + "convnext_large_d_320": _convnext_large_d_320, + "convnext_xxlarge": _convnext_xxlarge, + "coca_ViT-B-32": _coca_VITB32, + "coca_ViT-L-14": _coca_VITL14, + "EVA01-g-14": dict( + # from QuanSun/EVA-CLIP/EVA01_CLIP_g_14_psz14_s11B.pt + laion400m_s11b_b41k=_pcfg(hf_hub='timm/eva_giant_patch14_clip_224.laion400m_s11b_b41k/'), + ), + "EVA01-g-14-plus": dict( + # from QuanSun/EVA-CLIP/EVA01_CLIP_g_14_plus_psz14_s11B.pt + merged2b_s11b_b114k=_pcfg(hf_hub='timm/eva_giant_patch14_plus_clip_224.merged2b_s11b_b114k/'), + ), + "EVA02-B-16": dict( + # from QuanSun/EVA-CLIP/EVA02_CLIP_B_psz16_s8B.pt + merged2b_s8b_b131k=_pcfg(hf_hub='timm/eva02_base_patch16_clip_224.merged2b_s8b_b131k/'), + ), + "EVA02-L-14": dict( + # from QuanSun/EVA-CLIP/EVA02_CLIP_L_psz14_s4B.pt + merged2b_s4b_b131k=_pcfg(hf_hub='timm/eva02_large_patch14_clip_224.merged2b_s4b_b131k/'), + ), + "EVA02-L-14-336": dict( + # from QuanSun/EVA-CLIP/EVA02_CLIP_L_336_psz14_s6B.pt + merged2b_s6b_b61k=_pcfg(hf_hub='timm/eva02_large_patch14_clip_336.merged2b_s6b_b61k/'), + ), + "EVA02-E-14": dict( + # from QuanSun/EVA-CLIP/EVA02_CLIP_E_psz14_s4B.pt + laion2b_s4b_b115k=_pcfg(hf_hub='timm/eva02_enormous_patch14_clip_224.laion2b_s4b_b115k/'), + ), + "EVA02-E-14-plus": dict( + # from QuanSun/EVA-CLIP/EVA02_CLIP_E_psz14_plus_s9B.pt + laion2b_s9b_b144k=_pcfg(hf_hub='timm/eva02_enormous_patch14_plus_clip_224.laion2b_s9b_b144k/'), + ) +} + + +def _clean_tag(tag: str): + # normalize pretrained tags + return tag.lower().replace('-', '_') + + +def list_pretrained(as_str: bool = False): + """ returns list of pretrained models + Returns a tuple (model_name, pretrain_tag) by default or 'name:tag' if as_str == True + """ + return [':'.join([k, t]) if as_str else (k, t) for k in _PRETRAINED.keys() for t in _PRETRAINED[k].keys()] + + +def list_pretrained_models_by_tag(tag: str): + """ return all models having the specified pretrain tag """ + models = [] + tag = _clean_tag(tag) + for k in _PRETRAINED.keys(): + if tag in _PRETRAINED[k]: + models.append(k) + return models + + +def list_pretrained_tags_by_model(model: str): + """ return all pretrain tags for the specified model architecture """ + tags = [] + if model in _PRETRAINED: + tags.extend(_PRETRAINED[model].keys()) + return tags + + +def is_pretrained_cfg(model: str, tag: str): + if model not in _PRETRAINED: + return False + return _clean_tag(tag) in _PRETRAINED[model] + + +def get_pretrained_cfg(model: str, tag: str): + if model not in _PRETRAINED: + return {} + model_pretrained = _PRETRAINED[model] + return model_pretrained.get(_clean_tag(tag), {}) + + +def get_pretrained_url(model: str, tag: str): + cfg = get_pretrained_cfg(model, _clean_tag(tag)) + return cfg.get('url', '') + + +def download_pretrained_from_url( + url: str, + cache_dir: Union[str, None] = None, +): + if not cache_dir: + cache_dir = os.path.expanduser("~/.cache/clip") + os.makedirs(cache_dir, exist_ok=True) + filename = os.path.basename(url) + + if 'openaipublic' in url: + expected_sha256 = url.split("/")[-2] + elif 'mlfoundations' in url: + expected_sha256 = os.path.splitext(filename)[0].split("-")[-1] + else: + expected_sha256 = '' + + download_target = os.path.join(cache_dir, filename) + + if os.path.exists(download_target) and not os.path.isfile(download_target): + raise RuntimeError(f"{download_target} exists and is not a regular file") + + if os.path.isfile(download_target): + if expected_sha256: + if hashlib.sha256(open(download_target, "rb").read()).hexdigest().startswith(expected_sha256): + return download_target + else: + warnings.warn(f"{download_target} exists, but the SHA256 checksum does not match; re-downloading the file") + else: + return download_target + + with urllib.request.urlopen(url) as source, open(download_target, "wb") as output: + with tqdm(total=int(source.headers.get("Content-Length")), ncols=80, unit='iB', unit_scale=True) as loop: + while True: + buffer = source.read(8192) + if not buffer: + break + + output.write(buffer) + loop.update(len(buffer)) + + if expected_sha256 and not hashlib.sha256(open(download_target, "rb").read()).hexdigest().startswith(expected_sha256): + raise RuntimeError(f"Model has been downloaded but the SHA256 checksum does not not match") + + return download_target + + +def has_hf_hub(necessary=False): + if not _has_hf_hub and necessary: + # if no HF Hub module installed, and it is necessary to continue, raise error + raise RuntimeError( + 'Hugging Face hub model specified but package not installed. Run `pip install huggingface_hub`.') + return _has_hf_hub + + +def download_pretrained_from_hf( + model_id: str, + filename: str = 'open_clip_pytorch_model.bin', + revision=None, + cache_dir: Union[str, None] = None, +): + has_hf_hub(True) + cached_file = hf_hub_download(model_id, filename, revision=revision, cache_dir=cache_dir) + return cached_file + + +def download_pretrained( + cfg: Dict, + force_hf_hub: bool = False, + cache_dir: Union[str, None] = None, +): + target = '' + if not cfg: + return target + + download_url = cfg.get('url', '') + download_hf_hub = cfg.get('hf_hub', '') + if download_hf_hub and force_hf_hub: + # use HF hub even if url exists + download_url = '' + + if download_url: + target = download_pretrained_from_url(download_url, cache_dir=cache_dir) + elif download_hf_hub: + has_hf_hub(True) + # we assume the hf_hub entries in pretrained config combine model_id + filename in + # 'org/model_name/filename.pt' form. To specify just the model id w/o filename and + # use 'open_clip_pytorch_model.bin' default, there must be a trailing slash 'org/model_name/'. + model_id, filename = os.path.split(download_hf_hub) + if filename: + target = download_pretrained_from_hf(model_id, filename=filename, cache_dir=cache_dir) + else: + target = download_pretrained_from_hf(model_id, cache_dir=cache_dir) + + return target \ No newline at end of file diff --git a/utils/segmentation_utils.py b/utils/segmentation_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..e286e0a4d3255952ef2d501b6ac8571cd72cb7f6 --- /dev/null +++ b/utils/segmentation_utils.py @@ -0,0 +1,682 @@ +import torch +import matplotlib.cm +import skimage.io +import skimage.feature +import skimage.filters +import numpy as np +import os +from collections import OrderedDict +import glob +from sklearn.metrics import f1_score, average_precision_score +from sklearn.metrics import precision_recall_curve, roc_curve + +SMOOTH = 1e-6 + + +def get_iou(outputs: torch.Tensor, labels: torch.Tensor): + # You can comment out this line if you are passing tensors of equal shape + # But if you are passing output from UNet or something it will most probably + # be with the BATCH x 1 x H x W shape + outputs = outputs.squeeze(1) # BATCH x 1 x H x W => BATCH x H x W + labels = labels.squeeze(1) # BATCH x 1 x H x W => BATCH x H x W + + intersection = (outputs & labels).float().sum((1, 2)) # Will be zero if Truth=0 or Prediction=0 + union = (outputs | labels).float().sum((1, 2)) # Will be zzero if both are 0 + + iou = (intersection + SMOOTH) / (union + SMOOTH) # We smooth our devision to avoid 0/0 + + return iou.cpu().numpy() + + +def get_f1_scores(predict, target, ignore_index=-1): + # Tensor process + batch_size = predict.shape[0] + predict = predict.data.cpu().numpy().reshape(-1) + target = target.data.cpu().numpy().reshape(-1) + pb = predict[target != ignore_index].reshape(batch_size, -1) + tb = target[target != ignore_index].reshape(batch_size, -1) + + total = [] + for p, t in zip(pb, tb): + total.append(np.nan_to_num(f1_score(t, p))) + + return total + + +def get_roc(predict, target, ignore_index=-1): + target_expand = target.unsqueeze(1).expand_as(predict) + target_expand_numpy = target_expand.data.cpu().numpy().reshape(-1) + # Tensor process + x = torch.zeros_like(target_expand) + t = target.unsqueeze(1).clamp(min=0) + target_1hot = x.scatter_(1, t, 1) + batch_size = predict.shape[0] + predict = predict.data.cpu().numpy().reshape(-1) + target = target_1hot.data.cpu().numpy().reshape(-1) + pb = predict[target_expand_numpy != ignore_index].reshape(batch_size, -1) + tb = target[target_expand_numpy != ignore_index].reshape(batch_size, -1) + + total = [] + for p, t in zip(pb, tb): + total.append(roc_curve(t, p)) + + return total + + +def get_pr(predict, target, ignore_index=-1): + target_expand = target.unsqueeze(1).expand_as(predict) + target_expand_numpy = target_expand.data.cpu().numpy().reshape(-1) + # Tensor process + x = torch.zeros_like(target_expand) + t = target.unsqueeze(1).clamp(min=0) + target_1hot = x.scatter_(1, t, 1) + batch_size = predict.shape[0] + predict = predict.data.cpu().numpy().reshape(-1) + target = target_1hot.data.cpu().numpy().reshape(-1) + pb = predict[target_expand_numpy != ignore_index].reshape(batch_size, -1) + tb = target[target_expand_numpy != ignore_index].reshape(batch_size, -1) + + total = [] + for p, t in zip(pb, tb): + total.append(precision_recall_curve(t, p)) + + return total + + +def get_ap_scores(predict, target, ignore_index=-1): + total = [] + for pred, tgt in zip(predict, target): + target_expand = tgt.unsqueeze(0).expand_as(pred) + target_expand_numpy = target_expand.data.cpu().numpy().reshape(-1) + + # Tensor process + x = torch.zeros_like(target_expand) + t = tgt.unsqueeze(0).clamp(min=0).long() + target_1hot = x.scatter_(0, t, 1) + predict_flat = pred.data.cpu().numpy().reshape(-1) + target_flat = target_1hot.data.cpu().numpy().reshape(-1) + + p = predict_flat[target_expand_numpy != ignore_index] + t = target_flat[target_expand_numpy != ignore_index] + + total.append(np.nan_to_num(average_precision_score(t, p))) + + return total + + +def get_ap_multiclass(predict, target): + total = [] + for pred, tgt in zip(predict, target): + predict_flat = pred.data.cpu().numpy().reshape(-1) + target_flat = tgt.data.cpu().numpy().reshape(-1) + + total.append(np.nan_to_num(average_precision_score(target_flat, predict_flat))) + + return total + + +def batch_precision_recall(predict, target, thr=0.5): + """Batch Precision Recall + Args: + predict: input 4D tensor + target: label 4D tensor + """ + # _, predict = torch.max(predict, 1) + + predict = predict > thr + predict = predict.data.cpu().numpy() + 1 + target = target.data.cpu().numpy() + 1 + + tp = np.sum(((predict == 2) * (target == 2)) * (target > 0)) + fp = np.sum(((predict == 2) * (target == 1)) * (target > 0)) + fn = np.sum(((predict == 1) * (target == 2)) * (target > 0)) + + precision = float(np.nan_to_num(tp / (tp + fp))) + recall = float(np.nan_to_num(tp / (tp + fn))) + + return precision, recall + + +def batch_pix_accuracy(predict, target): + """Batch Pixel Accuracy + Args: + predict: input 3D tensor + target: label 3D tensor + """ + + # for thr in np.linspace(0, 1, slices): + + _, predict = torch.max(predict, 0) + predict = predict.cpu().numpy() + 1 + target = target.cpu().numpy() + 1 + pixel_labeled = np.sum(target > 0) + pixel_correct = np.sum((predict == target) * (target > 0)) + assert pixel_correct <= pixel_labeled, \ + "Correct area should be smaller than Labeled" + return pixel_correct, pixel_labeled + + +def batch_intersection_union(predict, target, nclass): + """Batch Intersection of Union + Args: + predict: input 3D tensor + target: label 3D tensor + nclass: number of categories (int) + """ + _, predict = torch.max(predict, 0) + mini = 1 + maxi = nclass + nbins = nclass + predict = predict.cpu().numpy() + 1 + target = target.cpu().numpy() + 1 + + predict = predict * (target > 0).astype(predict.dtype) + intersection = predict * (predict == target) + # areas of intersection and union + area_inter, _ = np.histogram(intersection, bins=nbins, range=(mini, maxi)) + area_pred, _ = np.histogram(predict, bins=nbins, range=(mini, maxi)) + area_lab, _ = np.histogram(target, bins=nbins, range=(mini, maxi)) + area_union = area_pred + area_lab - area_inter + assert (area_inter <= area_union).all(), \ + "Intersection area should be smaller than Union area" + return area_inter, area_union + + +def pixel_accuracy(im_pred, im_lab): + # ref https://github.com/CSAILVision/sceneparsing/blob/master/evaluationCode/utils_eval.py + im_pred = np.asarray(im_pred) + im_lab = np.asarray(im_lab) + + # Remove classes from unlabeled pixels in gt image. + # We should not penalize detections in unlabeled portions of the image. + pixel_labeled = np.sum(im_lab > 0) + pixel_correct = np.sum((im_pred == im_lab) * (im_lab > 0)) + # pixel_accuracy = 1.0 * pixel_correct / pixel_labeled + return pixel_correct, pixel_labeled + + +def intersection_and_union(im_pred, im_lab, num_class): + im_pred = np.asarray(im_pred) + im_lab = np.asarray(im_lab) + # Remove classes from unlabeled pixels in gt image. + im_pred = im_pred * (im_lab > 0) + # Compute area intersection: + intersection = im_pred * (im_pred == im_lab) + area_inter, _ = np.histogram(intersection, bins=num_class - 1, + range=(1, num_class - 1)) + # Compute area union: + area_pred, _ = np.histogram(im_pred, bins=num_class - 1, + range=(1, num_class - 1)) + area_lab, _ = np.histogram(im_lab, bins=num_class - 1, + range=(1, num_class - 1)) + area_union = area_pred + area_lab - area_inter + return area_inter, area_union + + +class Saver(object): + def __init__(self, args): + self.args = args + self.directory = os.path.join('run', args.train_dataset, args.model) + self.runs = sorted(glob.glob(os.path.join(self.directory, 'experiment_*'))) + run_id = int(self.runs[-1].split('_')[-1]) + 1 if self.runs else 0 + + self.experiment_dir = os.path.join(self.directory, 'experiment_{}'.format(str(run_id))) + if not os.path.exists(self.experiment_dir): + os.makedirs(self.experiment_dir) + + def save_checkpoint(self, state, filename='checkpoint.pth.tar'): + """Saves checkpoint to disk""" + filename = os.path.join(self.experiment_dir, filename) + torch.save(state, filename) + + def save_experiment_config(self): + logfile = os.path.join(self.experiment_dir, 'parameters.txt') + log_file = open(logfile, 'w') + p = OrderedDict() + p['train_dataset'] = self.args.train_dataset + p['lr'] = self.args.lr + p['epoch'] = self.args.epochs + + for key, val in p.items(): + log_file.write(key + ':' + str(val) + '\n') + log_file.close() + + +class Metric(object): + """Base class for all metrics. + From: https://github.com/pytorch/tnt/blob/master/torchnet/meter/meter.py + """ + def reset(self): + pass + + def add(self): + pass + + def value(self): + pass + + +class ConfusionMatrix(Metric): + """Constructs a confusion matrix for a multi-class classification problems. + Does not support multi-label, multi-class problems. + Keyword arguments: + - num_classes (int): number of classes in the classification problem. + - normalized (boolean, optional): Determines whether or not the confusion + matrix is normalized or not. Default: False. + Modified from: https://github.com/pytorch/tnt/blob/master/torchnet/meter/confusionmeter.py + """ + + def __init__(self, num_classes, normalized=False): + super().__init__() + + self.conf = np.ndarray((num_classes, num_classes), dtype=np.int32) + self.normalized = normalized + self.num_classes = num_classes + self.reset() + + def reset(self): + self.conf.fill(0) + + def add(self, predicted, target): + """Computes the confusion matrix + The shape of the confusion matrix is K x K, where K is the number + of classes. + Keyword arguments: + - predicted (Tensor or numpy.ndarray): Can be an N x K tensor/array of + predicted scores obtained from the model for N examples and K classes, + or an N-tensor/array of integer values between 0 and K-1. + - target (Tensor or numpy.ndarray): Can be an N x K tensor/array of + ground-truth classes for N examples and K classes, or an N-tensor/array + of integer values between 0 and K-1. + """ + # If target and/or predicted are tensors, convert them to numpy arrays + if torch.is_tensor(predicted): + predicted = predicted.cpu().numpy() + if torch.is_tensor(target): + target = target.cpu().numpy() + + assert predicted.shape[0] == target.shape[0], \ + 'number of targets and predicted outputs do not match' + + if np.ndim(predicted) != 1: + assert predicted.shape[1] == self.num_classes, \ + 'number of predictions does not match size of confusion matrix' + predicted = np.argmax(predicted, 1) + else: + assert (predicted.max() < self.num_classes) and (predicted.min() >= 0), \ + 'predicted values are not between 0 and k-1' + + if np.ndim(target) != 1: + assert target.shape[1] == self.num_classes, \ + 'Onehot target does not match size of confusion matrix' + assert (target >= 0).all() and (target <= 1).all(), \ + 'in one-hot encoding, target values should be 0 or 1' + assert (target.sum(1) == 1).all(), \ + 'multi-label setting is not supported' + target = np.argmax(target, 1) + else: + assert (target.max() < self.num_classes) and (target.min() >= 0), \ + 'target values are not between 0 and k-1' + + # hack for bincounting 2 arrays together + x = predicted + self.num_classes * target + bincount_2d = np.bincount( + x.astype(np.int32), minlength=self.num_classes**2) + assert bincount_2d.size == self.num_classes**2 + conf = bincount_2d.reshape((self.num_classes, self.num_classes)) + + self.conf += conf + + def value(self): + """ + Returns: + Confustion matrix of K rows and K columns, where rows corresponds + to ground-truth targets and columns corresponds to predicted + targets. + """ + if self.normalized: + conf = self.conf.astype(np.float32) + return conf / conf.sum(1).clip(min=1e-12)[:, None] + else: + return self.conf + + +def vec2im(V, shape=()): + ''' + Transform an array V into a specified shape - or if no shape is given assume a square output format. + + Parameters + ---------- + + V : numpy.ndarray + an array either representing a matrix or vector to be reshaped into an two-dimensional image + + shape : tuple or list + optional. containing the shape information for the output array if not given, the output is assumed to be square + + Returns + ------- + + W : numpy.ndarray + with W.shape = shape or W.shape = [np.sqrt(V.size)]*2 + + ''' + + if len(shape) < 2: + shape = [np.sqrt(V.size)] * 2 + shape = map(int, shape) + return np.reshape(V, shape) + + +def enlarge_image(img, scaling=3): + ''' + Enlarges a given input matrix by replicating each pixel value scaling times in horizontal and vertical direction. + + Parameters + ---------- + + img : numpy.ndarray + array of shape [H x W] OR [H x W x D] + + scaling : int + positive integer value > 0 + + Returns + ------- + + out : numpy.ndarray + two-dimensional array of shape [scaling*H x scaling*W] + OR + three-dimensional array of shape [scaling*H x scaling*W x D] + depending on the dimensionality of the input + ''' + + if scaling < 1 or not isinstance(scaling, int): + print('scaling factor needs to be an int >= 1') + + if len(img.shape) == 2: + H, W = img.shape + + out = np.zeros((scaling * H, scaling * W)) + for h in range(H): + fh = scaling * h + for w in range(W): + fw = scaling * w + out[fh:fh + scaling, fw:fw + scaling] = img[h, w] + + elif len(img.shape) == 3: + H, W, D = img.shape + + out = np.zeros((scaling * H, scaling * W, D)) + for h in range(H): + fh = scaling * h + for w in range(W): + fw = scaling * w + out[fh:fh + scaling, fw:fw + scaling, :] = img[h, w, :] + + return out + + +def repaint_corner_pixels(rgbimg, scaling=3): + ''' + DEPRECATED/OBSOLETE. + + Recolors the top left and bottom right pixel (groups) with the average rgb value of its three neighboring pixel (groups). + The recoloring visually masks the opposing pixel values which are a product of stabilizing the scaling. + Assumes those image ares will pretty much never show evidence. + + Parameters + ---------- + + rgbimg : numpy.ndarray + array of shape [H x W x 3] + + scaling : int + positive integer value > 0 + + Returns + ------- + + rgbimg : numpy.ndarray + three-dimensional array of shape [scaling*H x scaling*W x 3] + ''' + + # top left corner. + rgbimg[0:scaling, 0:scaling, :] = (rgbimg[0, scaling, :] + rgbimg[scaling, 0, :] + rgbimg[scaling, scaling, + :]) / 3.0 + # bottom right corner + rgbimg[-scaling:, -scaling:, :] = (rgbimg[-1, -1 - scaling, :] + rgbimg[-1 - scaling, -1, :] + rgbimg[-1 - scaling, + -1 - scaling, + :]) / 3.0 + return rgbimg + + +def digit_to_rgb(X, scaling=3, shape=(), cmap='binary'): + ''' + Takes as input an intensity array and produces a rgb image due to some color map + + Parameters + ---------- + + X : numpy.ndarray + intensity matrix as array of shape [M x N] + + scaling : int + optional. positive integer value > 0 + + shape: tuple or list of its , length = 2 + optional. if not given, X is reshaped to be square. + + cmap : str + name of color map of choice. default is 'binary' + + Returns + ------- + + image : numpy.ndarray + three-dimensional array of shape [scaling*H x scaling*W x 3] , where H*W == M*N + ''' + + # create color map object from name string + cmap = eval('matplotlib.cm.{}'.format(cmap)) + + image = enlarge_image(vec2im(X, shape), scaling) # enlarge + image = cmap(image.flatten())[..., 0:3].reshape([image.shape[0], image.shape[1], 3]) # colorize, reshape + + return image + + +def hm_to_rgb(R, X=None, scaling=3, shape=(), sigma=2, cmap='bwr', normalize=True): + ''' + Takes as input an intensity array and produces a rgb image for the represented heatmap. + optionally draws the outline of another input on top of it. + + Parameters + ---------- + + R : numpy.ndarray + the heatmap to be visualized, shaped [M x N] + + X : numpy.ndarray + optional. some input, usually the data point for which the heatmap R is for, which shall serve + as a template for a black outline to be drawn on top of the image + shaped [M x N] + + scaling: int + factor, on how to enlarge the heatmap (to control resolution and as a inverse way to control outline thickness) + after reshaping it using shape. + + shape: tuple or list, length = 2 + optional. if not given, X is reshaped to be square. + + sigma : double + optional. sigma-parameter for the canny algorithm used for edge detection. the found edges are drawn as outlines. + + cmap : str + optional. color map of choice + + normalize : bool + optional. whether to normalize the heatmap to [-1 1] prior to colorization or not. + + Returns + ------- + + rgbimg : numpy.ndarray + three-dimensional array of shape [scaling*H x scaling*W x 3] , where H*W == M*N + ''' + + # create color map object from name string + cmap = eval('matplotlib.cm.{}'.format(cmap)) + + if normalize: + R = R / np.max(np.abs(R)) # normalize to [-1,1] wrt to max relevance magnitude + R = (R + 1.) / 2. # shift/normalize to [0,1] for color mapping + + R = enlarge_image(R, scaling) + rgb = cmap(R.flatten())[..., 0:3].reshape([R.shape[0], R.shape[1], 3]) + # rgb = repaint_corner_pixels(rgb, scaling) #obsolete due to directly calling the color map with [0,1]-normalized inputs + + if not X is None: # compute the outline of the input + # X = enlarge_image(vec2im(X,shape), scaling) + xdims = X.shape + Rdims = R.shape + + return rgb + + +def save_image(rgb_images, path, gap=2): + ''' + Takes as input a list of rgb images, places them next to each other with a gap and writes out the result. + + Parameters + ---------- + + rgb_images : list , tuple, collection. such stuff + each item in the collection is expected to be an rgb image of dimensions [H x _ x 3] + where the width is variable + + path : str + the output path of the assembled image + + gap : int + optional. sets the width of a black area of pixels realized as an image shaped [H x gap x 3] in between the input images + + Returns + ------- + + image : numpy.ndarray + the assembled image as written out to path + ''' + + sz = [] + image = [] + for i in range(len(rgb_images)): + if not sz: + sz = rgb_images[i].shape + image = rgb_images[i] + gap = np.zeros((sz[0], gap, sz[2])) + continue + if not sz[0] == rgb_images[i].shape[0] and sz[1] == rgb_images[i].shape[2]: + print('image', i, 'differs in size. unable to perform horizontal alignment') + print('expected: Hx_xD = {0}x_x{1}'.format(sz[0], sz[1])) + print('got : Hx_xD = {0}x_x{1}'.format(rgb_images[i].shape[0], rgb_images[i].shape[1])) + print('skipping image\n') + else: + image = np.hstack((image, gap, rgb_images[i])) + + image *= 255 + image = image.astype(np.uint8) + + print('saving image to ', path) + skimage.io.imsave(path, image) + return image + + +class IoU(Metric): + """Computes the intersection over union (IoU) per class and corresponding + mean (mIoU). + + Intersection over union (IoU) is a common evaluation metric for semantic + segmentation. The predictions are first accumulated in a confusion matrix + and the IoU is computed from it as follows: + + IoU = true_positive / (true_positive + false_positive + false_negative). + + Keyword arguments: + - num_classes (int): number of classes in the classification problem + - normalized (boolean, optional): Determines whether or not the confusion + matrix is normalized or not. Default: False. + - ignore_index (int or iterable, optional): Index of the classes to ignore + when computing the IoU. Can be an int, or any iterable of ints. + """ + + def __init__(self, num_classes, normalized=False, ignore_index=None): + super().__init__() + self.conf_metric = ConfusionMatrix(num_classes, normalized) + + if ignore_index is None: + self.ignore_index = None + elif isinstance(ignore_index, int): + self.ignore_index = (ignore_index,) + else: + try: + self.ignore_index = tuple(ignore_index) + except TypeError: + raise ValueError("'ignore_index' must be an int or iterable") + + def reset(self): + self.conf_metric.reset() + + def add(self, predicted, target): + """Adds the predicted and target pair to the IoU metric. + + Keyword arguments: + - predicted (Tensor): Can be a (N, K, H, W) tensor of + predicted scores obtained from the model for N examples and K classes, + or (N, H, W) tensor of integer values between 0 and K-1. + - target (Tensor): Can be a (N, K, H, W) tensor of + target scores for N examples and K classes, or (N, H, W) tensor of + integer values between 0 and K-1. + + """ + # Dimensions check + assert predicted.size(0) == target.size(0), \ + 'number of targets and predicted outputs do not match' + assert predicted.dim() == 3 or predicted.dim() == 4, \ + "predictions must be of dimension (N, H, W) or (N, K, H, W)" + assert target.dim() == 3 or target.dim() == 4, \ + "targets must be of dimension (N, H, W) or (N, K, H, W)" + + # If the tensor is in categorical format convert it to integer format + if predicted.dim() == 4: + _, predicted = predicted.max(1) + if target.dim() == 4: + _, target = target.max(1) + + self.conf_metric.add(predicted.view(-1), target.view(-1)) + + def value(self): + """Computes the IoU and mean IoU. + + The mean computation ignores NaN elements of the IoU array. + + Returns: + Tuple: (IoU, mIoU). The first output is the per class IoU, + for K classes it's numpy.ndarray with K elements. The second output, + is the mean IoU. + """ + conf_matrix = self.conf_metric.value() + if self.ignore_index is not None: + for index in self.ignore_index: + conf_matrix[:, self.ignore_index] = 0 + conf_matrix[self.ignore_index, :] = 0 + true_positive = np.diag(conf_matrix) + false_positive = np.sum(conf_matrix, 0) - true_positive + false_negative = np.sum(conf_matrix, 1) - true_positive + + # Just in case we get a division by 0, ignore/hide the error + with np.errstate(divide='ignore', invalid='ignore'): + iou = true_positive / (true_positive + false_positive + false_negative) + + return iou, np.nanmean(iou) + \ No newline at end of file diff --git a/utils/timm_model.py b/utils/timm_model.py new file mode 100644 index 0000000000000000000000000000000000000000..3fae156ba4b31b4652d8b444a09e3f2d396fd78e --- /dev/null +++ b/utils/timm_model.py @@ -0,0 +1,149 @@ +""" timm model adapter + +Wraps timm (https://github.com/rwightman/pytorch-image-models) models for use as a vision tower in CLIP model. +""" +import logging +from collections import OrderedDict + +import torch +import torch.nn as nn + +try: + import timm + from timm.models.layers import Mlp, to_2tuple + try: + # old timm imports < 0.8.1 + from timm.models.layers.attention_pool2d import RotAttentionPool2d + from timm.models.layers.attention_pool2d import AttentionPool2d as AbsAttentionPool2d + except ImportError: + # new timm imports >= 0.8.1 + from timm.layers import RotAttentionPool2d + from timm.layers import AttentionPool2d as AbsAttentionPool2d +except ImportError: + timm = None + +from utils.misc import freeze_batch_norm_2d + + +class TimmModel(nn.Module): + """ timm model adapter + """ + + def __init__( + self, + model_name, + embed_dim, + image_size=224, + pool='avg', + proj='linear', + proj_bias=False, + drop=0., + drop_path=None, + patch_drop=None, + pretrained=False, + ): + super().__init__() + if timm is None: + raise RuntimeError("Please `pip install timm` to use timm models.") + self.image_size = to_2tuple(image_size) + + # setup kwargs that may not be common across all models + timm_kwargs = {} + if drop_path is not None: + timm_kwargs['drop_path_rate'] = drop_path + if patch_drop is not None: + timm_kwargs['patch_drop_rate'] = patch_drop + + custom_pool = pool in ('abs_attn', 'rot_attn') + if not proj and not custom_pool: + # use network classifier head as projection if no proj specified and no custom pooling used + self.trunk = timm.create_model( + model_name, + num_classes=embed_dim, + global_pool=pool, + pretrained=pretrained, + **timm_kwargs, + ) + prev_chs = embed_dim + else: + self.trunk = timm.create_model( + model_name, + pretrained=pretrained, + **timm_kwargs, + ) + feat_size = self.trunk.default_cfg.get('pool_size', None) + feature_ndim = 1 if not feat_size else 2 + if custom_pool: + assert feature_ndim == 2 + # if attn pooling used, remove both classifier and default pool + self.trunk.reset_classifier(0, global_pool='') + else: + # reset global pool if pool config set, otherwise leave as network default + reset_kwargs = dict(global_pool=pool) if pool else {} + self.trunk.reset_classifier(0, **reset_kwargs) + prev_chs = self.trunk.num_features + + head_layers = OrderedDict() + + # Add custom pooling to head + if pool == 'abs_attn': + head_layers['pool'] = AbsAttentionPool2d(prev_chs, feat_size=feat_size, out_features=embed_dim) + prev_chs = embed_dim + elif pool == 'rot_attn': + head_layers['pool'] = RotAttentionPool2d(prev_chs, out_features=embed_dim) + prev_chs = embed_dim + + # NOTE attention pool ends with a projection layer, so proj should usually be set to '' if such pooling is used + if proj == 'linear': + head_layers['drop'] = nn.Dropout(drop) + head_layers['proj'] = nn.Linear(prev_chs, embed_dim, bias=proj_bias) + elif proj == 'mlp': + head_layers['mlp'] = Mlp(prev_chs, 2 * embed_dim, embed_dim, drop=(drop, 0), bias=(True, proj_bias)) + else: + assert not proj, f'Unknown projection type {proj}.' + + self.head = nn.Sequential(head_layers) + + def lock(self, unlocked_groups=0, freeze_bn_stats=False): + """ lock modules + Args: + unlocked_groups (int): leave last n layer groups unlocked (default: 0) + """ + if not unlocked_groups: + # lock full model + for param in self.trunk.parameters(): + param.requires_grad = False + if freeze_bn_stats: + freeze_batch_norm_2d(self.trunk) + else: + # NOTE: partial freeze requires latest timm (master) branch and is subject to change + try: + # FIXME import here until API stable and in an official release + from timm.models.helpers import group_parameters, group_modules + except ImportError: + raise RuntimeError( + 'Please install latest timm `pip install git+https://github.com/rwightman/pytorch-image-models`') + matcher = self.trunk.group_matcher() + gparams = group_parameters(self.trunk, matcher) + max_layer_id = max(gparams.keys()) + max_layer_id = max_layer_id - unlocked_groups + for group_idx in range(max_layer_id + 1): + group = gparams[group_idx] + for param in group: + self.trunk.get_parameter(param).requires_grad = False + if freeze_bn_stats: + gmodules = group_modules(self.trunk, matcher, reverse=True) + gmodules = {k for k, v in gmodules.items() if v <= max_layer_id} + freeze_batch_norm_2d(self.trunk, gmodules) + + @torch.jit.ignore + def set_grad_checkpointing(self, enable=True): + try: + self.trunk.set_grad_checkpointing(enable) + except Exception as e: + logging.warning('grad checkpointing not supported for this timm image tower, continuing without...') + + def forward(self, x): + x = self.trunk(x) + x = self.head(x) + return x \ No newline at end of file diff --git a/utils/tokenizer.py b/utils/tokenizer.py new file mode 100644 index 0000000000000000000000000000000000000000..0320ef95f162322195632d27a5df0c5e54f9149e --- /dev/null +++ b/utils/tokenizer.py @@ -0,0 +1,219 @@ +""" CLIP tokenizer + +Copied from https://github.com/openai/CLIP. Originally MIT License, Copyright (c) 2021 OpenAI. +""" +import gzip +import html +import os +from functools import lru_cache +from typing import Union, List + +import ftfy +import regex as re +import torch + +# https://stackoverflow.com/q/62691279 +import os +os.environ["TOKENIZERS_PARALLELISM"] = "false" + + +@lru_cache() +def default_bpe(): + return os.path.join(os.path.dirname(os.path.abspath(__file__)), "vocab/bpe_simple_vocab_16e6.txt.gz") + + +@lru_cache() +def bytes_to_unicode(): + """ + Returns list of utf-8 byte and a corresponding list of unicode strings. + The reversible bpe codes work on unicode strings. + This means you need a large # of unicode characters in your vocab if you want to avoid UNKs. + When you're at something like a 10B token dataset you end up needing around 5K for decent coverage. + This is a significant percentage of your normal, say, 32K bpe vocab. + To avoid that, we want lookup tables between utf-8 bytes and unicode strings. + And avoids mapping to whitespace/control characters the bpe code barfs on. + """ + bs = list(range(ord("!"), ord("~")+1))+list(range(ord("¡"), ord("¬")+1))+list(range(ord("®"), ord("ÿ")+1)) + cs = bs[:] + n = 0 + for b in range(2**8): + if b not in bs: + bs.append(b) + cs.append(2**8+n) + n += 1 + cs = [chr(n) for n in cs] + return dict(zip(bs, cs)) + + +def get_pairs(word): + """Return set of symbol pairs in a word. + Word is represented as tuple of symbols (symbols being variable-length strings). + """ + pairs = set() + prev_char = word[0] + for char in word[1:]: + pairs.add((prev_char, char)) + prev_char = char + return pairs + + +def basic_clean(text): + text = ftfy.fix_text(text) + text = html.unescape(html.unescape(text)) + return text.strip() + + +def whitespace_clean(text): + text = re.sub(r'\s+', ' ', text) + text = text.strip() + return text + + +class SimpleTokenizer(object): + def __init__(self, bpe_path: str = default_bpe(), special_tokens=None): + self.byte_encoder = bytes_to_unicode() + self.byte_decoder = {v: k for k, v in self.byte_encoder.items()} + merges = gzip.open(bpe_path).read().decode("utf-8").split('\n') + merges = merges[1:49152-256-2+1] + merges = [tuple(merge.split()) for merge in merges] + vocab = list(bytes_to_unicode().values()) + vocab = vocab + [v+'' for v in vocab] + for merge in merges: + vocab.append(''.join(merge)) + if not special_tokens: + special_tokens = ['', ''] + else: + special_tokens = ['', ''] + special_tokens + vocab.extend(special_tokens) + self.encoder = dict(zip(vocab, range(len(vocab)))) + self.decoder = {v: k for k, v in self.encoder.items()} + self.bpe_ranks = dict(zip(merges, range(len(merges)))) + self.cache = {t:t for t in special_tokens} + special = "|".join(special_tokens) + self.pat = re.compile(special + r"""|'s|'t|'re|'ve|'m|'ll|'d|[\p{L}]+|[\p{N}]|[^\s\p{L}\p{N}]+""", re.IGNORECASE) + + self.vocab_size = len(self.encoder) + self.all_special_ids = [self.encoder[t] for t in special_tokens] + + def bpe(self, token): + if token in self.cache: + return self.cache[token] + word = tuple(token[:-1]) + ( token[-1] + '',) + pairs = get_pairs(word) + + if not pairs: + return token+'' + + while True: + bigram = min(pairs, key = lambda pair: self.bpe_ranks.get(pair, float('inf'))) + if bigram not in self.bpe_ranks: + break + first, second = bigram + new_word = [] + i = 0 + while i < len(word): + try: + j = word.index(first, i) + new_word.extend(word[i:j]) + i = j + except: + new_word.extend(word[i:]) + break + + if word[i] == first and i < len(word)-1 and word[i+1] == second: + new_word.append(first+second) + i += 2 + else: + new_word.append(word[i]) + i += 1 + new_word = tuple(new_word) + word = new_word + if len(word) == 1: + break + else: + pairs = get_pairs(word) + word = ' '.join(word) + self.cache[token] = word + return word + + def encode(self, text): + bpe_tokens = [] + text = whitespace_clean(basic_clean(text)).lower() + for token in re.findall(self.pat, text): + token = ''.join(self.byte_encoder[b] for b in token.encode('utf-8')) + bpe_tokens.extend(self.encoder[bpe_token] for bpe_token in self.bpe(token).split(' ')) + return bpe_tokens + + # def decode(self, tokens): + # text = ''.join([self.decoder[token] for token in tokens]) + # text = bytearray([self.byte_decoder[c] for c in text]).decode('utf-8', errors="replace").replace('', ' ') + # return text + + def decode(self, tokens): + texts = [self.decoder[token] for token in tokens] + for i in range(len(texts)): + texts[i] = bytearray([self.byte_decoder[c] for c in texts[i]]).decode('utf-8', errors="replace").replace('', ' ') + return texts + +_tokenizer = SimpleTokenizer() + +def decode(output_ids: torch.Tensor): + output_ids = output_ids.cpu().numpy() + return _tokenizer.decode(output_ids) + +def tokenize(texts: Union[str, List[str]], context_length: int = 77) -> torch.LongTensor: + """ + Returns the tokenized representation of given input string(s) + + Parameters + ---------- + texts : Union[str, List[str]] + An input string or a list of input strings to tokenize + context_length : int + The context length to use; all CLIP models use 77 as the context length + + Returns + ------- + A two-dimensional tensor containing the resulting tokens, shape = [number of input strings, context_length] + """ + if isinstance(texts, str): + texts = [texts] + + sot_token = _tokenizer.encoder[""] + eot_token = _tokenizer.encoder[""] + all_tokens = [[sot_token] + _tokenizer.encode(text) + [eot_token] for text in texts] + result = torch.zeros(len(all_tokens), context_length, dtype=torch.long) + + for i, tokens in enumerate(all_tokens): + if len(tokens) > context_length: + tokens = tokens[:context_length] # Truncate + tokens[-1] = eot_token + result[i, :len(tokens)] = torch.tensor(tokens) + + return result + + +class HFTokenizer: + """HuggingFace tokenizer wrapper""" + + def __init__(self, tokenizer_name: str): + from transformers import AutoTokenizer + self.tokenizer = AutoTokenizer.from_pretrained(tokenizer_name) + + def save_pretrained(self, dest): + self.tokenizer.save_pretrained(dest) + + def __call__(self, texts: Union[str, List[str]], context_length: int = 77) -> torch.Tensor: + # same cleaning as for default tokenizer, except lowercasing + # adding lower (for case-sensitive tokenizers) will make it more robust but less sensitive to nuance + if isinstance(texts, str): + texts = [texts] + texts = [whitespace_clean(basic_clean(text)) for text in texts] + input_ids = self.tokenizer( + texts, + return_tensors='pt', + max_length=context_length, + padding='max_length', + truncation=True, + ).input_ids + return input_ids \ No newline at end of file diff --git a/utils/transform.py b/utils/transform.py new file mode 100644 index 0000000000000000000000000000000000000000..2f1b3e71658767131e6e5319c227242219e7b9d5 --- /dev/null +++ b/utils/transform.py @@ -0,0 +1,133 @@ +import warnings +from dataclasses import dataclass, asdict +from typing import Any, Dict, Optional, Sequence, Tuple, Union + +import torch +import torch.nn as nn +import torchvision.transforms.functional as F + +from torchvision.transforms import Normalize, Compose, RandomResizedCrop, InterpolationMode, ToTensor, Resize, \ + CenterCrop + +from utils.constants import OPENAI_DATASET_MEAN, OPENAI_DATASET_STD + + +@dataclass +class AugmentationCfg: + scale: Tuple[float, float] = (0.9, 1.0) + ratio: Optional[Tuple[float, float]] = None + color_jitter: Optional[Union[float, Tuple[float, float, float]]] = None + interpolation: Optional[str] = None + re_prob: Optional[float] = None + re_count: Optional[int] = None + use_timm: bool = False + + +class ResizeMaxSize(nn.Module): + + def __init__(self, max_size, interpolation=InterpolationMode.BICUBIC, fn='max', fill=0): + super().__init__() + if not isinstance(max_size, int): + raise TypeError(f"Size should be int. Got {type(max_size)}") + self.max_size = max_size + self.interpolation = interpolation + self.fn = min if fn == 'min' else min + self.fill = fill + + def forward(self, img): + if isinstance(img, torch.Tensor): + height, width = img.shape[:2] + else: + width, height = img.size + scale = self.max_size / float(max(height, width)) + if scale != 1.0: + new_size = tuple(round(dim * scale) for dim in (height, width)) + img = F.resize(img, new_size, self.interpolation) + pad_h = self.max_size - new_size[0] + pad_w = self.max_size - new_size[1] + img = F.pad(img, padding=[pad_w//2, pad_h//2, pad_w - pad_w//2, pad_h - pad_h//2], fill=self.fill) + return img + + +def _convert_to_rgb(image): + return image.convert('RGB') + + +def image_transform( + image_size: int, + is_train: bool, + mean: Optional[Tuple[float, ...]] = None, + std: Optional[Tuple[float, ...]] = None, + resize_longest_max: bool = False, + fill_color: int = 0, + aug_cfg: Optional[Union[Dict[str, Any], AugmentationCfg]] = None, +): + mean = mean or OPENAI_DATASET_MEAN + if not isinstance(mean, (list, tuple)): + mean = (mean,) * 3 + + std = std or OPENAI_DATASET_STD + if not isinstance(std, (list, tuple)): + std = (std,) * 3 + + if isinstance(image_size, (list, tuple)) and image_size[0] == image_size[1]: + # for square size, pass size as int so that Resize() uses aspect preserving shortest edge + image_size = image_size[0] + + if isinstance(aug_cfg, dict): + aug_cfg = AugmentationCfg(**aug_cfg) + else: + aug_cfg = aug_cfg or AugmentationCfg() + normalize = Normalize(mean=mean, std=std) + if is_train: + aug_cfg_dict = {k: v for k, v in asdict(aug_cfg).items() if v is not None} + use_timm = aug_cfg_dict.pop('use_timm', False) + if use_timm: + from timm.data import create_transform # timm can still be optional + if isinstance(image_size, (tuple, list)): + assert len(image_size) >= 2 + input_size = (3,) + image_size[-2:] + else: + input_size = (3, image_size, image_size) + # by default, timm aug randomly alternates bicubic & bilinear for better robustness at inference time + aug_cfg_dict.setdefault('interpolation', 'random') + aug_cfg_dict.setdefault('color_jitter', None) # disable by default + train_transform = create_transform( + input_size=input_size, + is_training=True, + hflip=0., + mean=mean, + std=std, + re_mode='pixel', + **aug_cfg_dict, + ) + else: + train_transform = Compose([ + RandomResizedCrop( + image_size, + scale=aug_cfg_dict.pop('scale'), + interpolation=InterpolationMode.BICUBIC, + ), + _convert_to_rgb, + ToTensor(), + normalize, + ]) + if aug_cfg_dict: + warnings.warn(f'Unused augmentation cfg items, specify `use_timm` to use ({list(aug_cfg_dict.keys())}).') + return train_transform + else: + if resize_longest_max: + transforms = [ + ResizeMaxSize(image_size, fill=fill_color) + ] + else: + transforms = [ + Resize(image_size, interpolation=InterpolationMode.BICUBIC), + CenterCrop(image_size), + ] + transforms.extend([ + _convert_to_rgb, + ToTensor(), + normalize, + ]) + return Compose(transforms) \ No newline at end of file diff --git a/utils/transformer.py b/utils/transformer.py new file mode 100644 index 0000000000000000000000000000000000000000..d5564e39bd00ef9c8aae5d1d8fbf9474f05b893f --- /dev/null +++ b/utils/transformer.py @@ -0,0 +1,1006 @@ +from collections import OrderedDict +import math +from typing import Callable, Optional, Sequence, Tuple, Text + +import torch +from torch import nn +from torch.nn import functional as F +from torch.utils.checkpoint import checkpoint +import numbers +import einops +import numpy as np +from utils.misc import to_2tuple +from utils.hook import HookManager + + +class LayerNorm(nn.Module): + """Subclass torch's LayerNorm (with cast back to input dtype).""" + + def __init__( + self, + normalized_shape, + eps: float = 1e-5, + elementwise_affine: bool = True, + device=None, + dtype=None, + hook: Optional[HookManager] = None, + ): + super().__init__() + self.hook = hook or HookManager() + if isinstance(normalized_shape, numbers.Integral): + # mypy error: incompatible types in assignment + normalized_shape = (normalized_shape,) # type: ignore[assignment] + self.normalized_shape = tuple(normalized_shape) # type: ignore[arg-type] + self.eps = eps + self.elementwise_affine = elementwise_affine + if self.elementwise_affine: + self.weight = torch.nn.Parameter( + torch.empty( + self.normalized_shape, + ) + ) + self.bias = torch.nn.Parameter( + torch.empty( + self.normalized_shape, + ) + ) + else: + self.register_parameter("weight", None) + self.register_parameter("bias", None) + + def forward(self, x: torch.Tensor): + orig_type = x.dtype + assert self.normalized_shape == x.shape[-len(self.normalized_shape) :] + dims = [-(i + 1) for i in range(len(self.normalized_shape))] + mean = self.hook("mean", ret=x.mean(dim=dims, keepdim=True)) + mean_x2 = (x**2).mean(dim=dims, keepdim=True) + var = mean_x2 - mean**2 + x_norm = self.hook("mean_reduced", ret=(x - mean)) / self.hook( + "sqrt_var", ret=torch.sqrt(var + self.eps) + ) + if self.elementwise_affine: + x_norm = self.hook("renorm.post", ret=self.weight * x_norm + self.bias) + self.hook.finalize() + return x_norm.to(orig_type) + + +class QuickGELU(nn.Module): + # NOTE This is slower than nn.GELU or nn.SiLU and uses more GPU memory + def forward(self, x: torch.Tensor): + return x * torch.sigmoid(1.702 * x) + + +class LayerScale(nn.Module): + def __init__(self, dim, init_values=1e-5, inplace=False): + super().__init__() + self.inplace = inplace + self.gamma = nn.Parameter(init_values * torch.ones(dim)) + + def forward(self, x): + raise ValueError("Not implemented") + return x.mul_(self.gamma) if self.inplace else x * self.gamma + + +class PatchDropout(nn.Module): + """ + https://arxiv.org/abs/2212.00794 + """ + + def __init__(self, prob, exclude_first_token=True): + super().__init__() + assert 0 <= prob < 1.0 + self.prob = prob + self.exclude_first_token = exclude_first_token # exclude CLS token + + def forward(self, x): + if not self.training or self.prob == 0.0: + return x + + if self.exclude_first_token: + cls_tokens, x = x[:, :1], x[:, 1:] + else: + cls_tokens = torch.jit.annotate(torch.Tensor, x[:, :1]) + + batch = x.size()[0] + num_tokens = x.size()[1] + + batch_indices = torch.arange(batch) + batch_indices = batch_indices[..., None] + + keep_prob = 1 - self.prob + num_patches_keep = max(1, int(num_tokens * keep_prob)) + + rand = torch.randn(batch, num_tokens) + patch_indices_keep = rand.topk(num_patches_keep, dim=-1).indices + + x = x[batch_indices, patch_indices_keep] + + if self.exclude_first_token: + x = torch.cat((cls_tokens, x), dim=1) + + return x + + +class Attention(nn.Module): + def __init__( + self, + dim, + num_heads=8, + qkv_bias=True, + scaled_cosine=False, + scale_heads=False, + logit_scale_max=math.log(1.0 / 0.01), + attn_drop=0.0, + proj_drop=0.0, + ): + super().__init__() + self.scaled_cosine = scaled_cosine + self.scale_heads = scale_heads + assert dim % num_heads == 0, "dim should be divisible by num_heads" + self.num_heads = num_heads + self.head_dim = dim // num_heads + self.scale = self.head_dim**-0.5 + self.logit_scale_max = logit_scale_max + + # keeping in_proj in this form (instead of nn.Linear) to match weight scheme of original + self.in_proj_weight = nn.Parameter(torch.randn((dim * 3, dim)) * self.scale) + if qkv_bias: + self.in_proj_bias = nn.Parameter(torch.zeros(dim * 3)) + else: + self.in_proj_bias = None + + if self.scaled_cosine: + self.logit_scale = nn.Parameter( + torch.log(10 * torch.ones((num_heads, 1, 1))) + ) + else: + self.logit_scale = None + self.attn_drop = nn.Dropout(attn_drop) + if self.scale_heads: + self.head_scale = nn.Parameter(torch.ones((num_heads, 1, 1))) + else: + self.head_scale = None + self.out_proj = nn.Linear(dim, dim) + self.out_drop = nn.Dropout(proj_drop) + + def forward(self, x, attn_mask: Optional[torch.Tensor] = None): + L, N, C = x.shape + q, k, v = F.linear(x, self.in_proj_weight, self.in_proj_bias).chunk(3, dim=-1) + q = q.contiguous().view(L, N * self.num_heads, -1).transpose(0, 1) + k = k.contiguous().view(L, N * self.num_heads, -1).transpose(0, 1) + v = v.contiguous().view(L, N * self.num_heads, -1).transpose(0, 1) + + if self.logit_scale is not None: + attn = torch.bmm( + F.normalize(q, dim=-1), F.normalize(k, dim=-1).transpose(-1, -2) + ) + logit_scale = torch.clamp(self.logit_scale, max=self.logit_scale_max).exp() + attn = attn.view(N, self.num_heads, L, L) * logit_scale + attn = attn.view(-1, L, L) + else: + q = q * self.scale + attn = torch.bmm(q, k.transpose(-1, -2)) + + if attn_mask is not None: + if attn_mask.dtype == torch.bool: + new_attn_mask = torch.zeros_like(attn_mask, dtype=q.dtype) + new_attn_mask.masked_fill_(attn_mask, float("-inf")) + attn_mask = new_attn_mask + attn += attn_mask + + attn = attn.softmax(dim=-1) + attn = self.attn_drop(attn) + + x = torch.bmm(attn, v) + if self.head_scale is not None: + x = x.view(N, self.num_heads, L, C) * self.head_scale + x = x.view(-1, L, C) + x = x.transpose(0, 1).reshape(L, N, C) + x = self.out_proj(x) + x = self.out_drop(x) + return x + + +class AttentionalPooler(nn.Module): + def __init__( + self, + d_model: int, + context_dim: int, + n_head: int = 8, + n_queries: int = 256, + norm_layer: Callable = LayerNorm, + ): + super().__init__() + self.query = nn.Parameter(torch.randn(n_queries, d_model)) + self.attn = nn.MultiheadAttention( + d_model, n_head, kdim=context_dim, vdim=context_dim + ) + self.ln_q = norm_layer(d_model) + self.ln_k = norm_layer(context_dim) + + def forward(self, x: torch.Tensor): + x = self.ln_k(x).permute(1, 0, 2) # NLD -> LND + N = x.shape[1] + q = self.ln_q(self.query) + out = self.attn(self._repeat(q, N), x, x, need_weights=False)[0] + return out.permute(1, 0, 2) # LND -> NLD + + def _repeat(self, query, N: int): + return query.unsqueeze(1).repeat(1, N, 1) + + +class MLP(nn.Module): + def __init__( + self, + d_model: int, + mlp_width: int, + act_layer: Callable = nn.GELU, + hook: Optional[HookManager] = None, + ): + super().__init__() + self.hook = hook or HookManager() + self.c_fc = nn.Linear(d_model, mlp_width) + self.gelu = act_layer() + self.c_proj = nn.Linear(mlp_width, d_model) + + def forward(self, x): + x = self.hook("c_fc.post", ret=self.c_fc(x)) + x = self.hook("gelu.post", ret=self.gelu(x)) + x = self.hook("c_proj.post", ret=self.c_proj(x)) + self.hook.finalize() + return x + + +class MultiheadAttention(nn.Module): + """ + There are variety of ways to look at multihead attention. Because of that I implemented a few so it will be easy to compare. + """ + + def __init__( + self, + embed_dim, + num_heads, + dropout=0.0, + bias=True, + add_bias_kv=False, + add_zero_attn=False, + kdim=None, + vdim=None, + batch_first=False, + device=None, + dtype=None, + hook: Optional[HookManager] = None, + ): + super().__init__() + self.hook = hook or HookManager() + self.embed_dim = embed_dim + self.kdim = kdim if kdim is not None else embed_dim + self.vdim = vdim if vdim is not None else embed_dim + self._qkv_same_embed_dim = self.kdim == embed_dim and self.vdim == embed_dim + + self.num_heads = num_heads + self.dropout = dropout + self.batch_first = batch_first + self.head_dim = embed_dim // num_heads + assert ( + self.head_dim * num_heads == self.embed_dim + ), "embed_dim must be divisible by num_heads" + self.in_proj_weight = nn.Parameter(torch.empty((3 * embed_dim, embed_dim))) + + if bias: + self.in_proj_bias = nn.Parameter(torch.empty(3 * embed_dim)) + else: + self.register_parameter("in_proj_bias", None) + self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias) + + if add_bias_kv: + self.bias_k = nn.Parameter(torch.empty((1, 1, embed_dim))) + self.bias_v = nn.Parameter(torch.empty((1, 1, embed_dim))) + else: + self.bias_k = self.bias_v = None + + self.add_zero_attn = add_zero_attn + + def forward_direct(self, x, attn_mask=None): + B, N, C = x.shape + qkv = self.hook( + "in_proj_bias.post", + ret=self.hook("in_proj.post", ret=x @ self.in_proj_weight.T) + + self.in_proj_bias, + ) + qkv = qkv.reshape(B, N, 3, self.num_heads, self.head_dim).permute(2, 0, 3, 1, 4) + q, k, v = qkv.unbind(0) + k = self.hook("k", ret=k) + q = self.hook("q", ret=q) + v = self.hook("v", ret=v) + dk = q.size()[-1] + q = q / math.sqrt(dk) + q = self.hook("q_norm", ret=q) + attn = q @ k.transpose(-2, -1) # [B, H, N, N] + attn = self.hook("pre_mask", ret=attn) + if attn_mask is not None: + attn += attn_mask + attn = self.hook("post_mask", ret=attn) + attn = attn.softmax(dim=-1) + attn = self.hook("post_softmax", ret=attn) + x = attn @ v + + x = x.transpose(1, 2).reshape(B, N, C) + x = self.hook("attn_v", ret=x) + x = self.hook( + "out_proj_bias.post", + ret=self.hook("out_proj.post", ret=x @ self.out_proj.weight.T) + + self.out_proj.bias, + ) + return x + + def _split_qkv_weight(self): + q_weight, k_weight, v_weight = ( + self.in_proj_weight[: self.embed_dim].reshape( + self.num_heads, self.head_dim, -1 + ), + self.in_proj_weight[self.embed_dim : self.embed_dim * 2].reshape( + self.num_heads, self.head_dim, -1 + ), + self.in_proj_weight[self.embed_dim * 2 :].reshape( + self.num_heads, self.head_dim, -1 + ), + ) + return q_weight, k_weight, v_weight + + def _split_qkv_bias(self): + q_bias, k_bias, v_bias = ( + self.in_proj_bias[: self.embed_dim].reshape( + 1, self.num_heads, 1, self.head_dim + ), + self.in_proj_bias[self.embed_dim : self.embed_dim * 2].reshape( + 1, self.num_heads, 1, self.head_dim + ), + self.in_proj_bias[self.embed_dim * 2 :].reshape( + 1, self.num_heads, 1, self.head_dim + ), + ) + return q_bias, k_bias, v_bias + + def forward_qkv(self, x, attn_mask=None): + B, N, C = x.shape + q_weight, k_weight, v_weight = ( + self.in_proj_weight[: self.embed_dim], + self.in_proj_weight[self.embed_dim : self.embed_dim * 2], + self.in_proj_weight[self.embed_dim * 2 :], + ) + q_bias, k_bias, v_bias = ( + self.in_proj_bias[: self.embed_dim], + self.in_proj_bias[self.embed_dim : self.embed_dim * 2], + self.in_proj_bias[self.embed_dim * 2 :], + ) + q = ( + self.hook( + "in_q_bias.post", + ret=self.hook("in_q.post", ret=x @ q_weight.T) + q_bias, + ) + .reshape(B, N, self.num_heads, self.head_dim) + .permute(0, 2, 1, 3) + ) + k = ( + self.hook( + "in_k_bias.post", + ret=self.hook("in_k.post", ret=x @ k_weight.T) + k_bias, + ) + .reshape(B, N, self.num_heads, self.head_dim) + .permute(0, 2, 1, 3) + ) + v = ( + self.hook( + "in_v_bias.post", + ret=self.hook("in_v.post", ret=x @ v_weight.T) + v_bias, + ) + .reshape(B, N, self.num_heads, self.head_dim) + .permute(0, 2, 1, 3) + ) + dk = q.size()[-1] + q = q / math.sqrt(dk) + q = self.hook("q_norm", ret=q) + attn = q @ k.transpose(-2, -1) + attn = self.hook("attention.pre_mask", ret=attn) + if attn_mask is not None: + attn += attn_mask + attn = self.hook("attention.post_mask", ret=attn) + attn = attn.softmax(dim=-1) + attn = self.hook("attention.post_softmax", ret=attn) # [B, H, N, N] + x = torch.einsum("bhnm,bhmc->bhnmc", attn, v) + x = self.hook("extended_attn_v", ret=x) + x = x.sum(axis=3).transpose(1, 2).reshape(B, N, C) + x = self.hook("attn_v", ret=x) + x = self.hook( + "out.post_bias", + ret=self.hook("out.post", ret=x @ self.out_proj.weight.T) + + self.out_proj.bias, + ) + return x + + def forward_per_head_no_spatial(self, x, attn_mask=None): + B, N, C = x.shape + q_weight, k_weight, v_weight = self._split_qkv_weight() + q_bias, k_bias, v_bias = self._split_qkv_bias() + q = self.hook( + "in_q_bias.post", + ret=self.hook("in_q.post", ret=torch.einsum("bnc,hdc->bhnd", x, q_weight)) + + q_bias, + ) + k = self.hook( + "in_k_bias.post", + ret=self.hook("in_k.post", ret=torch.einsum("bnc,hdc->bhnd", x, k_weight)) + + k_bias, + ) + v = self.hook( + "in_v_bias.post", + ret=self.hook("in_v.post", ret=torch.einsum("bnc,hdc->bhnd", x, v_weight)) + + v_bias, + ) # (B, self.num_heads, N, self.head_dim) + dk = q.size()[-1] + q = q / math.sqrt(dk) + q = self.hook("q_norm", ret=q) + attn = q @ k.transpose(-2, -1) + attn = self.hook("attention.pre_mask", ret=attn) + if attn_mask is not None: + attn += attn_mask + attn = self.hook("attention.post_mask", ret=attn) + attn = attn.softmax(dim=-1) + attn = self.hook("attention.post_softmax", ret=attn) # [B, H, N, N] + x = torch.einsum( + "bhnm,bhmc->bnhc", attn, v + ) # We also switch here back from head-first to n-first + x = self.hook("attn_v", ret=x) + x = self.hook( + "out.post", + ret=torch.einsum( + "bnhc,dhc->bnhd", + x, + self.out_proj.weight.reshape( + self.embed_dim, self.num_heads, self.head_dim + ), + ), + ) + x = self.hook("out.post_collapse", ret=x.sum(axis=2)) + x = self.hook("out.post_bias", ret=x + self.out_proj.bias) + return x + + + def forward_per_head(self, x, attn_mask=None): + B, N, C = x.shape + q_weight, k_weight, v_weight = self._split_qkv_weight() + q_bias, k_bias, v_bias = self._split_qkv_bias() + q = self.hook( + "in_q_bias.post", + ret=self.hook("in_q.post", ret=torch.einsum("bnc,hdc->bhnd", x, q_weight)) + + q_bias, + ) + k = self.hook( + "in_k_bias.post", + ret=self.hook("in_k.post", ret=torch.einsum("bnc,hdc->bhnd", x, k_weight)) + + k_bias, + ) + v = self.hook( + "in_v_bias.post", + ret=self.hook("in_v.post", ret=torch.einsum("bnc,hdc->bhnd", x, v_weight)) + + v_bias, + ) # (B, self.num_heads, N, self.head_dim) + dk = q.size()[-1] + q = q / math.sqrt(dk) + q = self.hook("q_norm", ret=q) + attn = q @ k.transpose(-2, -1) + attn = self.hook("attention.pre_mask", ret=attn) + if attn_mask is not None: + attn += attn_mask + attn = self.hook("attention.post_mask", ret=attn) + attn = attn.softmax(dim=-1) + attn = self.hook("attention.post_softmax", ret=attn) # [B, H, N, N] + x = torch.einsum( + "bhnm,bhmc->bnmhc", attn, v + ) # We also switch here back from head-first to n-first + x = self.hook("extended_attn_v", ret=x) + x = self.hook( + "out.post", + ret=torch.einsum( + "bnmhc,dhc->bnmhd", + x, + self.out_proj.weight.reshape( + self.embed_dim, self.num_heads, self.head_dim + ), + ), + ) + x = self.hook("out.post_collapse", ret=x.sum(axis=[2, 3])) + x = self.hook("out.post_bias", ret=x + self.out_proj.bias) + return x + + def _get_ov_circuit( + self, + ): + reshaped_o = self.out_proj.weight.reshape( + self.embed_dim, self.num_heads, self.head_dim + ) + _, _, v_weight = self._split_qkv_weight() # num_heads, head_dim, embed_dim + _, _, v_bias = self._split_qkv_bias() # 1, num_heads, 1, head_dim + ov_circuit = torch.einsum("onh,nhi->oni", reshaped_o, v_weight) + ov_bias_circuit = torch.einsum( + "onh,bnxh->bnxo", reshaped_o, v_bias + ) # [1, num_heads, 1, embed_dim] + return ov_circuit, ov_bias_circuit + + def forward_ov_circuit(self, x, attn_mask=None): + B, N, C = x.shape + q_weight, k_weight, _ = self._split_qkv_weight() + q_bias, k_bias, _ = self._split_qkv_bias() + q = self.hook( + "in_q_bias.post", + ret=self.hook("in_q.post", ret=torch.einsum("bnc,hdc->bhnd", x, q_weight)) + + q_bias, + ) + k = self.hook( + "in_k_bias.post", + ret=self.hook("in_k.post", ret=torch.einsum("bnc,hdc->bhnd", x, k_weight)) + + k_bias, + ) + ov, ov_bias = self._get_ov_circuit() + ov = self.hook("ov", ret=ov) + ov_bias = self.hook("ov_bias", ret=ov_bias) + v = self.hook( + "ov_bias.post", + ret=self.hook("ov.post", ret=torch.einsum("bnc,dhc->bhnd", x, ov)) + + ov_bias, + ) + + dk = q.size()[-1] + q = q / math.sqrt(dk) + q = self.hook("q_norm", ret=q) + attn = q @ k.transpose(-2, -1) + attn = self.hook("attention.pre_mask", ret=attn) + if attn_mask is not None: + attn += attn_mask + attn = self.hook("attention.post_mask", ret=attn) + attn = attn.softmax(dim=-1) + attn = self.hook("attention.post_softmax", ret=attn) # [B, H, N, N] + x = torch.einsum( + "bhnm,bhmc->bnmhc", attn, v + ) # We also switch here back from head-first to n-first + x = self.hook("extended_attn_ov", ret=x) + x = self.hook("out.post_collapse", ret=x.sum(axis=[2, 3])) + x = self.hook("out.post_bias", ret=x + self.out_proj.bias) + return x + + def forward(self, x, attn_mask=None, method: Text = "ov_circuit"): + if method == "direct": + x = self.forward_direct(x, attn_mask=attn_mask) + elif method == "qkv": + x = self.forward_qkv(x, attn_mask=attn_mask) + elif method == "head": + x = self.forward_per_head(x, attn_mask=attn_mask) + elif method == "head_no_spatial": + x = self.forward_per_head_no_spatial(x, attn_mask=attn_mask) + elif method == "ov_circuit": + x = self.forward_ov_circuit(x, attn_mask=attn_mask) + else: + raise NotImplementedError('Unknown attention method') + self.hook.finalize() + + return x + + +class ResidualAttentionBlock(nn.Module): + def __init__( + self, + d_model: int, + n_head: int, + mlp_ratio: float = 4.0, + ls_init_value: float = None, + act_layer: Callable = nn.GELU, + norm_layer: Callable = LayerNorm, + hook: Optional[HookManager] = None, + ): + super().__init__() + self.hook = hook or HookManager() + self.ln_1 = norm_layer(d_model, hook=hook.fork("ln_1")) + self.attn = MultiheadAttention(d_model, n_head, hook=hook.fork("attn")) + + self.ls_1 = ( + LayerScale(d_model, ls_init_value) + if ls_init_value is not None + else nn.Identity() + ) + + self.ln_2 = norm_layer(d_model, hook=hook.fork("ln_2")) + mlp_width = int(d_model * mlp_ratio) + self.mlp = MLP(d_model, mlp_width, act_layer=act_layer, hook=hook.fork("mlp")) + self.ls_2 = ( + LayerScale(d_model, ls_init_value) + if ls_init_value is not None + else nn.Identity() + ) + + def attention( + self, + q_x: torch.Tensor, + attn_mask: Optional[torch.Tensor] = None, + method: Text = "direct", + ): + attn_mask = attn_mask.to(q_x.dtype) if attn_mask is not None else None + return self.attn(q_x, attn_mask=attn_mask, method=method) + + def forward( + self, + q_x: torch.Tensor, + attn_mask: Optional[torch.Tensor] = None, + attn_method: Text = "direct", + ): + q_x = self.hook("pre", ret=q_x) + after_ln1 = self.ln_1(q_x) + after_attn = self.attention( + q_x=after_ln1, attn_mask=attn_mask, method=attn_method + ) + after_attn = self.hook("after_attn", ret=after_attn) + x = q_x + self.ls_1(after_attn) + after_ln2 = self.ln_2(x) + after_mlp = self.mlp(after_ln2) + after_mlp = self.hook("after_mlp", ret=after_mlp) + x = x + self.ls_2(after_mlp) + x = self.hook("post", ret=x) + self.hook.finalize() + return x + + +class Transformer(nn.Module): + def __init__( + self, + width: int, + layers: int, + heads: int, + mlp_ratio: float = 4.0, + ls_init_value: float = None, + act_layer: Callable = nn.GELU, + norm_layer: Callable = LayerNorm, + hook: Optional[HookManager] = None, + ): + super().__init__() + self.hook = hook or HookManager() + self.width = width + self.layers = layers + self.grad_checkpointing = False + + self.resblocks = nn.ModuleList( + [ + ResidualAttentionBlock( + width, + heads, + mlp_ratio, + ls_init_value=ls_init_value, + act_layer=act_layer, + norm_layer=norm_layer, + hook=hook.fork(f"resblocks.{i}"), + ) + for i in range(layers) + ] + ) + + def get_cast_dtype(self) -> torch.dtype: + if hasattr(self.resblocks[0].mlp.c_fc, "int8_original_dtype"): + return self.resblocks[0].mlp.c_fc.int8_original_dtype + return self.resblocks[0].mlp.c_fc.weight.dtype + + def forward( + self, + x: torch.Tensor, + attn_mask: Optional[torch.Tensor] = None, + attn_method: Text = "direct", + ): + for r in self.resblocks: + if self.grad_checkpointing and not torch.jit.is_scripting(): + raise ValueError("grad_checkpointing not implement") + # TODO: handle kwargs https://github.com/pytorch/pytorch/issues/79887#issuecomment-1161758372 + x = checkpoint(r, x, None, None, attn_mask) + else: + x = r(x, attn_mask=attn_mask, attn_method=attn_method) + self.hook.finalize() + return x + + +class VisionTransformer(nn.Module): + output_tokens: torch.jit.Final[bool] + + def __init__( + self, + image_size: int, + patch_size: int, + width: int, + layers: int, + heads: int, + mlp_ratio: float, + ls_init_value: float = None, + global_average_pool: bool = False, + attentional_pool: bool = False, + n_queries: int = 256, + attn_pooler_heads: int = 8, + output_dim: int = 512, + patch_dropout: float = 0.0, + input_patchnorm: bool = False, + act_layer: Callable = nn.GELU, + norm_layer: Callable = LayerNorm, + output_tokens: bool = False, + hook: Optional[HookManager] = None, + ): + super().__init__() + self.hook = hook or HookManager() + self.output_tokens = output_tokens + image_height, image_width = self.image_size = to_2tuple(image_size) + patch_height, patch_width = self.patch_size = to_2tuple(patch_size) + self.grid_size = (image_height // patch_height, image_width // patch_width) + self.output_dim = output_dim + + # whether to layernorm each patch, as done in dual patchnorm paper - https://arxiv.org/abs/2302.01327v1 + self.input_patchnorm = input_patchnorm + + if input_patchnorm: + patch_input_dim = patch_height * patch_width * 3 + self.patchnorm_pre_ln = LayerNorm( + patch_input_dim, hook=hook.fork("patchnorm_pre_ln") + ) + self.conv1 = nn.Linear(patch_input_dim, width) + else: + self.patchnorm_pre_ln = nn.Identity() + self.conv1 = nn.Conv2d( + in_channels=3, + out_channels=width, + kernel_size=patch_size, + stride=patch_size, + bias=False, + ) + + # class embeddings and positional embeddings + scale = width**-0.5 + self.class_embedding = nn.Parameter(scale * torch.randn(width)) + self.positional_embedding = nn.Parameter( + scale * torch.randn(self.grid_size[0] * self.grid_size[1] + 1, width) + ) + + # setting a patch_dropout of 0. would mean it is disabled and this function would be the identity fn + self.patch_dropout = ( + PatchDropout(patch_dropout) if patch_dropout > 0.0 else nn.Identity() + ) + + self.ln_pre = norm_layer(width, hook=hook.fork("ln_pre")) + self.transformer = Transformer( + width, + layers, + heads, + mlp_ratio, + ls_init_value=ls_init_value, + act_layer=act_layer, + norm_layer=norm_layer, + hook=hook.fork("transformer"), + ) + + self.global_average_pool = global_average_pool + if attentional_pool: + self.attn_pool = AttentionalPooler( + output_dim, width, n_head=attn_pooler_heads, n_queries=n_queries + ) + self.ln_post = norm_layer(output_dim, hook=hook.fork("ln_post")) + self.proj = nn.Parameter(scale * torch.randn(output_dim, output_dim)) + else: + self.attn_pool = None + self.ln_post = norm_layer(width, hook=hook.fork("ln_post")) + self.proj = nn.Parameter(scale * torch.randn(width, output_dim)) + + @torch.jit.ignore + def set_grad_checkpointing(self, enable=True): + self.transformer.grad_checkpointing = enable + + def _global_pool(self, x: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]: + if self.global_average_pool: + return x.mean(dim=1), x + else: + return x[:, 0], x[:, 1:] + + def forward(self, x: torch.Tensor, attn_method: Text = "direct"): + + # to patches - whether to use dual patchnorm - https://arxiv.org/abs/2302.01327v1 + if self.input_patchnorm: + # einops - rearrange(x, 'b c (h p1) (w p2) -> b (h w) (c p1 p2)') + x = x.reshape( + x.shape[0], + x.shape[1], + self.grid_size[0], + self.patch_size[0], + self.grid_size[1], + self.patch_size[1], + ) + x = x.permute(0, 2, 4, 1, 3, 5) + x = x.reshape(x.shape[0], self.grid_size[0] * self.grid_size[1], -1) + x = self.hook("patchnorm_pre_ln.post", ret=self.patchnorm_pre_ln(x)) + x = self.hook("conv1.post", ret=self.conv1(x)) + else: + x = self.hook( + "conv1.post", ret=self.conv1(x) + ) # shape = [*, width, grid, grid] + x = x.reshape(x.shape[0], x.shape[1], -1) # shape = [*, width, grid ** 2] + x = x.permute(0, 2, 1) # shape = [*, grid ** 2, width] + + # class embeddings and positional embeddings + x = torch.cat( + [ + self.class_embedding.to(x.dtype) + + torch.zeros( + x.shape[0], 1, x.shape[-1], dtype=x.dtype, device=x.device + ), + x, + ], + dim=1, + ) # shape = [*, grid ** 2 + 1, width] + x = self.hook( + "positional_embedding.post", ret=x + self.positional_embedding.to(x.dtype) + ) + + # a patch_dropout of 0. would mean it is disabled and this function would do nothing but return what was passed in + x = self.hook("patch_dropout.post", ret=self.patch_dropout(x)) + x = self.hook("ln_pre_post", ret=self.ln_pre(x)) + # x = x.permute(1, 0, 2) # NLD -> LND + x = self.transformer(x, attn_method=attn_method) + # x = x.permute(1, 0, 2) # LND -> NLD + if self.attn_pool is not None: + x = self.hook("attn_pool.post", ret=self.attn_pool(x)) + x = self.hook("ln_post_post", ret=self.ln_post(x)) + pooled, tokens = self.hook("global_pool.post", ret=self._global_pool(x)) + else: + pooled, tokens = self.hook("global_pool.post", ret=self._global_pool(x)) + pooled = self.hook("ln_post_post", ret=self.ln_post(pooled)) + + if self.proj is not None: + pooled = self.hook( + "proj.post", ret=self.hook("proj.pre", ret=pooled) @ self.proj + ) + + self.hook.finalize() + + if self.output_tokens: + return pooled, tokens + + return pooled + + +class TextTransformer(nn.Module): + output_tokens: torch.jit.Final[bool] + + def __init__( + self, + context_length: int = 77, + vocab_size: int = 49408, + width: int = 512, + heads: int = 8, + layers: int = 12, + ls_init_value: float = None, + output_dim: int = 512, + act_layer: Callable = nn.GELU, + norm_layer: Callable = LayerNorm, + embed_cls: bool = False, + pad_id: int = 0, + output_tokens: bool = False, + hook: Optional[HookManager] = None, + ): + super().__init__() + self.hook = hook or HookManager() + self.output_tokens = output_tokens + self.num_pos = self.context_length = context_length + self.vocab_size = vocab_size + self.width = width + self.output_dim = output_dim + self.heads = heads + self.pad_id = pad_id + + self.text_projection = nn.Parameter(torch.empty(width, output_dim)) + + if embed_cls: + self.cls_emb = nn.Parameter(torch.empty(width)) + self.num_pos += 1 + else: + self.cls_emb = None + + self.token_embedding = nn.Embedding(vocab_size, width) + self.positional_embedding = nn.Parameter(torch.empty(self.num_pos, width)) + self.transformer = Transformer( + width=width, + layers=layers, + heads=heads, + ls_init_value=ls_init_value, + act_layer=act_layer, + norm_layer=norm_layer, + hook=self.hook.fork("transformer"), + ) + self.ln_final = norm_layer(width) + + self.register_buffer("attn_mask", self.build_attention_mask(), persistent=False) + + self.init_parameters() + + def init_parameters(self): + nn.init.normal_(self.token_embedding.weight, std=0.02) + nn.init.normal_(self.positional_embedding, std=0.01) + if self.cls_emb is not None: + nn.init.normal_(self.cls_emb, std=0.01) + + proj_std = (self.transformer.width**-0.5) * ( + (2 * self.transformer.layers) ** -0.5 + ) + attn_std = self.transformer.width**-0.5 + fc_std = (2 * self.transformer.width) ** -0.5 + for block in self.transformer.resblocks: + nn.init.normal_(block.attn.in_proj_weight, std=attn_std) + nn.init.normal_(block.attn.out_proj.weight, std=proj_std) + nn.init.normal_(block.mlp.c_fc.weight, std=fc_std) + nn.init.normal_(block.mlp.c_proj.weight, std=proj_std) + + if self.text_projection is not None: + nn.init.normal_(self.text_projection, std=self.transformer.width**-0.5) + + @torch.jit.ignore + def set_grad_checkpointing(self, enable=True): + self.transformer.grad_checkpointing = enable + + def build_attention_mask(self): + # lazily create causal attention mask, with full attention between the tokens + # pytorch uses additive attention mask; fill with -inf + mask = torch.empty(self.num_pos, self.num_pos) + mask.fill_(float("-inf")) + mask.triu_(1) # zero out the lower diagonal + return mask + + def build_cls_mask(self, text, cast_dtype: torch.dtype): + cls_mask = (text != self.pad_id).unsqueeze(1) + cls_mask = F.pad(cls_mask, (1, 0, cls_mask.shape[2], 0), value=1.0) + additive_mask = torch.empty( + cls_mask.shape, dtype=cast_dtype, device=cls_mask.device + ) + additive_mask.fill_(0) + additive_mask.masked_fill_(~cls_mask, float("-inf")) + additive_mask = torch.repeat_interleave(additive_mask, self.heads, 0) + return additive_mask + + def _repeat(self, t, N: int): + return t.reshape(1, 1, -1).repeat(N, 1, 1) + + def forward(self, text, attn_method: Text = "direct"): + cast_dtype = self.transformer.get_cast_dtype() + seq_len = text.shape[1] + + x = self.token_embedding(text).to(cast_dtype) # [batch_size, n_ctx, d_model] + attn_mask = self.attn_mask + if self.cls_emb is not None: + seq_len += 1 + x = torch.cat([x, self._repeat(self.cls_emb, x.shape[0])], dim=1) + cls_mask = self.build_cls_mask(text, cast_dtype) + attn_mask = ( + attn_mask[None, :seq_len, :seq_len] + cls_mask[:, :seq_len, :seq_len] + ) + + x = x + self.positional_embedding[:seq_len].to(cast_dtype) + # x = x.permute(1, 0, 2) # NLD -> LND + x = self.transformer(x, attn_mask=attn_mask, attn_method=attn_method) + # x = x.permute(1, 0, 2) # LND -> NLD + + # x.shape = [batch_size, n_ctx, transformer.width] + # take features from the eot embedding (eot_token is the highest number in each sequence) + if self.cls_emb is not None: + pooled, tokens = x[:, -1], x[:, :-1] + pooled = self.ln_final(pooled) + else: + x = self.ln_final(x) + pooled, tokens = x[torch.arange(x.shape[0]), text.argmax(dim=-1)], x + + if self.text_projection is not None: + pooled = pooled @ self.text_projection + + self.hook.finalize() + + if self.output_tokens: + return pooled, tokens + + return pooled diff --git a/utils/visualization.py b/utils/visualization.py new file mode 100644 index 0000000000000000000000000000000000000000..54cc0be5eb0ef0ad856cfa40264da5a19c534d1a --- /dev/null +++ b/utils/visualization.py @@ -0,0 +1,30 @@ +from PIL import Image + +## Imports +from PIL import Image +from torchvision import transforms + + +def _convert_to_rgb(image): + return image.convert("RGB") + + +visualization_preprocess = transforms.Compose( + [ + transforms.Resize(size=224, interpolation=Image.BICUBIC), + transforms.CenterCrop(size=(224, 224)), + _convert_to_rgb, + ] +) + + +def image_grid(imgs, rows, cols): + assert len(imgs) == rows * cols + + w, h = imgs[0].size + grid = Image.new("RGB", size=(cols * w, rows * h)) + grid_w, grid_h = grid.size + + for i, img in enumerate(imgs): + grid.paste(img, box=(i % cols * w, i // cols * h)) + return grid diff --git a/utils/vocab/bpe_simple_vocab_16e6.txt.gz b/utils/vocab/bpe_simple_vocab_16e6.txt.gz new file mode 100644 index 0000000000000000000000000000000000000000..36a15856e00a06a9fbed8cdd34d2393fea4a3113 --- /dev/null +++ b/utils/vocab/bpe_simple_vocab_16e6.txt.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:924691ac288e54409236115652ad4aa250f48203de50a9e4722a6ecd48d6804a +size 1356917