New switched_conv

This commit is contained in:
James Betker 2021-01-23 13:46:30 -07:00
parent 557cdec116
commit 1b8a26db93
2 changed files with 211 additions and 61 deletions

View File

@ -6,10 +6,14 @@ import torch
import torch.nn as nn import torch.nn as nn
import torch.nn.functional as F import torch.nn.functional as F
import torchvision import torchvision
from torchvision.models.resnet import Bottleneck
from models.arch_util import make_layer, default_init_weights, ConvGnSilu, ConvGnLelu from models.arch_util import make_layer, default_init_weights, ConvGnSilu, ConvGnLelu
from models.pixel_level_contrastive_learning.resnet_unet_2 import UResNet50_2
from models.pixel_level_contrastive_learning.resnet_unet_3 import UResNet50_3
from trainer.networks import register_model from trainer.networks import register_model
from utils.util import checkpoint, sequential_checkpoint, opt_get from utils.util import checkpoint, sequential_checkpoint, opt_get
from models.switched_conv import SwitchedConv
class ResidualDenseBlock(nn.Module): class ResidualDenseBlock(nn.Module):
@ -303,82 +307,91 @@ class RRDBNet(nn.Module):
torchvision.utils.save_image(bm.bypass_map.cpu().float(), os.path.join(path, "%i_bypass_%i.png" % (step, i+1))) torchvision.utils.save_image(bm.bypass_map.cpu().float(), os.path.join(path, "%i_bypass_%i.png" % (step, i+1)))
class RRDBNetSwitchedConv(nn.Module):
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, def __init__(self,
in_channels, in_channels,
out_channels,
mid_channels=64, mid_channels=64,
num_blocks=23, num_blocks=23,
growth_channels=32, growth_channels=32,
blocks_per_checkpoint=1 body_block=RRDB,
blocks_per_checkpoint=1,
scale=4,
initial_stride=1,
use_ref=False, # When set, a reference image is expected as input and synthesized if not found. Useful for video SR.
resnet_encoder_dict=None
): ):
super(RRDBDiscriminator, self).__init__() super().__init__()
self.num_blocks = num_blocks self.num_blocks = num_blocks
self.blocks_per_checkpoint = blocks_per_checkpoint self.blocks_per_checkpoint = blocks_per_checkpoint
self.scale = scale
self.in_channels = in_channels self.in_channels = in_channels
self.conv_first = ConvGnLelu(in_channels, mid_channels, 3, stride=4, activation=False, norm=False, bias=True) 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
first_conv_padding = 1 if first_conv_stride == 1 else 3
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
self.body = make_layer( self.body = make_layer(
DiscRRDB, body_block,
num_blocks, num_blocks,
mid_channels=mid_channels, mid_channels=mid_channels,
growth_channels=growth_channels) growth_channels=growth_channels,
self.tail = nn.Sequential( reduce_to=reduce_to)
ConvGnLelu(mid_channels, mid_channels // 2, kernel_size=1, activation=True, norm=False, bias=True), self.conv_body = SwitchedConv(self.reduce_ch, self.reduce_ch, 3, 8, 1, 1, include_coupler=True, coupler_dim_in=64)
ConvGnLelu(mid_channels // 2, mid_channels // 4, kernel_size=1, activation=True, norm=False, bias=True), # upsample
ConvGnLelu(mid_channels // 4, 1, kernel_size=1, activation=False, norm=False, bias=True) self.conv_up1 = SwitchedConv(self.reduce_ch, self.reduce_ch, 3, 8, 1, 1, include_coupler=True, coupler_dim_in=64)
) self.conv_up2 = SwitchedConv(self.reduce_ch, self.reduce_ch, 3, 8, 1, 1, include_coupler=True, coupler_dim_in=64)
self.pred_ = None if scale >= 8:
self.conv_up3 = SwitchedConv(self.reduce_ch, self.reduce_ch, 3, 8, 1, 1, include_coupler=True, coupler_dim_in=64)
else:
self.conv_up3 = None
self.conv_hr = SwitchedConv(self.reduce_ch, self.reduce_ch, 3, 8, 1, 1, include_coupler=True, coupler_dim_in=64)
self.conv_last = SwitchedConv(self.reduce_ch, out_channels, 3, 8, 1, 1, include_coupler=True, coupler_dim_in=64)
self.lrelu = nn.LeakyReLU(negative_slope=0.2, inplace=True)
def forward(self, x): self.resnet_encoder = UResNet50_3(Bottleneck, [3, 4, 6, 3], out_dim=64)
feat = self.conv_first(x) if resnet_encoder_dict:
self.resnet_encoder.load_state_dict(torch.load(resnet_encoder_dict))
for m in [
self.conv_first, self.conv_body, self.conv_up1,
self.conv_up2, self.conv_up3, self.conv_hr, self.conv_last
]:
if m is not None:
default_init_weights(m, 0.1)
def forward(self, x, ref=None):
switch_enc = checkpoint(self.resnet_encoder, F.interpolate(x, scale_factor=2, mode="bilinear"))
x_lg = x
feat = self.conv_first(x_lg)
feat = sequential_checkpoint(self.body, self.num_blocks // self.blocks_per_checkpoint, feat) feat = sequential_checkpoint(self.body, self.num_blocks // self.blocks_per_checkpoint, feat)
pred = checkpoint(self.tail, feat) feat = feat[:, :self.reduce_ch]
self.pred_ = pred.detach().clone() body_feat = checkpoint(self.conv_body, feat, switch_enc)
return pred feat = feat + body_feat
# upsample
out = self.lrelu(
checkpoint(self.conv_up1, F.interpolate(feat, scale_factor=2, mode='nearest'), switch_enc))
if self.scale >= 4:
out = self.lrelu(
checkpoint(self.conv_up2, F.interpolate(out, scale_factor=2, mode='nearest'), switch_enc))
if self.scale >= 8:
out = self.lrelu(
self.conv_up3(F.interpolate(out, scale_factor=2, mode='nearest'), switch_enc))
else:
out = self.lrelu(checkpoint(self.conv_up2, out, switch_enc))
out = checkpoint(self.conv_hr, out, switch_enc)
out = checkpoint(self.conv_last, self.lrelu(out), switch_enc)
return out
def visual_dbg(self, step, path): def visual_dbg(self, step, path):
if self.pred_ is not None: for i, bm in enumerate(self.body):
self.pred_ = F.sigmoid(self.pred_) if hasattr(bm, 'bypass_map'):
torchvision.utils.save_image(self.pred_.cpu().float(), os.path.join(path, "%i_predictions.png" % (step,))) torchvision.utils.save_image(bm.bypass_map.cpu().float(), os.path.join(path, "%i_bypass_%i.png" % (step, i+1)))
@register_model @register_model
@ -404,4 +417,16 @@ def register_RRDBNet(opt_net, opt):
return RRDBNet(in_channels=opt_net['in_nc'], out_channels=opt_net['out_nc'], return RRDBNet(in_channels=opt_net['in_nc'], out_channels=opt_net['out_nc'],
mid_channels=opt_net['nf'], num_blocks=opt_net['nb'], additive_mode=additive_mode, mid_channels=opt_net['nf'], num_blocks=opt_net['nb'], additive_mode=additive_mode,
output_mode=output_mode, body_block=RRDB, scale=opt_net['scale'], growth_channels=gc, output_mode=output_mode, body_block=RRDB, scale=opt_net['scale'], growth_channels=gc,
initial_stride=initial_stride) initial_stride=initial_stride)
@register_model
def register_rrdb_switched_conv(opt_net, opt):
gc = opt_net['gc'] if 'gc' in opt_net.keys() else 32
initial_stride = opt_net['initial_stride'] if 'initial_stride' in opt_net.keys() else 1
bypass_noise = opt_get(opt_net, ['bypass_noise'], False)
block = functools.partial(RRDBWithBypass, randomly_add_noise_to_bypass=bypass_noise)
return RRDBNetSwitchedConv(in_channels=opt_net['in_nc'], out_channels=opt_net['out_nc'],
mid_channels=opt_net['nf'], num_blocks=opt_net['nb'],
body_block=block, scale=opt_net['scale'], growth_channels=gc,
initial_stride=initial_stride, resnet_encoder_dict=opt_net['switch_encoder'])

View File

@ -0,0 +1,125 @@
import functools
import math
from collections import OrderedDict
import torch
import torch.nn as nn
from torch.nn import init, Conv2d
import torch.nn.functional as F
class SwitchedConv(nn.Module):
def __init__(self,
in_channels: int,
out_channels: int,
kernel_size: int,
switch_breadth: int,
stride: int = 1,
padding: int = 0,
dilation: int = 1,
groups: int = 1,
bias: bool = True,
padding_mode: str = 'zeros',
include_coupler: bool = False, # A 'coupler' is a latent converter which can make any bxcxhxw tensor a compatible switchedconv selector by performing a linear 1x1 conv, softmax and interpolate.
coupler_dim_in: int = 0):
super().__init__()
self.in_channels = in_channels
self.out_channels = out_channels
self.kernel_size = kernel_size
self.stride = stride
self.padding = padding
self.dilation = dilation
self.padding_mode = padding_mode
self.groups = groups
if include_coupler:
self.coupler = Conv2d(coupler_dim_in, switch_breadth, kernel_size=1)
else:
self.coupler = None
self.weights = nn.ParameterList([nn.Parameter(torch.Tensor(out_channels, in_channels // groups, kernel_size, kernel_size)) for _ in range(switch_breadth)])
if bias:
self.bias = nn.Parameter(torch.Tensor(out_channels))
else:
self.register_parameter('bias', None)
self.reset_parameters()
def reset_parameters(self) -> None:
for w in self.weights:
init.kaiming_uniform_(w, a=math.sqrt(5))
if self.bias is not None:
fan_in, _ = init._calculate_fan_in_and_fan_out(self.weights[0])
bound = 1 / math.sqrt(fan_in)
init.uniform_(self.bias, -bound, bound)
def forward(self, inp, selector):
if self.coupler:
selector = F.softmax(self.coupler(selector), dim=1)
out_shape = [s // self.stride for s in inp.shape[2:]]
if selector.shape[2] != out_shape[0] or selector.shape[3] != out_shape[1]:
selector = F.interpolate(selector, size=out_shape, mode="nearest")
conv_results = []
for i, w in enumerate(self.weights):
conv_results.append(F.conv2d(inp, w, self.bias, self.stride, self.padding, self.dilation, self.groups) * selector[:, i].unsqueeze(1))
return torch.stack(conv_results, dim=-1).sum(dim=-1)
# Given a state_dict and the module that that sd belongs to, strips out all Conv2d.weight parameters and replaces them
# with the equivalent SwitchedConv.weight parameters. Does not create coupler params.
def convert_conv_net_state_dict_to_switched_conv(module, switch_breadth, ignore_list=[]):
state_dict = module.state_dict()
for name, m in module.named_modules():
ignored = False
for smod in ignore_list:
if smod in name:
ignored = True
continue
if ignored:
continue
if isinstance(m, nn.Conv2d):
if name == '':
basename = 'weight'
modname = 'weights'
else:
basename = f'{name}.weight'
modname = f'{name}.weights'
cnv_weights = state_dict[basename]
del state_dict[basename]
for j in range(switch_breadth):
state_dict[f'{modname}.{j}'] = cnv_weights.clone()
return state_dict
def test_net():
base_conv = Conv2d(32, 64, 3, stride=2, padding=1, bias=True).to('cuda')
mod_conv = SwitchedConv(32, 64, 3, switch_breadth=8, stride=2, padding=1, bias=True, include_coupler=True, coupler_dim_in=128).to('cuda')
mod_sd = convert_conv_net_state_dict_to_switched_conv(base_conv, 8)
mod_conv.load_state_dict(mod_sd, strict=False)
inp = torch.randn((8,32,128,128), device='cuda')
sel = torch.randn((8,128,32,32), device='cuda')
out1 = base_conv(inp)
out2 = mod_conv(inp, sel)
assert(torch.max(torch.abs(out1-out2)) < 1e-6)
def perform_conversion():
sd = torch.load("../experiments/rrdb_imgset_226500_generator.pth")
load_net_clean = OrderedDict() # remove unnecessary 'module.'
for k, v in sd.items():
if k.startswith('module.'):
load_net_clean[k.replace('module.', '')] = v
else:
load_net_clean[k] = v
sd = load_net_clean
import models.RRDBNet_arch as rrdb
block = functools.partial(rrdb.RRDBWithBypass)
mod = rrdb.RRDBNet(in_channels=3, out_channels=3,
mid_channels=64, num_blocks=23, body_block=block, scale=2, initial_stride=2)
mod.load_state_dict(sd)
converted = convert_conv_net_state_dict_to_switched_conv(mod, 8, ['body.','conv_first','resnet_encoder'])
torch.save(converted, "../experiments/rrdb_imgset_226500_generator_converted.pth")
if __name__ == '__main__':
perform_conversion()