decoder.py 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  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 Any, Optional, Tuple
  18. import torch
  19. from torch import nn
  20. from kornia.core import Tensor
  21. class Decoder(nn.Module):
  22. def __init__(self, layers: Any, *args, super_resolution: bool = False, num_prototypes: int = 1, **kwargs) -> None: # type: ignore[no-untyped-def]
  23. super().__init__(*args, **kwargs)
  24. self.layers = layers
  25. self.scales = self.layers.keys()
  26. self.super_resolution = super_resolution
  27. self.num_prototypes = num_prototypes
  28. def forward(
  29. self, features: Tensor, context: Optional[Tensor] = None, scale: Optional[int] = None
  30. ) -> Tuple[Tensor, Optional[Tensor]]:
  31. if context is not None:
  32. features = torch.cat((features, context), dim=1)
  33. stuff = self.layers[scale](features)
  34. logits, context = stuff[:, : self.num_prototypes], stuff[:, self.num_prototypes :]
  35. return logits, context
  36. class ConvRefiner(nn.Module):
  37. def __init__( # type: ignore[no-untyped-def]
  38. self,
  39. in_dim=6,
  40. hidden_dim=16,
  41. out_dim=2,
  42. dw=True,
  43. kernel_size=5,
  44. hidden_blocks=5,
  45. amp=True,
  46. residual=False,
  47. amp_dtype=torch.float16,
  48. ):
  49. super().__init__()
  50. self.block1 = self.create_block(
  51. in_dim,
  52. hidden_dim,
  53. dw=False,
  54. kernel_size=1,
  55. )
  56. self.hidden_blocks = nn.Sequential(
  57. *[
  58. self.create_block(
  59. hidden_dim,
  60. hidden_dim,
  61. dw=dw,
  62. kernel_size=kernel_size,
  63. )
  64. for hb in range(hidden_blocks)
  65. ]
  66. )
  67. self.hidden_blocks = self.hidden_blocks
  68. self.out_conv = nn.Conv2d(hidden_dim, out_dim, 1, 1, 0)
  69. self.amp = amp
  70. self.amp_dtype = amp_dtype
  71. self.residual = residual
  72. def create_block( # type: ignore[no-untyped-def]
  73. self,
  74. in_dim,
  75. out_dim,
  76. dw=True,
  77. kernel_size=5,
  78. bias=True,
  79. norm_type=nn.BatchNorm2d,
  80. ):
  81. num_groups = 1 if not dw else in_dim
  82. if dw:
  83. if out_dim % in_dim != 0:
  84. raise Exception("outdim must be divisible by indim for depthwise")
  85. conv1 = nn.Conv2d(
  86. in_dim,
  87. out_dim,
  88. kernel_size=kernel_size,
  89. stride=1,
  90. padding=kernel_size // 2,
  91. groups=num_groups,
  92. bias=bias,
  93. )
  94. norm = norm_type(out_dim) if norm_type is nn.BatchNorm2d else norm_type(num_channels=out_dim)
  95. relu = nn.ReLU(inplace=True)
  96. conv2 = nn.Conv2d(out_dim, out_dim, 1, 1, 0)
  97. return nn.Sequential(conv1, norm, relu, conv2)
  98. def forward(self, feats: Tensor) -> Tensor:
  99. _b, _c, _hs, _ws = feats.shape
  100. with torch.autocast("cuda", enabled=self.amp, dtype=self.amp_dtype):
  101. x0 = self.block1(feats)
  102. x = self.hidden_blocks(x0)
  103. if self.residual:
  104. x = (x + x0) / 1.4
  105. x = self.out_conv(x)
  106. return x