gca_enc.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  1. # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
  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.cvlibs import manager, param_init
  20. from paddleseg.utils import utils
  21. from ppmatting.models.layers import GuidedCxtAtten
  22. class ResNet_D(nn.Layer):
  23. def __init__(self,
  24. input_channels,
  25. layers,
  26. late_downsample=False,
  27. pretrained=None):
  28. super().__init__()
  29. self.pretrained = pretrained
  30. self._norm_layer = nn.BatchNorm
  31. self.inplanes = 64
  32. self.late_downsample = late_downsample
  33. self.midplanes = 64 if late_downsample else 32
  34. self.start_stride = [1, 2, 1, 2] if late_downsample else [2, 1, 2, 1]
  35. self.conv1 = nn.utils.spectral_norm(
  36. nn.Conv2D(
  37. input_channels,
  38. 32,
  39. kernel_size=3,
  40. stride=self.start_stride[0],
  41. padding=1,
  42. bias_attr=False))
  43. self.conv2 = nn.utils.spectral_norm(
  44. nn.Conv2D(
  45. 32,
  46. self.midplanes,
  47. kernel_size=3,
  48. stride=self.start_stride[1],
  49. padding=1,
  50. bias_attr=False))
  51. self.conv3 = nn.utils.spectral_norm(
  52. nn.Conv2D(
  53. self.midplanes,
  54. self.inplanes,
  55. kernel_size=3,
  56. stride=self.start_stride[2],
  57. padding=1,
  58. bias_attr=False))
  59. self.bn1 = self._norm_layer(32)
  60. self.bn2 = self._norm_layer(self.midplanes)
  61. self.bn3 = self._norm_layer(self.inplanes)
  62. self.activation = nn.ReLU()
  63. self.layer1 = self._make_layer(
  64. BasicBlock, 64, layers[0], stride=self.start_stride[3])
  65. self.layer2 = self._make_layer(BasicBlock, 128, layers[1], stride=2)
  66. self.layer3 = self._make_layer(BasicBlock, 256, layers[2], stride=2)
  67. self.layer_bottleneck = self._make_layer(
  68. BasicBlock, 512, layers[3], stride=2)
  69. self.init_weight()
  70. def _make_layer(self, block, planes, block_num, stride=1):
  71. if block_num == 0:
  72. return nn.Sequential(nn.Identity())
  73. norm_layer = self._norm_layer
  74. downsample = None
  75. if stride != 1:
  76. downsample = nn.Sequential(
  77. nn.AvgPool2D(2, stride),
  78. nn.utils.spectral_norm(
  79. conv1x1(self.inplanes, planes * block.expansion)),
  80. norm_layer(planes * block.expansion), )
  81. elif self.inplanes != planes * block.expansion:
  82. downsample = nn.Sequential(
  83. nn.utils.spectral_norm(
  84. conv1x1(self.inplanes, planes * block.expansion, stride)),
  85. norm_layer(planes * block.expansion), )
  86. layers = [block(self.inplanes, planes, stride, downsample, norm_layer)]
  87. self.inplanes = planes * block.expansion
  88. for _ in range(1, block_num):
  89. layers.append(block(self.inplanes, planes, norm_layer=norm_layer))
  90. return nn.Sequential(*layers)
  91. def forward(self, x):
  92. x = self.conv1(x)
  93. x = self.bn1(x)
  94. x = self.activation(x)
  95. x = self.conv2(x)
  96. x = self.bn2(x)
  97. x1 = self.activation(x) # N x 32 x 256 x 256
  98. x = self.conv3(x1)
  99. x = self.bn3(x)
  100. x2 = self.activation(x) # N x 64 x 128 x 128
  101. x3 = self.layer1(x2) # N x 64 x 128 x 128
  102. x4 = self.layer2(x3) # N x 128 x 64 x 64
  103. x5 = self.layer3(x4) # N x 256 x 32 x 32
  104. x = self.layer_bottleneck(x5) # N x 512 x 16 x 16
  105. return x, (x1, x2, x3, x4, x5)
  106. def init_weight(self):
  107. for layer in self.sublayers():
  108. if isinstance(layer, nn.Conv2D):
  109. if hasattr(layer, "weight_orig"):
  110. param = layer.weight_orig
  111. else:
  112. param = layer.weight
  113. param_init.xavier_uniform(param)
  114. elif isinstance(layer, (nn.BatchNorm, nn.SyncBatchNorm)):
  115. param_init.constant_init(layer.weight, value=1.0)
  116. param_init.constant_init(layer.bias, value=0.0)
  117. elif isinstance(layer, BasicBlock):
  118. param_init.constant_init(layer.bn2.weight, value=0.0)
  119. if self.pretrained is not None:
  120. utils.load_pretrained_model(self, self.pretrained)
  121. @manager.MODELS.add_component
  122. class ResShortCut_D(ResNet_D):
  123. def __init__(self,
  124. input_channels,
  125. layers,
  126. late_downsample=False,
  127. pretrained=None):
  128. super().__init__(
  129. input_channels,
  130. layers,
  131. late_downsample=late_downsample,
  132. pretrained=pretrained)
  133. self.shortcut_inplane = [input_channels, self.midplanes, 64, 128, 256]
  134. self.shortcut_plane = [32, self.midplanes, 64, 128, 256]
  135. self.shortcut = nn.LayerList()
  136. for stage, inplane in enumerate(self.shortcut_inplane):
  137. self.shortcut.append(
  138. self._make_shortcut(inplane, self.shortcut_plane[stage]))
  139. def _make_shortcut(self, inplane, planes):
  140. return nn.Sequential(
  141. nn.utils.spectral_norm(
  142. nn.Conv2D(
  143. inplane, planes, kernel_size=3, padding=1,
  144. bias_attr=False)),
  145. nn.ReLU(),
  146. self._norm_layer(planes),
  147. nn.utils.spectral_norm(
  148. nn.Conv2D(
  149. planes, planes, kernel_size=3, padding=1, bias_attr=False)),
  150. nn.ReLU(),
  151. self._norm_layer(planes))
  152. def forward(self, x):
  153. out = self.conv1(x)
  154. out = self.bn1(out)
  155. out = self.activation(out)
  156. out = self.conv2(out)
  157. out = self.bn2(out)
  158. x1 = self.activation(out) # N x 32 x 256 x 256
  159. out = self.conv3(x1)
  160. out = self.bn3(out)
  161. out = self.activation(out)
  162. x2 = self.layer1(out) # N x 64 x 128 x 128
  163. x3 = self.layer2(x2) # N x 128 x 64 x 64
  164. x4 = self.layer3(x3) # N x 256 x 32 x 32
  165. out = self.layer_bottleneck(x4) # N x 512 x 16 x 16
  166. fea1 = self.shortcut[0](x) # input image and trimap
  167. fea2 = self.shortcut[1](x1)
  168. fea3 = self.shortcut[2](x2)
  169. fea4 = self.shortcut[3](x3)
  170. fea5 = self.shortcut[4](x4)
  171. return out, {
  172. 'shortcut': (fea1, fea2, fea3, fea4, fea5),
  173. 'image': x[:, :3, ...]
  174. }
  175. @manager.MODELS.add_component
  176. class ResGuidedCxtAtten(ResNet_D):
  177. def __init__(self,
  178. input_channels,
  179. layers,
  180. late_downsample=False,
  181. pretrained=None):
  182. super().__init__(
  183. input_channels,
  184. layers,
  185. late_downsample=late_downsample,
  186. pretrained=pretrained)
  187. self.input_channels = input_channels
  188. self.shortcut_inplane = [input_channels, self.midplanes, 64, 128, 256]
  189. self.shortcut_plane = [32, self.midplanes, 64, 128, 256]
  190. self.shortcut = nn.LayerList()
  191. for stage, inplane in enumerate(self.shortcut_inplane):
  192. self.shortcut.append(
  193. self._make_shortcut(inplane, self.shortcut_plane[stage]))
  194. self.guidance_head = nn.Sequential(
  195. nn.Pad2D(
  196. 1, mode="reflect"),
  197. nn.utils.spectral_norm(
  198. nn.Conv2D(
  199. 3, 16, kernel_size=3, padding=0, stride=2,
  200. bias_attr=False)),
  201. nn.ReLU(),
  202. self._norm_layer(16),
  203. nn.Pad2D(
  204. 1, mode="reflect"),
  205. nn.utils.spectral_norm(
  206. nn.Conv2D(
  207. 16, 32, kernel_size=3, padding=0, stride=2,
  208. bias_attr=False)),
  209. nn.ReLU(),
  210. self._norm_layer(32),
  211. nn.Pad2D(
  212. 1, mode="reflect"),
  213. nn.utils.spectral_norm(
  214. nn.Conv2D(
  215. 32,
  216. 128,
  217. kernel_size=3,
  218. padding=0,
  219. stride=2,
  220. bias_attr=False)),
  221. nn.ReLU(),
  222. self._norm_layer(128))
  223. self.gca = GuidedCxtAtten(128, 128)
  224. self.init_weight()
  225. def init_weight(self):
  226. for layer in self.sublayers():
  227. if isinstance(layer, nn.Conv2D):
  228. initializer = nn.initializer.XavierUniform()
  229. if hasattr(layer, "weight_orig"):
  230. param = layer.weight_orig
  231. else:
  232. param = layer.weight
  233. initializer(param, param.block)
  234. elif isinstance(layer, (nn.BatchNorm, nn.SyncBatchNorm)):
  235. param_init.constant_init(layer.weight, value=1.0)
  236. param_init.constant_init(layer.bias, value=0.0)
  237. elif isinstance(layer, BasicBlock):
  238. param_init.constant_init(layer.bn2.weight, value=0.0)
  239. if self.pretrained is not None:
  240. utils.load_pretrained_model(self, self.pretrained)
  241. def _make_shortcut(self, inplane, planes):
  242. return nn.Sequential(
  243. nn.utils.spectral_norm(
  244. nn.Conv2D(
  245. inplane, planes, kernel_size=3, padding=1,
  246. bias_attr=False)),
  247. nn.ReLU(),
  248. self._norm_layer(planes),
  249. nn.utils.spectral_norm(
  250. nn.Conv2D(
  251. planes, planes, kernel_size=3, padding=1, bias_attr=False)),
  252. nn.ReLU(),
  253. self._norm_layer(planes))
  254. def forward(self, x):
  255. out = self.conv1(x)
  256. out = self.bn1(out)
  257. out = self.activation(out)
  258. out = self.conv2(out)
  259. out = self.bn2(out)
  260. x1 = self.activation(out) # N x 32 x 256 x 256
  261. out = self.conv3(x1)
  262. out = self.bn3(out)
  263. out = self.activation(out)
  264. im_fea = self.guidance_head(
  265. x[:, :3, ...]) # downsample origin image and extract features
  266. if self.input_channels == 6:
  267. unknown = F.interpolate(
  268. x[:, 4:5, ...], scale_factor=1 / 8, mode='nearest')
  269. else:
  270. unknown = x[:, 3:, ...].equal(paddle.to_tensor([1.]))
  271. unknown = paddle.cast(unknown, dtype='float32')
  272. unknown = F.interpolate(unknown, scale_factor=1 / 8, mode='nearest')
  273. x2 = self.layer1(out) # N x 64 x 128 x 128
  274. x3 = self.layer2(x2) # N x 128 x 64 x 64
  275. x3 = self.gca(im_fea, x3, unknown) # contextual attention
  276. x4 = self.layer3(x3) # N x 256 x 32 x 32
  277. out = self.layer_bottleneck(x4) # N x 512 x 16 x 16
  278. fea1 = self.shortcut[0](x) # input image and trimap
  279. fea2 = self.shortcut[1](x1)
  280. fea3 = self.shortcut[2](x2)
  281. fea4 = self.shortcut[3](x3)
  282. fea5 = self.shortcut[4](x4)
  283. return out, {
  284. 'shortcut': (fea1, fea2, fea3, fea4, fea5),
  285. 'image_fea': im_fea,
  286. 'unknown': unknown,
  287. }
  288. class BasicBlock(nn.Layer):
  289. expansion = 1
  290. def __init__(self,
  291. inplanes,
  292. planes,
  293. stride=1,
  294. downsample=None,
  295. norm_layer=None):
  296. super().__init__()
  297. if norm_layer is None:
  298. norm_layer = nn.BatchNorm
  299. # Both self.conv1 and self.downsample layers downsample the input when stride != 1
  300. self.conv1 = nn.utils.spectral_norm(conv3x3(inplanes, planes, stride))
  301. self.bn1 = norm_layer(planes)
  302. self.activation = nn.ReLU()
  303. self.conv2 = nn.utils.spectral_norm(conv3x3(planes, planes))
  304. self.bn2 = norm_layer(planes)
  305. self.downsample = downsample
  306. self.stride = stride
  307. def forward(self, x):
  308. identity = x
  309. out = self.conv1(x)
  310. out = self.bn1(out)
  311. out = self.activation(out)
  312. out = self.conv2(out)
  313. out = self.bn2(out)
  314. if self.downsample is not None:
  315. identity = self.downsample(x)
  316. out += identity
  317. out = self.activation(out)
  318. return out
  319. def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1):
  320. """3x3 convolution with padding"""
  321. return nn.Conv2D(
  322. in_planes,
  323. out_planes,
  324. kernel_size=3,
  325. stride=stride,
  326. padding=dilation,
  327. groups=groups,
  328. bias_attr=False,
  329. dilation=dilation)
  330. def conv1x1(in_planes, out_planes, stride=1):
  331. """1x1 convolution"""
  332. return nn.Conv2D(
  333. in_planes, out_planes, kernel_size=1, stride=stride, bias_attr=False)