Applies padding to input (if needed) so that input can get fully covered by filter you specified. It support two modes "same" and "corner". The "same" mode is same with "SAME" padding mode in TensorFlow, pad zero around input. The "corner" mode would pad zero to bottom right. Args:
| 10 | |
| 11 | |
| 12 | class AdaptivePadding(nn.Module): |
| 13 | """Applies padding to input (if needed) so that input can get fully covered |
| 14 | by filter you specified. It support two modes "same" and "corner". The |
| 15 | "same" mode is same with "SAME" padding mode in TensorFlow, pad zero around |
| 16 | input. The "corner" mode would pad zero to bottom right. |
| 17 | |
| 18 | Args: |
| 19 | kernel_size (int | tuple): Size of the kernel: |
| 20 | stride (int | tuple): Stride of the filter. Default: 1: |
| 21 | dilation (int | tuple): Spacing between kernel elements. |
| 22 | Default: 1. |
| 23 | padding (str): Support "same" and "corner", "corner" mode |
| 24 | would pad zero to bottom right, and "same" mode would |
| 25 | pad zero around input. Default: "corner". |
| 26 | Example: |
| 27 | >>> kernel_size = 16 |
| 28 | >>> stride = 16 |
| 29 | >>> dilation = 1 |
| 30 | >>> input = torch.rand(1, 1, 15, 17) |
| 31 | >>> adap_pad = AdaptivePadding( |
| 32 | >>> kernel_size=kernel_size, |
| 33 | >>> stride=stride, |
| 34 | >>> dilation=dilation, |
| 35 | >>> padding="corner") |
| 36 | >>> out = adap_pad(input) |
| 37 | >>> assert (out.shape[2], out.shape[3]) == (16, 32) |
| 38 | >>> input = torch.rand(1, 1, 16, 17) |
| 39 | >>> out = adap_pad(input) |
| 40 | >>> assert (out.shape[2], out.shape[3]) == (16, 32) |
| 41 | """ |
| 42 | |
| 43 | def __init__(self, kernel_size=1, stride=1, dilation=1, padding="corner"): |
| 44 | super(AdaptivePadding, self).__init__() |
| 45 | |
| 46 | assert padding in ("same", "corner") |
| 47 | |
| 48 | kernel_size = to_2tuple(kernel_size) |
| 49 | stride = to_2tuple(stride) |
| 50 | dilation = to_2tuple(dilation) |
| 51 | |
| 52 | self.padding = padding |
| 53 | self.kernel_size = kernel_size |
| 54 | self.stride = stride |
| 55 | self.dilation = dilation |
| 56 | |
| 57 | def get_pad_shape(self, input_shape): |
| 58 | input_h, input_w = input_shape |
| 59 | kernel_h, kernel_w = self.kernel_size |
| 60 | stride_h, stride_w = self.stride |
| 61 | output_h = math.ceil(input_h / stride_h) |
| 62 | output_w = math.ceil(input_w / stride_w) |
| 63 | pad_h = max((output_h - 1) * stride_h + (kernel_h - 1) * self.dilation[0] + 1 - input_h, 0) |
| 64 | pad_w = max((output_w - 1) * stride_w + (kernel_w - 1) * self.dilation[1] + 1 - input_w, 0) |
| 65 | return pad_h, pad_w |
| 66 | |
| 67 | def forward(self, x): |
| 68 | pad_h, pad_w = self.get_pad_shape(x.size()[-2:]) |
| 69 | if pad_h > 0 or pad_w > 0: |