defmo.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  1. # LICENSE HEADER MANAGED BY add-license-header
  2. #
  3. # Copyright 2018 Kornia Team
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. #
  17. from typing import Callable, Dict, List, Optional, Type
  18. import torch
  19. from torch import nn
  20. from kornia.core import Module, Tensor, concatenate, stack
  21. urls: Dict[str, str] = {}
  22. urls["defmo_encoder"] = "http://ptak.felk.cvut.cz/personal/rozumden/defmo_saved_models/encoder_best.pt"
  23. urls["defmo_rendering"] = "http://ptak.felk.cvut.cz/personal/rozumden/defmo_saved_models/rendering_best.pt"
  24. # conv1x1, conv3x3, Bottleneck, ResNet are taken from:
  25. # https://github.com/pytorch/vision/blob/master/torchvision/models/resnet.py
  26. def conv1x1(in_planes: int, out_planes: int, stride: int = 1) -> nn.Conv2d:
  27. """1x1 convolution."""
  28. return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)
  29. def conv3x3(in_planes: int, out_planes: int, stride: int = 1, groups: int = 1, dilation: int = 1) -> nn.Conv2d:
  30. """3x3 convolution with padding."""
  31. return nn.Conv2d(
  32. in_planes,
  33. out_planes,
  34. kernel_size=3,
  35. stride=stride,
  36. padding=dilation,
  37. groups=groups,
  38. bias=False,
  39. dilation=dilation,
  40. )
  41. class Bottleneck(Module):
  42. # Bottleneck in torchvision places the stride for downsampling at 3x3 convolution(self.conv2)
  43. # while original implementation places the stride at the first 1x1 convolution(self.conv1)
  44. # according to "Deep residual learning for image recognition"https://arxiv.org/abs/1512.03385.
  45. # This variant is also known as ResNet V1.5 and improves accuracy according to
  46. # https://ngc.nvidia.com/catalog/model-scripts/nvidia:resnet_50_v1_5_for_pytorch.
  47. expansion: int = 4
  48. def __init__(
  49. self,
  50. inplanes: int,
  51. planes: int,
  52. stride: int = 1,
  53. downsample: Optional[Module] = None,
  54. groups: int = 1,
  55. base_width: int = 64,
  56. dilation: int = 1,
  57. norm_layer: Optional[Callable[..., Module]] = None,
  58. ) -> None:
  59. super().__init__()
  60. if norm_layer is None:
  61. norm_layer = nn.BatchNorm2d
  62. width = int(planes * (base_width / 64.0)) * groups
  63. # Both self.conv2 and self.downsample layers downsample the input when stride != 1
  64. self.conv1 = conv1x1(inplanes, width)
  65. self.bn1 = norm_layer(width)
  66. self.conv2 = conv3x3(width, width, stride, groups, dilation)
  67. self.bn2 = norm_layer(width)
  68. self.conv3 = conv1x1(width, planes * self.expansion)
  69. self.bn3 = norm_layer(planes * self.expansion)
  70. self.relu = nn.ReLU(inplace=True)
  71. self.downsample = downsample
  72. self.stride = stride
  73. def forward(self, x: Tensor) -> Tensor:
  74. identity = x
  75. out = self.conv1(x)
  76. out = self.bn1(out)
  77. out = self.relu(out)
  78. out = self.conv2(out)
  79. out = self.bn2(out)
  80. out = self.relu(out)
  81. out = self.conv3(out)
  82. out = self.bn3(out)
  83. if self.downsample is not None:
  84. identity = self.downsample(x)
  85. out += identity
  86. out = self.relu(out)
  87. return out
  88. class ResNet(Module):
  89. def __init__(
  90. self,
  91. block: Type[Bottleneck],
  92. layers: List[int],
  93. num_classes: int = 1000,
  94. zero_init_residual: bool = False,
  95. groups: int = 1,
  96. width_per_group: int = 64,
  97. replace_stride_with_dilation: Optional[List[bool]] = None,
  98. norm_layer: Optional[Callable[..., Module]] = None,
  99. ) -> None:
  100. super().__init__()
  101. if norm_layer is None:
  102. norm_layer = nn.BatchNorm2d
  103. self._norm_layer = norm_layer
  104. self.inplanes = 64
  105. self.dilation = 1
  106. if replace_stride_with_dilation is None:
  107. # each element in the tuple indicates if we should replace
  108. # the 2x2 stride with a dilated convolution instead
  109. replace_stride_with_dilation = [False, False, False]
  110. if len(replace_stride_with_dilation) != 3:
  111. raise ValueError(
  112. f"replace_stride_with_dilation should be None or a 3-element tuple, got {replace_stride_with_dilation}"
  113. )
  114. self.groups = groups
  115. self.base_width = width_per_group
  116. self.conv1 = nn.Conv2d(3, self.inplanes, kernel_size=7, stride=2, padding=3, bias=False)
  117. self.bn1 = norm_layer(self.inplanes)
  118. self.relu = nn.ReLU(inplace=True)
  119. self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
  120. self.layer1 = self._make_layer(block, 64, layers[0])
  121. self.layer2 = self._make_layer(block, 128, layers[1], stride=2, dilate=replace_stride_with_dilation[0])
  122. self.layer3 = self._make_layer(block, 256, layers[2], stride=2, dilate=replace_stride_with_dilation[1])
  123. self.layer4 = self._make_layer(block, 512, layers[3], stride=2, dilate=replace_stride_with_dilation[2])
  124. self.avgpool = nn.AdaptiveAvgPool2d((1, 1))
  125. self.fc = nn.Linear(512 * block.expansion, num_classes)
  126. for m in self.modules():
  127. if isinstance(m, nn.Conv2d):
  128. nn.init.kaiming_normal_(m.weight, mode="fan_out", nonlinearity="relu")
  129. elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)):
  130. nn.init.constant_(m.weight, 1)
  131. nn.init.constant_(m.bias, 0)
  132. # Zero-initialize the last BN in each residual branch,
  133. # so that the residual branch starts with zeros, and each residual block behaves like an identity.
  134. # This improves the model by 0.2~0.3% according to https://arxiv.org/abs/1706.02677
  135. if zero_init_residual:
  136. for m in self.modules():
  137. if isinstance(m, Bottleneck) and isinstance(m.bn3.weight, Tensor):
  138. nn.init.constant_(m.bn3.weight, 0)
  139. def _make_layer(
  140. self, block: Type[Bottleneck], planes: int, blocks: int, stride: int = 1, dilate: bool = False
  141. ) -> nn.Sequential:
  142. norm_layer = self._norm_layer
  143. downsample = None
  144. previous_dilation = self.dilation
  145. if dilate:
  146. self.dilation *= stride
  147. stride = 1
  148. if stride != 1 or self.inplanes != planes * block.expansion:
  149. downsample = nn.Sequential(
  150. conv1x1(self.inplanes, planes * block.expansion, stride), norm_layer(planes * block.expansion)
  151. )
  152. layers = []
  153. layers.append(
  154. block(
  155. self.inplanes, planes, stride, downsample, self.groups, self.base_width, previous_dilation, norm_layer
  156. )
  157. )
  158. self.inplanes = planes * block.expansion
  159. for _ in range(1, blocks):
  160. layers.append(
  161. block(
  162. self.inplanes,
  163. planes,
  164. groups=self.groups,
  165. base_width=self.base_width,
  166. dilation=self.dilation,
  167. norm_layer=norm_layer,
  168. )
  169. )
  170. return nn.Sequential(*layers)
  171. def _forward_impl(self, x: Tensor) -> Tensor:
  172. # See note [TorchScript super()]
  173. x = self.conv1(x)
  174. x = self.bn1(x)
  175. x = self.relu(x)
  176. x = self.maxpool(x)
  177. x = self.layer1(x)
  178. x = self.layer2(x)
  179. x = self.layer3(x)
  180. x = self.layer4(x)
  181. x = self.avgpool(x)
  182. x = torch.flatten(x, 1)
  183. x = self.fc(x)
  184. return x
  185. def forward(self, x: Tensor) -> Tensor:
  186. return self._forward_impl(x)
  187. class EncoderDeFMO(Module):
  188. def __init__(self) -> None:
  189. super().__init__()
  190. model = ResNet(Bottleneck, [3, 4, 6, 3]) # ResNet50
  191. modelc1 = nn.Sequential(*list(model.children())[:3])
  192. modelc2 = nn.Sequential(*list(model.children())[4:8])
  193. modelc1[0] = nn.Conv2d(6, 64, kernel_size=(7, 7), stride=(2, 2), padding=(3, 3), bias=False)
  194. self.net = nn.Sequential(modelc1, modelc2)
  195. def forward(self, input_data: Tensor) -> Tensor:
  196. return self.net(input_data)
  197. class RenderingDeFMO(Module):
  198. def __init__(self) -> None:
  199. super().__init__()
  200. self.tsr_steps: int = 24
  201. model = nn.Sequential(
  202. nn.Conv2d(2049, 1024, kernel_size=3, stride=1, padding=1, bias=False),
  203. nn.BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True),
  204. nn.ReLU(inplace=True),
  205. Bottleneck(1024, 256),
  206. nn.PixelShuffle(2),
  207. Bottleneck(256, 64),
  208. nn.PixelShuffle(2),
  209. Bottleneck(64, 16),
  210. nn.PixelShuffle(2),
  211. nn.Conv2d(16, 16, kernel_size=3, stride=1, padding=1, bias=False),
  212. nn.PixelShuffle(2),
  213. nn.Conv2d(4, 4, kernel_size=3, stride=1, padding=1, bias=True),
  214. nn.ReLU(inplace=True),
  215. nn.Conv2d(4, 4, kernel_size=3, stride=1, padding=1, bias=True),
  216. )
  217. self.net = model
  218. self.times = torch.linspace(0, 1, self.tsr_steps)
  219. def forward(self, latent: Tensor) -> Tensor:
  220. times = self.times.to(latent.device).unsqueeze(0).repeat(latent.shape[0], 1)
  221. renders = []
  222. for ki in range(times.shape[1]):
  223. t_tensor = (
  224. times[list(range(times.shape[0])), ki]
  225. .unsqueeze(-1)
  226. .unsqueeze(-1)
  227. .unsqueeze(-1)
  228. .repeat(1, 1, latent.shape[2], latent.shape[3])
  229. )
  230. latenti = concatenate((t_tensor, latent), 1)
  231. result = self.net(latenti)
  232. renders.append(result)
  233. renders_stacked = stack(renders, 1).contiguous()
  234. renders_stacked[:, :, :4] = torch.sigmoid(renders_stacked[:, :, :4])
  235. return renders_stacked
  236. class DeFMO(Module):
  237. """Module that disentangle a fast-moving object from the background and performs deblurring.
  238. This is based on the original code from paper "DeFMO: Deblurring and Shape Recovery
  239. of Fast Moving Objects". See :cite:`DeFMO2021` for more details.
  240. Args:
  241. pretrained: Download and set pretrained weights to the model. Default: false.
  242. Returns:
  243. Temporal super-resolution without background.
  244. Shape:
  245. - Input: (B, 6, H, W)
  246. - Output: (B, S, 4, H, W)
  247. Examples:
  248. >>> import kornia
  249. >>> input = torch.rand(2, 6, 240, 320)
  250. >>> defmo = kornia.feature.DeFMO()
  251. >>> tsr_nobgr = defmo(input) # 2x24x4x240x320
  252. """
  253. def __init__(self, pretrained: bool = False) -> None:
  254. super().__init__()
  255. self.encoder = EncoderDeFMO()
  256. self.rendering = RenderingDeFMO()
  257. # use torch.hub to load pretrained model
  258. if pretrained:
  259. pretrained_dict = torch.hub.load_state_dict_from_url(
  260. urls["defmo_encoder"], map_location=torch.device("cpu")
  261. )
  262. self.encoder.load_state_dict(pretrained_dict, strict=True)
  263. pretrained_dict_ren = torch.hub.load_state_dict_from_url(
  264. urls["defmo_rendering"], map_location=torch.device("cpu")
  265. )
  266. self.rendering.load_state_dict(pretrained_dict_ren, strict=True)
  267. self.eval()
  268. def forward(self, input_data: Tensor) -> Tensor:
  269. latent = self.encoder(input_data)
  270. x_out = self.rendering(latent)
  271. return x_out