gca.py 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  1. # copyright (c) 2022 PaddlePaddle Authors. All Rights Reserve.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. # The gca code was heavily based on https://github.com/Yaoyi-Li/GCA-Matting
  15. # and https://github.com/open-mmlab/mmediting
  16. import paddle
  17. import paddle.nn as nn
  18. import paddle.nn.functional as F
  19. from paddleseg.models import layers
  20. from paddleseg import utils
  21. from paddleseg.cvlibs import manager, param_init
  22. from ppmatting.models.layers import GuidedCxtAtten
  23. @manager.MODELS.add_component
  24. class GCABaseline(nn.Layer):
  25. def __init__(self, backbone, pretrained=None):
  26. super().__init__()
  27. self.encoder = backbone
  28. self.decoder = ResShortCut_D_Dec([2, 3, 3, 2])
  29. def forward(self, inputs):
  30. x = paddle.concat([inputs['img'], inputs['trimap'] / 255], axis=1)
  31. embedding, mid_fea = self.encoder(x)
  32. alpha_pred = self.decoder(embedding, mid_fea)
  33. if self.training:
  34. logit_dict = {'alpha_pred': alpha_pred, }
  35. loss_dict = {}
  36. alpha_gt = inputs['alpha']
  37. loss_dict["alpha"] = F.l1_loss(alpha_pred, alpha_gt)
  38. loss_dict["all"] = loss_dict["alpha"]
  39. return logit_dict, loss_dict
  40. return alpha_pred
  41. @manager.MODELS.add_component
  42. class GCA(GCABaseline):
  43. def __init__(self, backbone, pretrained=None):
  44. super().__init__(backbone, pretrained)
  45. self.decoder = ResGuidedCxtAtten_Dec([2, 3, 3, 2])
  46. def conv5x5(in_planes, out_planes, stride=1, groups=1, dilation=1):
  47. """5x5 convolution with padding"""
  48. return nn.Conv2D(
  49. in_planes,
  50. out_planes,
  51. kernel_size=5,
  52. stride=stride,
  53. padding=2,
  54. groups=groups,
  55. bias_attr=False,
  56. dilation=dilation)
  57. def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1):
  58. """3x3 convolution with padding"""
  59. return nn.Conv2D(
  60. in_planes,
  61. out_planes,
  62. kernel_size=3,
  63. stride=stride,
  64. padding=dilation,
  65. groups=groups,
  66. bias_attr=False,
  67. dilation=dilation)
  68. def conv1x1(in_planes, out_planes, stride=1):
  69. """1x1 convolution"""
  70. return nn.Conv2D(
  71. in_planes, out_planes, kernel_size=1, stride=stride, bias_attr=False)
  72. class BasicBlock(nn.Layer):
  73. expansion = 1
  74. def __init__(self,
  75. inplanes,
  76. planes,
  77. stride=1,
  78. upsample=None,
  79. norm_layer=None,
  80. large_kernel=False):
  81. super().__init__()
  82. if norm_layer is None:
  83. norm_layer = nn.BatchNorm
  84. self.stride = stride
  85. conv = conv5x5 if large_kernel else conv3x3
  86. # Both self.conv1 and self.downsample layers downsample the input when stride != 1
  87. if self.stride > 1:
  88. self.conv1 = nn.utils.spectral_norm(
  89. nn.Conv2DTranspose(
  90. inplanes,
  91. inplanes,
  92. kernel_size=4,
  93. stride=2,
  94. padding=1,
  95. bias_attr=False))
  96. else:
  97. self.conv1 = nn.utils.spectral_norm(conv(inplanes, inplanes))
  98. self.bn1 = norm_layer(inplanes)
  99. self.activation = nn.LeakyReLU(0.2)
  100. self.conv2 = nn.utils.spectral_norm(conv(inplanes, planes))
  101. self.bn2 = norm_layer(planes)
  102. self.upsample = upsample
  103. def forward(self, x):
  104. identity = x
  105. out = self.conv1(x)
  106. out = self.bn1(out)
  107. out = self.activation(out)
  108. out = self.conv2(out)
  109. out = self.bn2(out)
  110. if self.upsample is not None:
  111. identity = self.upsample(x)
  112. out += identity
  113. out = self.activation(out)
  114. return out
  115. class ResNet_D_Dec(nn.Layer):
  116. def __init__(self,
  117. layers=[3, 4, 4, 2],
  118. norm_layer=None,
  119. large_kernel=False,
  120. late_downsample=False):
  121. super().__init__()
  122. if norm_layer is None:
  123. norm_layer = nn.BatchNorm
  124. self._norm_layer = norm_layer
  125. self.large_kernel = large_kernel
  126. self.kernel_size = 5 if self.large_kernel else 3
  127. self.inplanes = 512 if layers[0] > 0 else 256
  128. self.late_downsample = late_downsample
  129. self.midplanes = 64 if late_downsample else 32
  130. self.conv1 = nn.utils.spectral_norm(
  131. nn.Conv2DTranspose(
  132. self.midplanes,
  133. 32,
  134. kernel_size=4,
  135. stride=2,
  136. padding=1,
  137. bias_attr=False))
  138. self.bn1 = norm_layer(32)
  139. self.leaky_relu = nn.LeakyReLU(0.2)
  140. self.conv2 = nn.Conv2D(
  141. 32,
  142. 1,
  143. kernel_size=self.kernel_size,
  144. stride=1,
  145. padding=self.kernel_size // 2)
  146. self.upsample = nn.UpsamplingNearest2D(scale_factor=2)
  147. self.tanh = nn.Tanh()
  148. self.layer1 = self._make_layer(BasicBlock, 256, layers[0], stride=2)
  149. self.layer2 = self._make_layer(BasicBlock, 128, layers[1], stride=2)
  150. self.layer3 = self._make_layer(BasicBlock, 64, layers[2], stride=2)
  151. self.layer4 = self._make_layer(
  152. BasicBlock, self.midplanes, layers[3], stride=2)
  153. self.init_weight()
  154. def _make_layer(self, block, planes, blocks, stride=1):
  155. if blocks == 0:
  156. return nn.Sequential(nn.Identity())
  157. norm_layer = self._norm_layer
  158. upsample = None
  159. if stride != 1:
  160. upsample = nn.Sequential(
  161. nn.UpsamplingNearest2D(scale_factor=2),
  162. nn.utils.spectral_norm(
  163. conv1x1(self.inplanes, planes * block.expansion)),
  164. norm_layer(planes * block.expansion), )
  165. elif self.inplanes != planes * block.expansion:
  166. upsample = nn.Sequential(
  167. nn.utils.spectral_norm(
  168. conv1x1(self.inplanes, planes * block.expansion)),
  169. norm_layer(planes * block.expansion), )
  170. layers = [
  171. block(self.inplanes, planes, stride, upsample, norm_layer,
  172. self.large_kernel)
  173. ]
  174. self.inplanes = planes * block.expansion
  175. for _ in range(1, blocks):
  176. layers.append(
  177. block(
  178. self.inplanes,
  179. planes,
  180. norm_layer=norm_layer,
  181. large_kernel=self.large_kernel))
  182. return nn.Sequential(*layers)
  183. def forward(self, x, mid_fea):
  184. x = self.layer1(x) # N x 256 x 32 x 32
  185. print(x.shape)
  186. x = self.layer2(x) # N x 128 x 64 x 64
  187. print(x.shape)
  188. x = self.layer3(x) # N x 64 x 128 x 128
  189. print(x.shape)
  190. x = self.layer4(x) # N x 32 x 256 x 256
  191. print(x.shape)
  192. x = self.conv1(x)
  193. x = self.bn1(x)
  194. x = self.leaky_relu(x)
  195. x = self.conv2(x)
  196. alpha = (self.tanh(x) + 1.0) / 2.0
  197. return alpha
  198. def init_weight(self):
  199. for layer in self.sublayers():
  200. if isinstance(layer, nn.Conv2D):
  201. if hasattr(layer, "weight_orig"):
  202. param = layer.weight_orig
  203. else:
  204. param = layer.weight
  205. param_init.xavier_uniform(param)
  206. elif isinstance(layer, (nn.BatchNorm, nn.SyncBatchNorm)):
  207. param_init.constant_init(layer.weight, value=1.0)
  208. param_init.constant_init(layer.bias, value=0.0)
  209. elif isinstance(layer, BasicBlock):
  210. param_init.constant_init(layer.bn2.weight, value=0.0)
  211. class ResShortCut_D_Dec(ResNet_D_Dec):
  212. def __init__(self,
  213. layers,
  214. norm_layer=None,
  215. large_kernel=False,
  216. late_downsample=False):
  217. super().__init__(
  218. layers, norm_layer, large_kernel, late_downsample=late_downsample)
  219. def forward(self, x, mid_fea):
  220. fea1, fea2, fea3, fea4, fea5 = mid_fea['shortcut']
  221. x = self.layer1(x) + fea5
  222. x = self.layer2(x) + fea4
  223. x = self.layer3(x) + fea3
  224. x = self.layer4(x) + fea2
  225. x = self.conv1(x)
  226. x = self.bn1(x)
  227. x = self.leaky_relu(x) + fea1
  228. x = self.conv2(x)
  229. alpha = (self.tanh(x) + 1.0) / 2.0
  230. return alpha
  231. class ResGuidedCxtAtten_Dec(ResNet_D_Dec):
  232. def __init__(self,
  233. layers,
  234. norm_layer=None,
  235. large_kernel=False,
  236. late_downsample=False):
  237. super().__init__(
  238. layers, norm_layer, large_kernel, late_downsample=late_downsample)
  239. self.gca = GuidedCxtAtten(128, 128)
  240. def forward(self, x, mid_fea):
  241. fea1, fea2, fea3, fea4, fea5 = mid_fea['shortcut']
  242. im = mid_fea['image_fea']
  243. x = self.layer1(x) + fea5 # N x 256 x 32 x 32
  244. x = self.layer2(x) + fea4 # N x 128 x 64 x 64
  245. x = self.gca(im, x, mid_fea['unknown']) # contextual attention
  246. x = self.layer3(x) + fea3 # N x 64 x 128 x 128
  247. x = self.layer4(x) + fea2 # N x 32 x 256 x 256
  248. x = self.conv1(x)
  249. x = self.bn1(x)
  250. x = self.leaky_relu(x) + fea1
  251. x = self.conv2(x)
  252. alpha = (self.tanh(x) + 1.0) / 2.0
  253. return alpha