|
| 1 | +import timm |
| 2 | +import torch |
| 3 | +import torch.nn as nn |
| 4 | +from torchvision.models.feature_extraction import create_feature_extractor |
| 5 | +from torchvision.transforms import Resize |
| 6 | + |
| 7 | +from keypoint_detection.models.backbones.base_backbone import Backbone |
| 8 | + |
| 9 | + |
| 10 | +class UpSamplingBlock(nn.Module): |
| 11 | + """ |
| 12 | + A very basic Upsampling block (these params have to be learnt from scratch so keep them small) |
| 13 | +
|
| 14 | + x --> up ---> conv1 --> norm -> relu |
| 15 | +
|
| 16 | + """ |
| 17 | + |
| 18 | + def __init__(self, n_channels_in, n_channels_out, kernel_size): |
| 19 | + super().__init__() |
| 20 | + |
| 21 | + self.conv1 = nn.Conv2d( |
| 22 | + in_channels=n_channels_in, |
| 23 | + out_channels=n_channels_out, |
| 24 | + kernel_size=kernel_size, |
| 25 | + bias=False, |
| 26 | + padding="same", |
| 27 | + ) |
| 28 | + |
| 29 | + self.norm1 = nn.BatchNorm2d(n_channels_out) |
| 30 | + self.relu1 = nn.ReLU() |
| 31 | + |
| 32 | + def forward(self, x): |
| 33 | + # bilinear is not deterministic, use nearest neighbor instead |
| 34 | + x = nn.functional.interpolate(x, scale_factor=2.0) |
| 35 | + x = self.conv1(x) |
| 36 | + x = self.norm1(x) |
| 37 | + x = self.relu1(x) |
| 38 | + |
| 39 | + # second conv as in original UNet upsampling block decreases performance |
| 40 | + # probably because I was using a small dataset that did not have enough data to learn the extra parameters |
| 41 | + return x |
| 42 | + |
| 43 | + |
| 44 | +class DinoV2Up(Backbone): |
| 45 | + """ |
| 46 | + backbone based on a frozen Dino-v2 ViT-S model and a number of conv-based upsampling blocks to go from patch-level to pixel-level. |
| 47 | + Images are resized to 518x518 before being fed to the ViT. |
| 48 | +
|
| 49 | + The Dino v2 paper considers adding both a linear layer and a full-blown DPT head to the intermediate output of the last 4 blocks of the ViT. |
| 50 | +
|
| 51 | + This model can be considered as a simpler alternative to the DPT head that also aims to increase resolution of the features. |
| 52 | +
|
| 53 | + The upsample blocks add about 6M params, bringing the total to 28 params. |
| 54 | + only these blocks are trained, the dino model is frozen. |
| 55 | +
|
| 56 | + Dinov2 paper: https://arxiv.org/pdf/2304.07193#page=13.87 |
| 57 | + DPT paper: https://arxiv.org/abs/2103.13413 |
| 58 | +
|
| 59 | +
|
| 60 | + THe head is most likely not the optimal architecture. reducing the #params in the decoder does not work for sure. |
| 61 | + Unfreezing the dino model doesn't work either (for small datasets). |
| 62 | + """ |
| 63 | + |
| 64 | + def __init__(self, **kwargs): |
| 65 | + super().__init__() |
| 66 | + self.encoder = timm.create_model( |
| 67 | + "vit_small_patch14_dinov2.lvd142m", |
| 68 | + pretrained=True, |
| 69 | + num_classes=0, # remove classifier nn.Linear |
| 70 | + ) |
| 71 | + |
| 72 | + # get model specific transforms (normalization, resize) |
| 73 | + self.img_resizer = Resize((518, 518)) # specific to DinoV2 ViT |
| 74 | + |
| 75 | + self.feature_extractor = create_feature_extractor( |
| 76 | + self.encoder, ["blocks.8", "blocks.9", "blocks.10", "blocks.11"] |
| 77 | + ) |
| 78 | + |
| 79 | + # freeze the feature extractor |
| 80 | + for param in self.feature_extractor.parameters(): |
| 81 | + param.requires_grad = False |
| 82 | + |
| 83 | + self.upsamplingblocks = nn.ModuleList( |
| 84 | + [ |
| 85 | + UpSamplingBlock(4 * 384, 384, 3), |
| 86 | + UpSamplingBlock(384, 192, 3), |
| 87 | + UpSamplingBlock(192, 96, 3), |
| 88 | + UpSamplingBlock(96, 96, 3), |
| 89 | + ] |
| 90 | + ) |
| 91 | + |
| 92 | + def forward(self, x): |
| 93 | + orig_image_shape = x.shape[-2:] |
| 94 | + x = self.img_resizer(x) |
| 95 | + features = self.feature_extractor(x) # [(B,1370,384)] |
| 96 | + features = list(features.values()) |
| 97 | + # concatenate the features |
| 98 | + features = torch.cat(features, dim=2) |
| 99 | + # drop class token patch |
| 100 | + features = features[:, 1:] # (B, 1369, 384) |
| 101 | + |
| 102 | + # reshape to (B,B, 37,37,4*384) |
| 103 | + features = features.view(features.shape[0], 37, 37, -1) |
| 104 | + |
| 105 | + # permute to (B, 4*384, 37, 37) |
| 106 | + features = features.permute(0, 3, 1, 2) |
| 107 | + |
| 108 | + # upsample 3 times 2x to 37*8 = 296 |
| 109 | + for i in range(3): |
| 110 | + features = self.upsamplingblocks[i](features) |
| 111 | + |
| 112 | + # resize to 518/2 = 259 |
| 113 | + features = nn.functional.interpolate(features, size=(259, 259)) |
| 114 | + # upsample final time to 518 |
| 115 | + features = self.upsamplingblocks[-1](features) |
| 116 | + |
| 117 | + # now resize to original image shape |
| 118 | + features = nn.functional.interpolate(features, size=orig_image_shape) |
| 119 | + return features |
| 120 | + |
| 121 | + def get_n_channels_out(self): |
| 122 | + return 96 |
| 123 | + |
| 124 | + |
| 125 | +if __name__ == "__main__": |
| 126 | + model = DinoV2Up() |
| 127 | + |
| 128 | + num_params = sum(p.numel() for p in model.parameters() if p.requires_grad) |
| 129 | + print(f"num trainable params = {num_params/10**6:.2f} M") |
| 130 | + |
| 131 | + x = torch.zeros((1, 3, 512, 512)) |
| 132 | + y = model(x) |
| 133 | + print(y.shape) |
0 commit comments