Path: blob/master/src/utils/style_ops/upfirdn2d.py
809 views
# Copyright (c) 2021, NVIDIA CORPORATION & AFFILIATES. All rights reserved.1#2# NVIDIA CORPORATION and its licensors retain all intellectual property3# and proprietary rights in and to this software, related documentation4# and any modifications thereto. Any use, reproduction, disclosure or5# distribution of this software and related documentation without an express6# license agreement from NVIDIA CORPORATION is strictly prohibited.78"""Custom PyTorch ops for efficient resampling of 2D images."""910import os11import numpy as np12import torch1314from .. import custom_ops15from .. import style_misc as misc16from . import conv2d_gradfix1718#----------------------------------------------------------------------------1920_plugin = None2122def _init():23global _plugin24if _plugin is None:25_plugin = custom_ops.get_plugin(26module_name='upfirdn2d_plugin',27sources=['upfirdn2d.cpp', 'upfirdn2d.cu'],28headers=['upfirdn2d.h'],29source_dir=os.path.dirname(__file__),30extra_cuda_cflags=['--use_fast_math'],31)32return True3334def _parse_scaling(scaling):35if isinstance(scaling, int):36scaling = [scaling, scaling]37assert isinstance(scaling, (list, tuple))38assert all(isinstance(x, int) for x in scaling)39sx, sy = scaling40assert sx >= 1 and sy >= 141return sx, sy4243def _parse_padding(padding):44if isinstance(padding, int):45padding = [padding, padding]46assert isinstance(padding, (list, tuple))47assert all(isinstance(x, int) for x in padding)48if len(padding) == 2:49padx, pady = padding50padding = [padx, padx, pady, pady]51padx0, padx1, pady0, pady1 = padding52return padx0, padx1, pady0, pady15354def _get_filter_size(f):55if f is None:56return 1, 157assert isinstance(f, torch.Tensor) and f.ndim in [1, 2]58fw = f.shape[-1]59fh = f.shape[0]60with misc.suppress_tracer_warnings():61fw = int(fw)62fh = int(fh)63misc.assert_shape(f, [fh, fw][:f.ndim])64assert fw >= 1 and fh >= 165return fw, fh6667#----------------------------------------------------------------------------6869def setup_filter(f, device=torch.device('cpu'), normalize=True, flip_filter=False, gain=1, separable=None):70r"""Convenience function to setup 2D FIR filter for `upfirdn2d()`.7172Args:73f: Torch tensor, numpy array, or python list of the shape74`[filter_height, filter_width]` (non-separable),75`[filter_taps]` (separable),76`[]` (impulse), or77`None` (identity).78device: Result device (default: cpu).79normalize: Normalize the filter so that it retains the magnitude80for constant input signal (DC)? (default: True).81flip_filter: Flip the filter? (default: False).82gain: Overall scaling factor for signal magnitude (default: 1).83separable: Return a separable filter? (default: select automatically).8485Returns:86Float32 tensor of the shape87`[filter_height, filter_width]` (non-separable) or88`[filter_taps]` (separable).89"""90# Validate.91if f is None:92f = 193f = torch.as_tensor(f, dtype=torch.float32)94assert f.ndim in [0, 1, 2]95assert f.numel() > 096if f.ndim == 0:97f = f[np.newaxis]9899# Separable?100if separable is None:101separable = (f.ndim == 1 and f.numel() >= 8)102if f.ndim == 1 and not separable:103f = f.ger(f)104assert f.ndim == (1 if separable else 2)105106# Apply normalize, flip, gain, and device.107if normalize:108f /= f.sum()109if flip_filter:110f = f.flip(list(range(f.ndim)))111f = f * (gain ** (f.ndim / 2))112f = f.to(device=device)113return f114115#----------------------------------------------------------------------------116117def upfirdn2d(x, f, up=1, down=1, padding=0, flip_filter=False, gain=1, impl='cuda'):118r"""Pad, upsample, filter, and downsample a batch of 2D images.119120Performs the following sequence of operations for each channel:1211221. Upsample the image by inserting N-1 zeros after each pixel (`up`).1231242. Pad the image with the specified number of zeros on each side (`padding`).125Negative padding corresponds to cropping the image.1261273. Convolve the image with the specified 2D FIR filter (`f`), shrinking it128so that the footprint of all output pixels lies within the input image.1291304. Downsample the image by keeping every Nth pixel (`down`).131132This sequence of operations bears close resemblance to scipy.signal.upfirdn().133The fused op is considerably more efficient than performing the same calculation134using standard PyTorch ops. It supports gradients of arbitrary order.135136Args:137x: Float32/float64/float16 input tensor of the shape138`[batch_size, num_channels, in_height, in_width]`.139f: Float32 FIR filter of the shape140`[filter_height, filter_width]` (non-separable),141`[filter_taps]` (separable), or142`None` (identity).143up: Integer upsampling factor. Can be a single int or a list/tuple144`[x, y]` (default: 1).145down: Integer downsampling factor. Can be a single int or a list/tuple146`[x, y]` (default: 1).147padding: Padding with respect to the upsampled image. Can be a single number148or a list/tuple `[x, y]` or `[x_before, x_after, y_before, y_after]`149(default: 0).150flip_filter: False = convolution, True = correlation (default: False).151gain: Overall scaling factor for signal magnitude (default: 1).152impl: Implementation to use. Can be `'ref'` or `'cuda'` (default: `'cuda'`).153154Returns:155Tensor of the shape `[batch_size, num_channels, out_height, out_width]`.156"""157assert isinstance(x, torch.Tensor)158assert impl in ['ref', 'cuda']159if impl == 'cuda' and x.device.type == 'cuda' and _init():160return _upfirdn2d_cuda(up=up, down=down, padding=padding, flip_filter=flip_filter, gain=gain).apply(x, f)161return _upfirdn2d_ref(x, f, up=up, down=down, padding=padding, flip_filter=flip_filter, gain=gain)162163#----------------------------------------------------------------------------164165def _upfirdn2d_ref(x, f, up=1, down=1, padding=0, flip_filter=False, gain=1):166"""Slow reference implementation of `upfirdn2d()` using standard PyTorch ops.167"""168# Validate arguments.169assert isinstance(x, torch.Tensor) and x.ndim == 4170if f is None:171f = torch.ones([1, 1], dtype=torch.float32, device=x.device)172assert isinstance(f, torch.Tensor) and f.ndim in [1, 2]173assert f.dtype == torch.float32 and not f.requires_grad174batch_size, num_channels, in_height, in_width = x.shape175upx, upy = _parse_scaling(up)176downx, downy = _parse_scaling(down)177padx0, padx1, pady0, pady1 = _parse_padding(padding)178179# Check that upsampled buffer is not smaller than the filter.180upW = in_width * upx + padx0 + padx1181upH = in_height * upy + pady0 + pady1182assert upW >= f.shape[-1] and upH >= f.shape[0]183184# Upsample by inserting zeros.185x = x.reshape([batch_size, num_channels, in_height, 1, in_width, 1])186x = torch.nn.functional.pad(x, [0, upx - 1, 0, 0, 0, upy - 1])187x = x.reshape([batch_size, num_channels, in_height * upy, in_width * upx])188189# Pad or crop.190x = torch.nn.functional.pad(x, [max(padx0, 0), max(padx1, 0), max(pady0, 0), max(pady1, 0)])191x = x[:, :, max(-pady0, 0) : x.shape[2] - max(-pady1, 0), max(-padx0, 0) : x.shape[3] - max(-padx1, 0)]192193# Setup filter.194f = f * (gain ** (f.ndim / 2))195f = f.to(x.dtype)196if not flip_filter:197f = f.flip(list(range(f.ndim)))198199# Convolve with the filter.200f = f[np.newaxis, np.newaxis].repeat([num_channels, 1] + [1] * f.ndim)201if f.ndim == 4:202x = conv2d_gradfix.conv2d(input=x, weight=f, groups=num_channels)203else:204x = conv2d_gradfix.conv2d(input=x, weight=f.unsqueeze(2), groups=num_channels)205x = conv2d_gradfix.conv2d(input=x, weight=f.unsqueeze(3), groups=num_channels)206207# Downsample by throwing away pixels.208x = x[:, :, ::downy, ::downx]209return x210211#----------------------------------------------------------------------------212213_upfirdn2d_cuda_cache = dict()214215def _upfirdn2d_cuda(up=1, down=1, padding=0, flip_filter=False, gain=1):216"""Fast CUDA implementation of `upfirdn2d()` using custom ops.217"""218# Parse arguments.219upx, upy = _parse_scaling(up)220downx, downy = _parse_scaling(down)221padx0, padx1, pady0, pady1 = _parse_padding(padding)222223# Lookup from cache.224key = (upx, upy, downx, downy, padx0, padx1, pady0, pady1, flip_filter, gain)225if key in _upfirdn2d_cuda_cache:226return _upfirdn2d_cuda_cache[key]227228# Forward op.229class Upfirdn2dCuda(torch.autograd.Function):230@staticmethod231def forward(ctx, x, f): # pylint: disable=arguments-differ232assert isinstance(x, torch.Tensor) and x.ndim == 4233if f is None:234f = torch.ones([1, 1], dtype=torch.float32, device=x.device)235if f.ndim == 1 and f.shape[0] == 1:236f = f.square().unsqueeze(0) # Convert separable-1 into full-1x1.237assert isinstance(f, torch.Tensor) and f.ndim in [1, 2]238y = x239if f.ndim == 2:240y = _plugin.upfirdn2d(y, f, upx, upy, downx, downy, padx0, padx1, pady0, pady1, flip_filter, gain)241else:242y = _plugin.upfirdn2d(y, f.unsqueeze(0), upx, 1, downx, 1, padx0, padx1, 0, 0, flip_filter, 1.0)243y = _plugin.upfirdn2d(y, f.unsqueeze(1), 1, upy, 1, downy, 0, 0, pady0, pady1, flip_filter, gain)244ctx.save_for_backward(f)245ctx.x_shape = x.shape246return y247248@staticmethod249def backward(ctx, dy): # pylint: disable=arguments-differ250f, = ctx.saved_tensors251_, _, ih, iw = ctx.x_shape252_, _, oh, ow = dy.shape253fw, fh = _get_filter_size(f)254p = [255fw - padx0 - 1,256iw * upx - ow * downx + padx0 - upx + 1,257fh - pady0 - 1,258ih * upy - oh * downy + pady0 - upy + 1,259]260dx = None261df = None262263if ctx.needs_input_grad[0]:264dx = _upfirdn2d_cuda(up=down, down=up, padding=p, flip_filter=(not flip_filter), gain=gain).apply(dy, f)265266assert not ctx.needs_input_grad[1]267return dx, df268269# Add to cache.270_upfirdn2d_cuda_cache[key] = Upfirdn2dCuda271return Upfirdn2dCuda272273#----------------------------------------------------------------------------274275def filter2d(x, f, padding=0, flip_filter=False, gain=1, impl='cuda'):276r"""Filter a batch of 2D images using the given 2D FIR filter.277278By default, the result is padded so that its shape matches the input.279User-specified padding is applied on top of that, with negative values280indicating cropping. Pixels outside the image are assumed to be zero.281282Args:283x: Float32/float64/float16 input tensor of the shape284`[batch_size, num_channels, in_height, in_width]`.285f: Float32 FIR filter of the shape286`[filter_height, filter_width]` (non-separable),287`[filter_taps]` (separable), or288`None` (identity).289padding: Padding with respect to the output. Can be a single number or a290list/tuple `[x, y]` or `[x_before, x_after, y_before, y_after]`291(default: 0).292flip_filter: False = convolution, True = correlation (default: False).293gain: Overall scaling factor for signal magnitude (default: 1).294impl: Implementation to use. Can be `'ref'` or `'cuda'` (default: `'cuda'`).295296Returns:297Tensor of the shape `[batch_size, num_channels, out_height, out_width]`.298"""299padx0, padx1, pady0, pady1 = _parse_padding(padding)300fw, fh = _get_filter_size(f)301p = [302padx0 + fw // 2,303padx1 + (fw - 1) // 2,304pady0 + fh // 2,305pady1 + (fh - 1) // 2,306]307return upfirdn2d(x, f, padding=p, flip_filter=flip_filter, gain=gain, impl=impl)308309#----------------------------------------------------------------------------310311def upsample2d(x, f, up=2, padding=0, flip_filter=False, gain=1, impl='cuda'):312r"""Upsample a batch of 2D images using the given 2D FIR filter.313314By default, the result is padded so that its shape is a multiple of the input.315User-specified padding is applied on top of that, with negative values316indicating cropping. Pixels outside the image are assumed to be zero.317318Args:319x: Float32/float64/float16 input tensor of the shape320`[batch_size, num_channels, in_height, in_width]`.321f: Float32 FIR filter of the shape322`[filter_height, filter_width]` (non-separable),323`[filter_taps]` (separable), or324`None` (identity).325up: Integer upsampling factor. Can be a single int or a list/tuple326`[x, y]` (default: 1).327padding: Padding with respect to the output. Can be a single number or a328list/tuple `[x, y]` or `[x_before, x_after, y_before, y_after]`329(default: 0).330flip_filter: False = convolution, True = correlation (default: False).331gain: Overall scaling factor for signal magnitude (default: 1).332impl: Implementation to use. Can be `'ref'` or `'cuda'` (default: `'cuda'`).333334Returns:335Tensor of the shape `[batch_size, num_channels, out_height, out_width]`.336"""337upx, upy = _parse_scaling(up)338padx0, padx1, pady0, pady1 = _parse_padding(padding)339fw, fh = _get_filter_size(f)340p = [341padx0 + (fw + upx - 1) // 2,342padx1 + (fw - upx) // 2,343pady0 + (fh + upy - 1) // 2,344pady1 + (fh - upy) // 2,345]346return upfirdn2d(x, f, up=up, padding=p, flip_filter=flip_filter, gain=gain*upx*upy, impl=impl)347348#----------------------------------------------------------------------------349350def downsample2d(x, f, down=2, padding=0, flip_filter=False, gain=1, impl='cuda'):351r"""Downsample a batch of 2D images using the given 2D FIR filter.352353By default, the result is padded so that its shape is a fraction of the input.354User-specified padding is applied on top of that, with negative values355indicating cropping. Pixels outside the image are assumed to be zero.356357Args:358x: Float32/float64/float16 input tensor of the shape359`[batch_size, num_channels, in_height, in_width]`.360f: Float32 FIR filter of the shape361`[filter_height, filter_width]` (non-separable),362`[filter_taps]` (separable), or363`None` (identity).364down: Integer downsampling factor. Can be a single int or a list/tuple365`[x, y]` (default: 1).366padding: Padding with respect to the input. Can be a single number or a367list/tuple `[x, y]` or `[x_before, x_after, y_before, y_after]`368(default: 0).369flip_filter: False = convolution, True = correlation (default: False).370gain: Overall scaling factor for signal magnitude (default: 1).371impl: Implementation to use. Can be `'ref'` or `'cuda'` (default: `'cuda'`).372373Returns:374Tensor of the shape `[batch_size, num_channels, out_height, out_width]`.375"""376downx, downy = _parse_scaling(down)377padx0, padx1, pady0, pady1 = _parse_padding(padding)378fw, fh = _get_filter_size(f)379p = [380padx0 + (fw - downx + 1) // 2,381padx1 + (fw - downx) // 2,382pady0 + (fh - downy + 1) // 2,383pady1 + (fh - downy) // 2,384]385return upfirdn2d(x, f, down=down, padding=p, flip_filter=flip_filter, gain=gain, impl=impl)386387#----------------------------------------------------------------------------388389390