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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
import torch
|
| 3 |
+
from torch import nn as nn
|
| 4 |
+
from torch.nn import functional as F
|
| 5 |
+
from torch.nn import init as init
|
| 6 |
+
from torch.nn.modules.batchnorm import _BatchNorm
|
| 7 |
+
|
| 8 |
+
@torch.no_grad()
|
| 9 |
+
def default_init_weights(module_list, scale=1, bias_fill=0, **kwargs):
|
| 10 |
+
"""Initialize network weights.
|
| 11 |
+
|
| 12 |
+
Args:
|
| 13 |
+
module_list (list[nn.Module] | nn.Module): Modules to be initialized.
|
| 14 |
+
scale (float): Scale initialized weights, especially for residual
|
| 15 |
+
blocks. Default: 1.
|
| 16 |
+
bias_fill (float): The value to fill bias. Default: 0
|
| 17 |
+
kwargs (dict): Other arguments for initialization function.
|
| 18 |
+
"""
|
| 19 |
+
if not isinstance(module_list, list):
|
| 20 |
+
module_list = [module_list]
|
| 21 |
+
for module in module_list:
|
| 22 |
+
for m in module.modules():
|
| 23 |
+
if isinstance(m, nn.Conv2d):
|
| 24 |
+
init.kaiming_normal_(m.weight, **kwargs)
|
| 25 |
+
m.weight.data *= scale
|
| 26 |
+
if m.bias is not None:
|
| 27 |
+
m.bias.data.fill_(bias_fill)
|
| 28 |
+
elif isinstance(m, nn.Linear):
|
| 29 |
+
init.kaiming_normal_(m.weight, **kwargs)
|
| 30 |
+
m.weight.data *= scale
|
| 31 |
+
if m.bias is not None:
|
| 32 |
+
m.bias.data.fill_(bias_fill)
|
| 33 |
+
elif isinstance(m, _BatchNorm):
|
| 34 |
+
init.constant_(m.weight, 1)
|
| 35 |
+
if m.bias is not None:
|
| 36 |
+
m.bias.data.fill_(bias_fill)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def make_layer(basic_block, num_basic_block, **kwarg):
|
| 40 |
+
"""Make layers by stacking the same blocks.
|
| 41 |
+
|
| 42 |
+
Args:
|
| 43 |
+
basic_block (nn.module): nn.module class for basic block.
|
| 44 |
+
num_basic_block (int): number of blocks.
|
| 45 |
+
|
| 46 |
+
Returns:
|
| 47 |
+
nn.Sequential: Stacked blocks in nn.Sequential.
|
| 48 |
+
"""
|
| 49 |
+
layers = []
|
| 50 |
+
for _ in range(num_basic_block):
|
| 51 |
+
layers.append(basic_block(**kwarg))
|
| 52 |
+
return nn.Sequential(*layers)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
class ResidualBlockNoBN(nn.Module):
|
| 56 |
+
"""Residual block without BN.
|
| 57 |
+
|
| 58 |
+
It has a style of:
|
| 59 |
+
---Conv-ReLU-Conv-+-
|
| 60 |
+
|________________|
|
| 61 |
+
|
| 62 |
+
Args:
|
| 63 |
+
num_feat (int): Channel number of intermediate features.
|
| 64 |
+
Default: 64.
|
| 65 |
+
res_scale (float): Residual scale. Default: 1.
|
| 66 |
+
pytorch_init (bool): If set to True, use pytorch default init,
|
| 67 |
+
otherwise, use default_init_weights. Default: False.
|
| 68 |
+
"""
|
| 69 |
+
|
| 70 |
+
def __init__(self, num_feat=64, res_scale=1, pytorch_init=False):
|
| 71 |
+
super(ResidualBlockNoBN, self).__init__()
|
| 72 |
+
self.res_scale = res_scale
|
| 73 |
+
self.conv1 = nn.Conv2d(num_feat, num_feat, 3, 1, 1, bias=True)
|
| 74 |
+
self.conv2 = nn.Conv2d(num_feat, num_feat, 3, 1, 1, bias=True)
|
| 75 |
+
self.relu = nn.ReLU(inplace=True)
|
| 76 |
+
|
| 77 |
+
if not pytorch_init:
|
| 78 |
+
default_init_weights([self.conv1, self.conv2], 0.1)
|
| 79 |
+
|
| 80 |
+
def forward(self, x):
|
| 81 |
+
identity = x
|
| 82 |
+
out = self.conv2(self.relu(self.conv1(x)))
|
| 83 |
+
return identity + out * self.res_scale
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
class Upsample(nn.Sequential):
|
| 87 |
+
"""Upsample module.
|
| 88 |
+
|
| 89 |
+
Args:
|
| 90 |
+
scale (int): Scale factor. Supported scales: 2^n and 3.
|
| 91 |
+
num_feat (int): Channel number of intermediate features.
|
| 92 |
+
"""
|
| 93 |
+
|
| 94 |
+
def __init__(self, scale, num_feat):
|
| 95 |
+
m = []
|
| 96 |
+
if (scale & (scale - 1)) == 0: # scale = 2^n
|
| 97 |
+
for _ in range(int(math.log(scale, 2))):
|
| 98 |
+
m.append(nn.Conv2d(num_feat, 4 * num_feat, 3, 1, 1))
|
| 99 |
+
m.append(nn.PixelShuffle(2))
|
| 100 |
+
elif scale == 3:
|
| 101 |
+
m.append(nn.Conv2d(num_feat, 9 * num_feat, 3, 1, 1))
|
| 102 |
+
m.append(nn.PixelShuffle(3))
|
| 103 |
+
else:
|
| 104 |
+
raise ValueError(f'scale {scale} is not supported. ' 'Supported scales: 2^n and 3.')
|
| 105 |
+
super(Upsample, self).__init__(*m)
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def flow_warp(x, flow, interp_mode='bilinear', padding_mode='zeros', align_corners=True):
|
| 109 |
+
"""Warp an image or feature map with optical flow.
|
| 110 |
+
|
| 111 |
+
Args:
|
| 112 |
+
x (Tensor): Tensor with size (n, c, h, w).
|
| 113 |
+
flow (Tensor): Tensor with size (n, h, w, 2), normal value.
|
| 114 |
+
interp_mode (str): 'nearest' or 'bilinear'. Default: 'bilinear'.
|
| 115 |
+
padding_mode (str): 'zeros' or 'border' or 'reflection'.
|
| 116 |
+
Default: 'zeros'.
|
| 117 |
+
align_corners (bool): Before pytorch 1.3, the default value is
|
| 118 |
+
align_corners=True. After pytorch 1.3, the default value is
|
| 119 |
+
align_corners=False. Here, we use the True as default.
|
| 120 |
+
|
| 121 |
+
Returns:
|
| 122 |
+
Tensor: Warped image or feature map.
|
| 123 |
+
"""
|
| 124 |
+
assert x.size()[-2:] == flow.size()[1:3]
|
| 125 |
+
_, _, h, w = x.size()
|
| 126 |
+
# create mesh grid
|
| 127 |
+
grid_y, grid_x = torch.meshgrid(torch.arange(0, h).type_as(x), torch.arange(0, w).type_as(x))
|
| 128 |
+
grid = torch.stack((grid_x, grid_y), 2).float() # W(x), H(y), 2
|
| 129 |
+
grid.requires_grad = False
|
| 130 |
+
|
| 131 |
+
vgrid = grid + flow
|
| 132 |
+
# scale grid to [-1,1]
|
| 133 |
+
vgrid_x = 2.0 * vgrid[:, :, :, 0] / max(w - 1, 1) - 1.0
|
| 134 |
+
vgrid_y = 2.0 * vgrid[:, :, :, 1] / max(h - 1, 1) - 1.0
|
| 135 |
+
vgrid_scaled = torch.stack((vgrid_x, vgrid_y), dim=3)
|
| 136 |
+
output = F.grid_sample(x, vgrid_scaled, mode=interp_mode, padding_mode=padding_mode, align_corners=align_corners)
|
| 137 |
+
|
| 138 |
+
# TODO, what if align_corners=False
|
| 139 |
+
return output
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
def resize_flow(flow, size_type, sizes, interp_mode='bilinear', align_corners=False):
|
| 143 |
+
"""Resize a flow according to ratio or shape.
|
| 144 |
+
|
| 145 |
+
Args:
|
| 146 |
+
flow (Tensor): Precomputed flow. shape [N, 2, H, W].
|
| 147 |
+
size_type (str): 'ratio' or 'shape'.
|
| 148 |
+
sizes (list[int | float]): the ratio for resizing or the final output
|
| 149 |
+
shape.
|
| 150 |
+
1) The order of ratio should be [ratio_h, ratio_w]. For
|
| 151 |
+
downsampling, the ratio should be smaller than 1.0 (i.e., ratio
|
| 152 |
+
< 1.0). For upsampling, the ratio should be larger than 1.0 (i.e.,
|
| 153 |
+
ratio > 1.0).
|
| 154 |
+
2) The order of output_size should be [out_h, out_w].
|
| 155 |
+
interp_mode (str): The mode of interpolation for resizing.
|
| 156 |
+
Default: 'bilinear'.
|
| 157 |
+
align_corners (bool): Whether align corners. Default: False.
|
| 158 |
+
|
| 159 |
+
Returns:
|
| 160 |
+
Tensor: Resized flow.
|
| 161 |
+
"""
|
| 162 |
+
_, _, flow_h, flow_w = flow.size()
|
| 163 |
+
if size_type == 'ratio':
|
| 164 |
+
output_h, output_w = int(flow_h * sizes[0]), int(flow_w * sizes[1])
|
| 165 |
+
elif size_type == 'shape':
|
| 166 |
+
output_h, output_w = sizes[0], sizes[1]
|
| 167 |
+
else:
|
| 168 |
+
raise ValueError(f'Size type should be ratio or shape, but got type {size_type}.')
|
| 169 |
+
|
| 170 |
+
input_flow = flow.clone()
|
| 171 |
+
ratio_h = output_h / flow_h
|
| 172 |
+
ratio_w = output_w / flow_w
|
| 173 |
+
input_flow[:, 0, :, :] *= ratio_w
|
| 174 |
+
input_flow[:, 1, :, :] *= ratio_h
|
| 175 |
+
resized_flow = F.interpolate(
|
| 176 |
+
input=input_flow, size=(output_h, output_w), mode=interp_mode, align_corners=align_corners)
|
| 177 |
+
return resized_flow
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
# TODO: may write a cpp file
|
| 181 |
+
def pixel_unshuffle(x, scale):
|
| 182 |
+
""" Pixel unshuffle.
|
| 183 |
+
|
| 184 |
+
Args:
|
| 185 |
+
x (Tensor): Input feature with shape (b, c, hh, hw).
|
| 186 |
+
scale (int): Downsample ratio.
|
| 187 |
+
|
| 188 |
+
Returns:
|
| 189 |
+
Tensor: the pixel unshuffled feature.
|
| 190 |
+
"""
|
| 191 |
+
b, c, hh, hw = x.size()
|
| 192 |
+
out_channel = c * (scale**2)
|
| 193 |
+
assert hh % scale == 0 and hw % scale == 0
|
| 194 |
+
h = hh // scale
|
| 195 |
+
w = hw // scale
|
| 196 |
+
x_view = x.view(b, c, h, scale, w, scale)
|
| 197 |
+
return x_view.permute(0, 1, 3, 5, 2, 4).reshape(b, out_channel, h, w)
|