refiner.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  1. import torch
  2. import torchvision
  3. from torch import nn
  4. from torch.nn import functional as F
  5. from typing import Tuple
  6. class Refiner(nn.Module):
  7. """
  8. Refiner refines the coarse output to full resolution.
  9. Args:
  10. mode: area selection mode. Options:
  11. "full" - No area selection, refine everywhere using regular Conv2d.
  12. "sampling" - Refine fixed amount of pixels ranked by the top most errors.
  13. "thresholding" - Refine varying amount of pixels that have greater error than the threshold.
  14. sample_pixels: number of pixels to refine. Only used when mode == "sampling".
  15. threshold: error threshold ranged from 0 ~ 1. Refine where err > threshold. Only used when mode == "thresholding".
  16. kernel_size: The convolution kernel_size. Options: [1, 3]
  17. prevent_oversampling: True for regular cases, False for speedtest.
  18. Compatibility Args:
  19. patch_crop_method: the operation for cropping patches. Options:
  20. "unfold" - Best performance for PyTorch and TorchScript.
  21. "roi_align" - Best compatibility for ONNX export.
  22. patch_replace_method: the operation for replacing patches. Options:
  23. "scatter_nd" - Best performance for PyTorch and TorchScript.
  24. "scatter_element" - Best compatibility for ONNX export.
  25. Input:
  26. src: (B, 3, H, W) full resolution source image.
  27. bgr: (B, 3, H, W) full resolution background image.
  28. pha: (B, 1, Hc, Wc) coarse alpha prediction.
  29. fgr: (B, 3, Hc, Wc) coarse foreground residual prediction.
  30. err: (B, 1, Hc, Hc) coarse error prediction.
  31. hid: (B, 32, Hc, Hc) coarse hidden encoding.
  32. Output:
  33. pha: (B, 1, H, W) full resolution alpha prediction.
  34. fgr: (B, 3, H, W) full resolution foreground residual prediction.
  35. ref: (B, 1, H/4, W/4) quarter resolution refinement selection map. 1 indicates refined 4x4 patch locations.
  36. """
  37. # For TorchScript export optimization.
  38. __constants__ = ['kernel_size', 'patch_crop_method', 'patch_replace_method']
  39. def __init__(self,
  40. mode: str,
  41. sample_pixels: int,
  42. threshold: float,
  43. kernel_size: int = 3,
  44. prevent_oversampling: bool = True,
  45. patch_crop_method: str = 'unfold',
  46. patch_replace_method: str = 'scatter_nd'):
  47. super().__init__()
  48. assert mode in ['full', 'sampling', 'thresholding']
  49. assert kernel_size in [1, 3]
  50. assert patch_crop_method in ['unfold', 'roi_align']
  51. assert patch_replace_method in ['scatter_nd', 'scatter_element']
  52. self.mode = mode
  53. self.sample_pixels = sample_pixels
  54. self.threshold = threshold
  55. self.kernel_size = kernel_size
  56. self.prevent_oversampling = prevent_oversampling
  57. self.patch_crop_method = patch_crop_method
  58. self.patch_replace_method = patch_replace_method
  59. channels = [32, 24, 16, 12, 4]
  60. self.conv1 = nn.Conv2d(channels[0] + 6 + 4, channels[1], kernel_size, bias=False)
  61. self.bn1 = nn.BatchNorm2d(channels[1])
  62. self.conv2 = nn.Conv2d(channels[1], channels[2], kernel_size, bias=False)
  63. self.bn2 = nn.BatchNorm2d(channels[2])
  64. self.conv3 = nn.Conv2d(channels[2] + 6, channels[3], kernel_size, bias=False)
  65. self.bn3 = nn.BatchNorm2d(channels[3])
  66. self.conv4 = nn.Conv2d(channels[3], channels[4], kernel_size, bias=True)
  67. self.relu = nn.ReLU(True)
  68. def forward(self,
  69. src: torch.Tensor,
  70. bgr: torch.Tensor,
  71. pha: torch.Tensor,
  72. fgr: torch.Tensor,
  73. err: torch.Tensor,
  74. hid: torch.Tensor):
  75. H_full, W_full = src.shape[2:]
  76. H_half, W_half = H_full // 2, W_full // 2
  77. H_quat, W_quat = H_full // 4, W_full // 4
  78. src_bgr = torch.cat([src, bgr], dim=1)
  79. if self.mode != 'full':
  80. err = F.interpolate(err, (H_quat, W_quat), mode='bilinear', align_corners=False)
  81. ref = self.select_refinement_regions(err)
  82. idx = torch.nonzero(ref.squeeze(1))
  83. idx = idx[:, 0], idx[:, 1], idx[:, 2]
  84. if idx[0].size(0) > 0:
  85. x = torch.cat([hid, pha, fgr], dim=1)
  86. x = F.interpolate(x, (H_half, W_half), mode='bilinear', align_corners=False)
  87. x = self.crop_patch(x, idx, 2, 3 if self.kernel_size == 3 else 0)
  88. y = F.interpolate(src_bgr, (H_half, W_half), mode='bilinear', align_corners=False)
  89. y = self.crop_patch(y, idx, 2, 3 if self.kernel_size == 3 else 0)
  90. x = self.conv1(torch.cat([x, y], dim=1))
  91. x = self.bn1(x)
  92. x = self.relu(x)
  93. x = self.conv2(x)
  94. x = self.bn2(x)
  95. x = self.relu(x)
  96. x = F.interpolate(x, 8 if self.kernel_size == 3 else 4, mode='nearest')
  97. y = self.crop_patch(src_bgr, idx, 4, 2 if self.kernel_size == 3 else 0)
  98. x = self.conv3(torch.cat([x, y], dim=1))
  99. x = self.bn3(x)
  100. x = self.relu(x)
  101. x = self.conv4(x)
  102. out = torch.cat([pha, fgr], dim=1)
  103. out = F.interpolate(out, (H_full, W_full), mode='bilinear', align_corners=False)
  104. out = self.replace_patch(out, x, idx)
  105. pha = out[:, :1]
  106. fgr = out[:, 1:]
  107. else:
  108. pha = F.interpolate(pha, (H_full, W_full), mode='bilinear', align_corners=False)
  109. fgr = F.interpolate(fgr, (H_full, W_full), mode='bilinear', align_corners=False)
  110. else:
  111. x = torch.cat([hid, pha, fgr], dim=1)
  112. x = F.interpolate(x, (H_half, W_half), mode='bilinear', align_corners=False)
  113. y = F.interpolate(src_bgr, (H_half, W_half), mode='bilinear', align_corners=False)
  114. if self.kernel_size == 3:
  115. x = F.pad(x, (3, 3, 3, 3))
  116. y = F.pad(y, (3, 3, 3, 3))
  117. x = self.conv1(torch.cat([x, y], dim=1))
  118. x = self.bn1(x)
  119. x = self.relu(x)
  120. x = self.conv2(x)
  121. x = self.bn2(x)
  122. x = self.relu(x)
  123. if self.kernel_size == 3:
  124. x = F.interpolate(x, (H_full + 4, W_full + 4))
  125. y = F.pad(src_bgr, (2, 2, 2, 2))
  126. else:
  127. x = F.interpolate(x, (H_full, W_full), mode='nearest')
  128. y = src_bgr
  129. x = self.conv3(torch.cat([x, y], dim=1))
  130. x = self.bn3(x)
  131. x = self.relu(x)
  132. x = self.conv4(x)
  133. pha = x[:, :1]
  134. fgr = x[:, 1:]
  135. ref = torch.ones((src.size(0), 1, H_quat, W_quat), device=src.device, dtype=src.dtype)
  136. return pha, fgr, ref
  137. def crop_patch(self,
  138. x: torch.Tensor,
  139. idx: Tuple[torch.Tensor, torch.Tensor, torch.Tensor],
  140. size: int,
  141. padding: int):
  142. """
  143. Crops selected patches from image given indices.
  144. Inputs:
  145. x: image (B, C, H, W).
  146. idx: selection indices Tuple[(P,), (P,), (P),], where the 3 values are (B, H, W) index.
  147. size: center size of the patch, also stride of the crop.
  148. padding: expansion size of the patch.
  149. Output:
  150. patch: (P, C, h, w), where h = w = size + 2 * padding.
  151. """
  152. if padding != 0:
  153. x = F.pad(x, (padding,) * 4)
  154. if self.patch_crop_method == 'unfold':
  155. # Use unfold. Best performance for PyTorch and TorchScript.
  156. return x.permute(0, 2, 3, 1) \
  157. .unfold(1, size + 2 * padding, size) \
  158. .unfold(2, size + 2 * padding, size)[idx[0], idx[1], idx[2]]
  159. else:
  160. # Use roi_align. Best compatibility for ONNX.
  161. idx = idx[0].type_as(x), idx[1].type_as(x), idx[2].type_as(x)
  162. b = idx[0]
  163. x1 = idx[2] * size - 0.5
  164. y1 = idx[1] * size - 0.5
  165. x2 = idx[2] * size + size + 2 * padding - 0.5
  166. y2 = idx[1] * size + size + 2 * padding - 0.5
  167. boxes = torch.stack([b, x1, y1, x2, y2], dim=1)
  168. return torchvision.ops.roi_align(x, boxes, size + 2 * padding, sampling_ratio=1)
  169. def replace_patch(self,
  170. x: torch.Tensor,
  171. y: torch.Tensor,
  172. idx: Tuple[torch.Tensor, torch.Tensor, torch.Tensor]):
  173. """
  174. Replaces patches back into image given index.
  175. Inputs:
  176. x: image (B, C, H, W)
  177. y: patches (P, C, h, w)
  178. idx: selection indices Tuple[(P,), (P,), (P,)] where the 3 values are (B, H, W) index.
  179. Output:
  180. image: (B, C, H, W), where patches at idx locations are replaced with y.
  181. """
  182. xB, xC, xH, xW = x.shape
  183. yB, yC, yH, yW = y.shape
  184. if self.patch_replace_method == 'scatter_nd':
  185. # Use scatter_nd. Best performance for PyTorch and TorchScript. Replacing patch by patch.
  186. x = x.view(xB, xC, xH // yH, yH, xW // yW, yW).permute(0, 2, 4, 1, 3, 5)
  187. x[idx[0], idx[1], idx[2]] = y
  188. x = x.permute(0, 3, 1, 4, 2, 5).view(xB, xC, xH, xW)
  189. return x
  190. else:
  191. # Use scatter_element. Best compatibility for ONNX. Replacing pixel by pixel.
  192. iH, iW = xH // yH, xW // yW
  193. i = self.crop_patch(torch.arange(0, xB * xC * xH * xW).view(xB, xC, xH, xW).type_as(x), idx, 4, 0)
  194. i, x, y = i.view(-1), x.view(-1), y.view(-1)
  195. x.scatter_(0, i.long(), y)
  196. x = x.view(xB, xC, xH, xW)
  197. return x
  198. def select_refinement_regions(self, err: torch.Tensor):
  199. """
  200. Select refinement regions.
  201. Input:
  202. err: error map (B, 1, H, W)
  203. Output:
  204. ref: refinement regions (B, 1, H, W). FloatTensor. 1 is selected, 0 is not.
  205. """
  206. if self.mode == 'sampling':
  207. # Sampling mode.
  208. b, _, h, w = err.shape
  209. err = err.view(b, -1)
  210. idx = err.topk(self.sample_pixels // 16, dim=1, sorted=False).indices
  211. ref = torch.zeros_like(err)
  212. ref.scatter_(1, idx, 1.)
  213. if self.prevent_oversampling:
  214. ref.mul_(err.gt(0).float())
  215. ref = ref.view(b, 1, h, w)
  216. else:
  217. # Thresholding mode.
  218. ref = err.gt(self.threshold).float()
  219. return ref