Skip to content

Instantly share code, notes, and snippets.

@A03ki
Last active March 25, 2024 05:03
Show Gist options
  • Select an option

  • Save A03ki/2305398458cb8e2155e8e81333f0a965 to your computer and use it in GitHub Desktop.

Select an option

Save A03ki/2305398458cb8e2155e8e81333f0a965 to your computer and use it in GitHub Desktop.
Implementation of ICNR with PyTorch

ICNR

ICNR is an initialization method for sub-pixel convolution.

References

Papar

Github or Gist

Requirements

Python 3.6 or later
PyTorch 1.1.0 or later

Usage

For example, input Tensor with the sizes (64, 8, 32, 32) would be output as (64, 8, 64, 64) if you set upscale_factor to 2.

import torch
import torch.nn as nn

from icnr import ICNR


upscale_factor = 2
input = torch.randn(64, 3, 32, 32)
conv = nn.Conv2d(3, 3 * (upscale_factor ** 2), 3, 1, 1, bias=0)
pixelshuffle = nn.PixelShuffle(upscale_factor)
weight = ICNR(conv.weight, initializer=nn.init.kaiming_normal_,
              upscale_factor=upscale_factor)
conv.weight.data.copy_(weight)   # initialize conv.weight
output = conv(input)  # (64, 12, 32, 32)
output = pixelshuffle(output)  # (64, 3, 64, 64)

Visualization

See visualization.ipynb

import torch
def ICNR(tensor, initializer, upscale_factor=2, *args, **kwargs):
"tensor: the 2-dimensional Tensor or more"
upscale_factor_squared = upscale_factor * upscale_factor
assert tensor.shape[0] % upscale_factor_squared == 0, \
("The size of the first dimension: "
f"tensor.shape[0] = {tensor.shape[0]}"
" is not divisible by square of upscale_factor: "
f"upscale_factor = {upscale_factor}")
sub_kernel = torch.empty(tensor.shape[0] // upscale_factor_squared,
*tensor.shape[1:])
sub_kernel = initializer(sub_kernel, *args, **kwargs)
return sub_kernel.repeat_interleave(upscale_factor_squared, dim=0)
Display the source blob
Display the rendered blob
Raw
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment