DL-Art-School/codes/models/archs/RRDBNet_arch.py

366 lines
14 KiB
Python
Raw Normal View History

2020-10-29 15:39:45 +00:00
import os
2019-08-23 13:42:47 +00:00
import torch
import torch.nn as nn
import torch.nn.functional as F
2020-10-29 15:39:45 +00:00
import torchvision
2019-08-23 13:42:47 +00:00
from models.archs.arch_util import make_layer, default_init_weights, ConvGnSilu, ConvGnLelu
2020-11-29 19:21:31 +00:00
from utils.util import checkpoint, sequential_checkpoint
2019-08-23 13:42:47 +00:00
2020-10-27 16:25:31 +00:00
class ResidualDenseBlock(nn.Module):
"""Residual Dense Block.
Used in RRDB block in ESRGAN.
Args:
mid_channels (int): Channel number of intermediate features.
growth_channels (int): Channels for each growth.
"""
2020-11-27 03:30:55 +00:00
def __init__(self, mid_channels=64, growth_channels=32, init_weight=.1):
2020-10-27 16:25:31 +00:00
super(ResidualDenseBlock, self).__init__()
for i in range(5):
out_channels = mid_channels if i == 4 else growth_channels
self.add_module(
f'conv{i+1}',
nn.Conv2d(mid_channels + i * growth_channels, out_channels, 3,
1, 1))
2019-08-23 13:42:47 +00:00
self.lrelu = nn.LeakyReLU(negative_slope=0.2, inplace=True)
2020-10-27 16:25:31 +00:00
for i in range(5):
2020-11-27 03:30:55 +00:00
default_init_weights(getattr(self, f'conv{i+1}'), init_weight)
2019-08-23 13:42:47 +00:00
def forward(self, x):
2020-10-27 16:25:31 +00:00
"""Forward function.
Args:
x (Tensor): Input tensor with shape (n, c, h, w).
Returns:
Tensor: Forward results.
"""
2019-08-23 13:42:47 +00:00
x1 = self.lrelu(self.conv1(x))
x2 = self.lrelu(self.conv2(torch.cat((x, x1), 1)))
x3 = self.lrelu(self.conv3(torch.cat((x, x1, x2), 1)))
x4 = self.lrelu(self.conv4(torch.cat((x, x1, x2, x3), 1)))
x5 = self.conv5(torch.cat((x, x1, x2, x3, x4), 1))
2020-10-27 16:25:31 +00:00
# Emperically, we use 0.2 to scale the residual for better performance
2019-08-23 13:42:47 +00:00
return x5 * 0.2 + x
2020-06-06 03:02:08 +00:00
2019-08-23 13:42:47 +00:00
class RRDB(nn.Module):
2020-10-27 16:25:31 +00:00
"""Residual in Residual Dense Block.
2019-08-23 13:42:47 +00:00
2020-10-27 16:25:31 +00:00
Used in RRDB-Net in ESRGAN.
2020-10-27 16:25:31 +00:00
Args:
mid_channels (int): Channel number of intermediate features.
growth_channels (int): Channels for each growth.
"""
def __init__(self, mid_channels, growth_channels=32, reduce_to=None):
2020-10-27 16:25:31 +00:00
super(RRDB, self).__init__()
self.rdb1 = ResidualDenseBlock(mid_channels, growth_channels)
self.rdb2 = ResidualDenseBlock(mid_channels, growth_channels)
self.rdb3 = ResidualDenseBlock(mid_channels, growth_channels)
if reduce_to is not None:
self.reducer = ConvGnLelu(mid_channels, reduce_to, kernel_size=3, activation=False, norm=False, bias=True)
self.recover_ch = mid_channels - reduce_to
else:
self.reducer = None
2020-06-06 03:02:08 +00:00
2020-11-28 21:35:46 +00:00
def forward(self, x, return_residual=False):
2020-10-27 16:25:31 +00:00
"""Forward function.
Args:
x (Tensor): Input tensor with shape (n, c, h, w).
Returns:
Tensor: Forward results.
"""
out = self.rdb1(x)
out = self.rdb2(out)
out = self.rdb3(out)
if self.reducer is not None:
out = self.reducer(out)
b, f, h, w = out.shape
out = torch.cat([out, torch.zeros((b, self.recover_ch, h, w), device=out.device)], dim=1)
2020-11-28 21:35:46 +00:00
if return_residual:
return 0.2 * out
else:
# Empirically, we use 0.2 to scale the residual for better performance
return out * 0.2 + x
2020-06-09 19:28:55 +00:00
2020-10-29 15:39:45 +00:00
class RRDBWithBypass(nn.Module):
"""Residual in Residual Dense Block.
Used in RRDB-Net in ESRGAN.
Args:
mid_channels (int): Channel number of intermediate features.
growth_channels (int): Channels for each growth.
"""
def __init__(self, mid_channels, growth_channels=32, reduce_to=None):
2020-10-29 15:39:45 +00:00
super(RRDBWithBypass, self).__init__()
self.rdb1 = ResidualDenseBlock(mid_channels, growth_channels)
self.rdb2 = ResidualDenseBlock(mid_channels, growth_channels)
self.rdb3 = ResidualDenseBlock(mid_channels, growth_channels)
if reduce_to is not None:
self.reducer = ConvGnLelu(mid_channels, reduce_to, kernel_size=3, activation=False, norm=False, bias=True)
self.recover_ch = mid_channels - reduce_to
bypass_channels = mid_channels + reduce_to
else:
self.reducer = None
bypass_channels = mid_channels * 2
self.bypass = nn.Sequential(ConvGnSilu(bypass_channels, mid_channels, kernel_size=3, bias=True, activation=True, norm=True),
2020-10-29 15:39:45 +00:00
ConvGnSilu(mid_channels, mid_channels//2, kernel_size=3, bias=False, activation=True, norm=False),
ConvGnSilu(mid_channels//2, 1, kernel_size=3, bias=False, activation=False, norm=False),
nn.Sigmoid())
def forward(self, x):
"""Forward function.
Args:
x (Tensor): Input tensor with shape (n, c, h, w).
Returns:
Tensor: Forward results.
"""
out = self.rdb1(x)
out = self.rdb2(out)
out = self.rdb3(out)
if self.reducer is not None:
out = self.reducer(out)
b, f, h, w = out.shape
out = torch.cat([out, torch.zeros((b, self.recover_ch, h, w), device=out.device)], dim=1)
2020-10-29 15:39:45 +00:00
bypass = self.bypass(torch.cat([x, out], dim=1))
self.bypass_map = bypass.detach().clone()
2020-11-11 18:25:49 +00:00
# Empirically, we use 0.2 to scale the residual for better performance
2020-10-29 15:39:45 +00:00
return out * 0.2 * bypass + x
2020-10-27 16:25:31 +00:00
class RRDBNet(nn.Module):
"""Networks consisting of Residual in Residual Dense Block, which is used
in ESRGAN.
ESRGAN: Enhanced Super-Resolution Generative Adversarial Networks.
Currently, it supports x4 upsampling scale factor.
Args:
in_channels (int): Channel number of inputs.
out_channels (int): Channel number of outputs.
mid_channels (int): Channel number of intermediate features.
Default: 64
num_blocks (int): Block number in the trunk network. Defaults: 23
growth_channels (int): Channels for each growth. Default: 32.
"""
def __init__(self,
in_channels,
out_channels,
mid_channels=64,
num_blocks=23,
2020-10-29 15:39:45 +00:00
growth_channels=32,
body_block=RRDB,
blocks_per_checkpoint=1,
2020-11-17 03:45:09 +00:00
scale=4,
additive_mode="not", # Options: "not", "additive", "additive_enforced"
headless=False,
feature_channels=64, # Only applicable when headless=True. How many channels are used at the trunk level.
output_mode="hq_only", # Options: "hq_only", "hq+features", "features_only"
2020-11-28 21:35:46 +00:00
initial_stride=1,
use_ref=False, # When set, a reference image is expected as input and synthesized if not found. Useful for video SR.
2020-11-17 03:45:09 +00:00
):
2020-06-09 19:28:55 +00:00
super(RRDBNet, self).__init__()
assert output_mode in ['hq_only', 'hq+features', 'features_only']
assert additive_mode in ['not', 'additive', 'additive_enforced']
2020-10-29 15:39:45 +00:00
self.num_blocks = num_blocks
self.blocks_per_checkpoint = blocks_per_checkpoint
2020-10-29 15:48:10 +00:00
self.scale = scale
self.in_channels = in_channels
self.output_mode = output_mode
self.use_ref = use_ref
first_conv_stride = initial_stride if not self.use_ref else scale
first_conv_ksize = 3 if first_conv_stride == 1 else 7
2020-10-30 06:19:58 +00:00
first_conv_padding = 1 if first_conv_stride == 1 else 3
if headless:
self.conv_first = None
self.reduce_ch = feature_channels
reduce_to = feature_channels
self.conv_ref_first = ConvGnLelu(3, feature_channels, 7, stride=2, norm=False, activation=False, bias=True)
else:
self.conv_first = nn.Conv2d(in_channels, mid_channels, first_conv_ksize, first_conv_stride, first_conv_padding)
self.reduce_ch = mid_channels
reduce_to = None
2020-10-27 16:25:31 +00:00
self.body = make_layer(
2020-10-29 15:39:45 +00:00
body_block,
2020-10-27 16:25:31 +00:00
num_blocks,
mid_channels=mid_channels,
growth_channels=growth_channels,
reduce_to=reduce_to)
self.conv_body = nn.Conv2d(self.reduce_ch, self.reduce_ch, 3, 1, 1)
2020-10-27 16:25:31 +00:00
# upsample
self.conv_up1 = nn.Conv2d(self.reduce_ch, self.reduce_ch, 3, 1, 1)
self.conv_up2 = nn.Conv2d(self.reduce_ch, self.reduce_ch, 3, 1, 1)
self.conv_hr = nn.Conv2d(self.reduce_ch, self.reduce_ch, 3, 1, 1)
self.conv_last = nn.Conv2d(self.reduce_ch, out_channels, 3, 1, 1)
2020-06-09 19:28:55 +00:00
2020-11-17 03:45:09 +00:00
self.additive_mode = additive_mode
if additive_mode == "additive_enforced":
self.add_enforced_pool = nn.AvgPool2d(kernel_size=scale, stride=scale)
2020-06-09 19:28:55 +00:00
self.lrelu = nn.LeakyReLU(negative_slope=0.2, inplace=True)
2020-10-27 16:25:31 +00:00
for m in [
self.conv_first, self.conv_body, self.conv_up1,
self.conv_up2, self.conv_hr, self.conv_last
]:
if m is not None:
default_init_weights(m, 0.1)
def forward(self, x, ref=None):
2020-10-27 16:25:31 +00:00
"""Forward function.
Args:
x (Tensor): Input tensor with shape (n, c, h, w).
Returns:
Tensor: Forward results.
"""
if self.conv_first is None:
# Headless mode -> embedding inputs.
if ref is not None:
ref = self.conv_ref_first(ref)
feat = torch.cat([x, ref], dim=1)
else:
feat = x
else:
# "Normal" mode -> image input.
if self.use_ref:
x_lg = F.interpolate(x, scale_factor=self.scale, mode="bicubic")
if ref is None:
ref = torch.zeros_like(x_lg)
x_lg = torch.cat([x_lg, ref], dim=1)
else:
x_lg = x
feat = self.conv_first(x_lg)
2020-11-29 19:21:31 +00:00
feat = sequential_checkpoint(self.body, self.num_blocks // self.blocks_per_checkpoint, feat)
feat = feat[:, :self.reduce_ch]
body_feat = self.conv_body(feat)
2020-10-27 16:25:31 +00:00
feat = feat + body_feat
if self.output_mode == "features_only":
return feat
2020-10-27 16:25:31 +00:00
# upsample
out = self.lrelu(
2020-10-27 16:25:31 +00:00
self.conv_up1(F.interpolate(feat, scale_factor=2, mode='nearest')))
2020-10-29 15:48:10 +00:00
if self.scale == 4:
out = self.lrelu(
self.conv_up2(F.interpolate(out, scale_factor=2, mode='nearest')))
2020-10-29 15:48:10 +00:00
else:
out = self.lrelu(self.conv_up2(out))
out = self.conv_last(self.lrelu(self.conv_hr(out)))
2020-11-17 03:45:09 +00:00
if "additive" in self.additive_mode:
x_interp = F.interpolate(x, scale_factor=self.scale, mode='bilinear')
if self.additive_mode == 'additive':
out = out + x_interp
elif self.additive_mode == 'additive_enforced':
out_pooled = self.add_enforced_pool(out)
out = out - F.interpolate(out_pooled, scale_factor=self.scale, mode='nearest')
out = out + x_interp
if self.output_mode == "hq+features":
return out, feat
2020-10-29 15:39:45 +00:00
return out
def visual_dbg(self, step, path):
for i, bm in enumerate(self.body):
2020-11-12 04:49:06 +00:00
if hasattr(bm, 'bypass_map'):
torchvision.utils.save_image(bm.bypass_map.cpu().float(), os.path.join(path, "%i_bypass_%i.png" % (step, i+1)))
2020-11-27 19:03:08 +00:00
class DiscRDB(nn.Module):
def __init__(self, mid_channels=64, growth_channels=32):
super(DiscRDB, self).__init__()
for i in range(5):
out_channels = mid_channels if i == 4 else growth_channels
actnorm = i != 5
self.add_module(
f'conv{i+1}',
ConvGnLelu(mid_channels + i * growth_channels, out_channels, kernel_size=3, norm=actnorm, activation=actnorm, bias=True)
)
self.lrelu = nn.LeakyReLU(negative_slope=.2)
for i in range(5):
default_init_weights(getattr(self, f'conv{i+1}'), 1)
def forward(self, x):
x1 = self.conv1(x)
x2 = self.conv2(torch.cat((x, x1), 1))
x3 = self.conv3(torch.cat((x, x1, x2), 1))
x4 = self.conv4(torch.cat((x, x1, x2, x3), 1))
x5 = self.conv5(torch.cat((x, x1, x2, x3, x4), 1))
return self.lrelu(x5 + x)
class DiscRRDB(nn.Module):
def __init__(self, mid_channels, growth_channels=32):
super(DiscRRDB, self).__init__()
self.rdb1 = DiscRDB(mid_channels, growth_channels)
self.rdb2 = DiscRDB(mid_channels, growth_channels)
self.rdb3 = DiscRDB(mid_channels, growth_channels)
self.gn = nn.GroupNorm(num_groups=8, num_channels=mid_channels)
def forward(self, x):
out = self.rdb1(x)
out = self.rdb2(out)
out = self.rdb3(out)
return self.gn(out + x)
class RRDBDiscriminator(nn.Module):
def __init__(self,
in_channels,
mid_channels=64,
num_blocks=23,
growth_channels=32,
blocks_per_checkpoint=1
):
super(RRDBDiscriminator, self).__init__()
self.num_blocks = num_blocks
self.blocks_per_checkpoint = blocks_per_checkpoint
self.in_channels = in_channels
self.conv_first = ConvGnLelu(in_channels, mid_channels, 3, stride=4, activation=False, norm=False, bias=True)
self.body = make_layer(
DiscRRDB,
num_blocks,
mid_channels=mid_channels,
growth_channels=growth_channels)
self.tail = nn.Sequential(
ConvGnLelu(mid_channels, mid_channels // 2, kernel_size=1, activation=True, norm=False, bias=True),
ConvGnLelu(mid_channels // 2, mid_channels // 4, kernel_size=1, activation=True, norm=False, bias=True),
ConvGnLelu(mid_channels // 4, 1, kernel_size=1, activation=False, norm=False, bias=True)
)
self.pred_ = None
def forward(self, x):
feat = self.conv_first(x)
2020-11-29 19:21:31 +00:00
feat = sequential_checkpoint(self.body, self.num_blocks // self.blocks_per_checkpoint, feat)
2020-11-27 19:03:08 +00:00
pred = checkpoint(self.tail, feat)
self.pred_ = pred.detach().clone()
return pred
def visual_dbg(self, step, path):
if self.pred_ is not None:
self.pred_ = F.sigmoid(self.pred_)
torchvision.utils.save_image(self.pred_.cpu().float(), os.path.join(path, "%i_predictions.png" % (step,)))