From 4e44bca611089ed065ea9efa8c992f7a0e4606e0 Mon Sep 17 00:00:00 2001 From: James Betker Date: Fri, 11 Sep 2020 22:55:37 -0600 Subject: [PATCH] SPSR4 aka - return of the backbone! I'm tired of massively overparameterized generators with pile-of-shit multiplexers. Let's give this another try.. --- codes/models/archs/SPSR_arch.py | 133 +++++++++++++++++- .../archs/SwitchedResidualGenerator_arch.py | 104 ++++++++++++++ codes/models/archs/spinenet_arch.py | 2 +- codes/models/networks.py | 6 + 4 files changed, 243 insertions(+), 2 deletions(-) diff --git a/codes/models/archs/SPSR_arch.py b/codes/models/archs/SPSR_arch.py index 52ac80cf..808f3f36 100644 --- a/codes/models/archs/SPSR_arch.py +++ b/codes/models/archs/SPSR_arch.py @@ -5,7 +5,7 @@ import torch.nn.functional as F from models.archs import SPSR_util as B from .RRDBNet_arch import RRDB from models.archs.arch_util import ConvGnLelu, UpconvBlock, ConjoinBlock, ConvGnSilu, MultiConvBlock, ReferenceJoinBlock -from models.archs.SwitchedResidualGenerator_arch import ConvBasisMultiplexer, ConfigurableSwitchComputer, ReferencingConvMultiplexer, ReferenceImageBranch, AdaInConvBlock, ProcessingBranchWithStochasticity +from models.archs.SwitchedResidualGenerator_arch import ConvBasisMultiplexer, ConfigurableSwitchComputer, ReferencingConvMultiplexer, ReferenceImageBranch, AdaInConvBlock, ProcessingBranchWithStochasticity, EmbeddingMultiplexer from switched_conv_util import save_attention_to_image_rgb from switched_conv import compute_attention_specificity import functools @@ -409,3 +409,134 @@ class SwitchedSpsrWithRef2(nn.Module): val["switch_%i_specificity" % (i,)] = means[i] val["switch_%i_histogram" % (i,)] = hists[i] return val + + +class Spsr4(nn.Module): + def __init__(self, in_nc, out_nc, nf, xforms=8, upscale=4, init_temperature=10): + super(Spsr4, self).__init__() + n_upscale = int(math.log(upscale, 2)) + + # switch options + transformation_filters = nf + self.transformation_counts = xforms + multiplx_fn = functools.partial(EmbeddingMultiplexer, transformation_filters) + pretransform_fn = functools.partial(ConvGnLelu, transformation_filters, transformation_filters, norm=False, bias=False, weight_init_factor=.1) + transform_fn = functools.partial(MultiConvBlock, transformation_filters, int(transformation_filters * 1.5), + transformation_filters, kernel_size=3, depth=3, + weight_init_factor=.1) + + # Feature branch + self.model_fea_conv = ConvGnLelu(in_nc, nf, kernel_size=3, norm=False, activation=False) + self.noise_ref_join = ReferenceJoinBlock(nf, residual_weight_init_factor=.1) + self.sw1 = ConfigurableSwitchComputer(transformation_filters, multiplx_fn, + pre_transform_block=pretransform_fn, transform_block=transform_fn, + attention_norm=True, + transform_count=self.transformation_counts, init_temp=init_temperature, + add_scalable_noise_to_transforms=False) + self.sw2 = ConfigurableSwitchComputer(transformation_filters, multiplx_fn, + pre_transform_block=pretransform_fn, transform_block=transform_fn, + attention_norm=True, + transform_count=self.transformation_counts, init_temp=init_temperature, + add_scalable_noise_to_transforms=False) + self.feature_lr_conv = ConvGnLelu(nf, nf, kernel_size=3, norm=True, activation=False) + self.feature_lr_conv2 = ConvGnLelu(nf, nf, kernel_size=3, norm=False, activation=False, bias=False) + + # Grad branch. Note - groupnorm on this branch is REALLY bad. Avoid it like the plague. + self.get_g_nopadding = ImageGradientNoPadding() + self.grad_conv = ConvGnLelu(in_nc, nf, kernel_size=3, norm=False, activation=False, bias=False) + self.noise_ref_join_grad = ReferenceJoinBlock(nf, residual_weight_init_factor=.1) + self.grad_ref_join = ReferenceJoinBlock(nf, residual_weight_init_factor=.3, final_norm=False) + self.sw_grad = ConfigurableSwitchComputer(transformation_filters, multiplx_fn, + pre_transform_block=pretransform_fn, transform_block=transform_fn, + attention_norm=True, + transform_count=self.transformation_counts // 2, init_temp=init_temperature, + add_scalable_noise_to_transforms=False) + self.grad_lr_conv = ConvGnLelu(nf, nf, kernel_size=3, norm=False, activation=True, bias=True) + self.grad_lr_conv2 = ConvGnLelu(nf, nf, kernel_size=3, norm=False, activation=True, bias=True) + self.upsample_grad = nn.Sequential(*[UpconvBlock(nf, nf, block=ConvGnLelu, norm=False, activation=True, bias=False) for _ in range(n_upscale)]) + self.grad_branch_output_conv = ConvGnLelu(nf, out_nc, kernel_size=1, norm=False, activation=False, bias=True) + + # Join branch (grad+fea) + self.noise_ref_join_conjoin = ReferenceJoinBlock(nf, residual_weight_init_factor=.1) + self.conjoin_ref_join = ReferenceJoinBlock(nf, residual_weight_init_factor=.3) + self.conjoin_sw = ConfigurableSwitchComputer(transformation_filters, multiplx_fn, + pre_transform_block=pretransform_fn, transform_block=transform_fn, + attention_norm=True, + transform_count=self.transformation_counts, init_temp=init_temperature, + add_scalable_noise_to_transforms=False) + self.final_lr_conv = ConvGnLelu(nf, nf, kernel_size=3, norm=False, activation=True, bias=True) + self.upsample = nn.Sequential(*[UpconvBlock(nf, nf, block=ConvGnLelu, norm=False, activation=True, bias=True) for _ in range(n_upscale)]) + self.final_hr_conv1 = ConvGnLelu(nf, nf, kernel_size=3, norm=False, activation=False, bias=True) + self.final_hr_conv2 = ConvGnLelu(nf, out_nc, kernel_size=3, norm=False, activation=False, bias=False) + self.switches = [self.sw1, self.sw2, self.sw_grad, self.conjoin_sw] + self.attentions = None + self.init_temperature = init_temperature + self.final_temperature_step = 10000 + + def forward(self, x, embedding): + noise_stds = [] + + x_grad = self.get_g_nopadding(x) + + x = self.model_fea_conv(x) + x1 = x + x1, a1 = self.sw1(x1, True, identity=x, att_in=(x1, embedding)) + + x2 = x1 + x2, nstd = self.noise_ref_join(x2, torch.randn_like(x2)) + x2, a2 = self.sw2(x2, True, identity=x1, att_in=(x2, embedding)) + noise_stds.append(nstd) + + x_grad = self.grad_conv(x_grad) + x_grad_identity = x_grad + x_grad, nstd = self.noise_ref_join_grad(x_grad, torch.randn_like(x_grad)) + x_grad, grad_fea_std = self.grad_ref_join(x_grad, x1) + x_grad, a3 = self.sw_grad(x_grad, True, identity=x_grad_identity, att_in=(x_grad, embedding)) + x_grad = self.grad_lr_conv(x_grad) + x_grad = self.grad_lr_conv2(x_grad) + x_grad_out = self.upsample_grad(x_grad) + x_grad_out = self.grad_branch_output_conv(x_grad_out) + noise_stds.append(nstd) + + x_out = x2 + x_out, nstd = self.noise_ref_join_conjoin(x_out, torch.randn_like(x_out)) + x_out, fea_grad_std = self.conjoin_ref_join(x_out, x_grad) + x_out, a4 = self.conjoin_sw(x_out, True, identity=x2, att_in=(x_out, embedding)) + x_out = self.final_lr_conv(x_out) + x_out = self.upsample(x_out) + x_out = self.final_hr_conv1(x_out) + x_out = self.final_hr_conv2(x_out) + noise_stds.append(nstd) + + self.attentions = [a1, a2, a3, a4] + self.noise_stds = torch.stack(noise_stds).mean().detach().cpu() + self.grad_fea_std = grad_fea_std.detach().cpu() + self.fea_grad_std = fea_grad_std.detach().cpu() + return x_grad_out, x_out, x_grad + + def set_temperature(self, temp): + [sw.set_temperature(temp) for sw in self.switches] + + def update_for_step(self, step, experiments_path='.'): + if self.attentions: + temp = max(1, 1 + self.init_temperature * + (self.final_temperature_step - step) / self.final_temperature_step) + self.set_temperature(temp) + if step % 200 == 0: + output_path = os.path.join(experiments_path, "attention_maps", "a%i") + prefix = "attention_map_%i_%%i.png" % (step,) + [save_attention_to_image_rgb(output_path % (i,), self.attentions[i], self.transformation_counts, prefix, step) for i in range(len(self.attentions))] + + def get_debug_values(self, step): + temp = self.switches[0].switch.temperature + mean_hists = [compute_attention_specificity(att, 2) for att in self.attentions] + means = [i[0] for i in mean_hists] + hists = [i[1].clone().detach().cpu().flatten() for i in mean_hists] + val = {"switch_temperature": temp, + "noise_branch_std_dev": self.noise_stds, + "grad_branch_feat_intg_std_dev": self.grad_fea_std, + "conjoin_branch_grad_intg_std_dev": self.fea_grad_std} + for i in range(len(means)): + val["switch_%i_specificity" % (i,)] = means[i] + val["switch_%i_histogram" % (i,)] = hists[i] + return val diff --git a/codes/models/archs/SwitchedResidualGenerator_arch.py b/codes/models/archs/SwitchedResidualGenerator_arch.py index ac875237..a20ed792 100644 --- a/codes/models/archs/SwitchedResidualGenerator_arch.py +++ b/codes/models/archs/SwitchedResidualGenerator_arch.py @@ -8,6 +8,7 @@ from models.archs.arch_util import ConvBnLelu, ConvGnSilu, ExpansionBlock, Expan from switched_conv_util import save_attention_to_image_rgb import os from torch.utils.checkpoint import checkpoint +from models.archs.spinenet_arch import SpineNet # Set to true to relieve memory pressure by using torch.utils.checkpoint in several memory-critical locations. @@ -335,3 +336,106 @@ class ConfigurableSwitchedResidualGenerator2(nn.Module): val["switch_%i_histogram" % (i,)] = hists[i] return val + +# This class encapsulates an encoder based on an object detection network backbone whose purpose is to generated a +# structured embedding encoding what is in an image patch. This embedding can then be used to perform structured +# alterations to the underlying image. +# +# Caveat: Since this uses a pre-defined (and potentially pre-trained) SpineNet backbone, it has a minimum-supported +# image size, which is 128x128. In order to use 64x64 patches, you must set interpolate_first=True. though this will +# degrade quality. +class BackboneEncoder(nn.Module): + def __init__(self, interpolate_first=True, pretrained_backbone=None): + super(BackboneEncoder, self).__init__() + self.interpolate_first = interpolate_first + + # Uses dual spinenets, one for the input patch and the other for the reference image. + self.patch_spine = SpineNet('49', in_channels=3, use_input_norm=True) + self.ref_spine = SpineNet('49', in_channels=3, use_input_norm=True) + + self.merge_process1 = ConvGnSilu(512, 512, kernel_size=1, activation=True, norm=False, bias=True) + self.merge_process2 = ConvGnSilu(512, 384, kernel_size=1, activation=True, norm=True, bias=False) + self.merge_process3 = ConvGnSilu(384, 256, kernel_size=1, activation=False, norm=False, bias=True) + + if pretrained_backbone is not None: + loaded_params = torch.load(pretrained_backbone) + self.ref_spine.load_state_dict(loaded_params['state_dict'], strict=True) + self.patch_spine.load_state_dict(loaded_params['state_dict'], strict=True) + + # Returned embedding will have been reduced in size by a factor of 8 (4 if interpolate_first=True). + # Output channels are always 256. + # ex, 64x64 input with interpolate_first=True will result in tensor of shape [bx256x16x16] + def forward(self, x, ref, ref_center_point): + if self.interpolate_first: + x = F.interpolate(x, scale_factor=2, mode="bicubic") + # Don't interpolate ref - assume it is fed in at the proper resolution. + # ref = F.interpolate(ref, scale_factor=2, mode="bicubic") + + # [ref] will have a 'mask' channel which we cannot use with pretrained spinenet. + ref = ref[:, :3, :, :] + ref_emb = checkpoint(self.ref_spine, ref)[0] + ref_code = gather_2d(ref_emb, ref_center_point // 8) # Divide by 8 to bring the center point to the correct location. + + patch = checkpoint(self.ref_spine, x)[0] + ref_code_expanded = ref_code.view(-1, 256, 1, 1).repeat(1, 1, patch.shape[2], patch.shape[3]) + combined = self.merge_process1(torch.cat([patch, ref_code_expanded], dim=1)) + combined = self.merge_process2(combined) + combined = self.merge_process3(combined) + + return combined + + +# Mutiplexer that combines a structured embedding with a contextual switch input to guide alterations to that input. +# +# Implemented as basically a u-net which reduces the input into the same structural space as the embedding, combines the +# two, then expands back into the original feature space. +class EmbeddingMultiplexer(nn.Module): + # Note: reductions=2 if the encoder is using interpolated input, otherwise reductions=3. + def __init__(self, nf, multiplexer_channels, reductions=2): + super(EmbeddingMultiplexer, self).__init__() + self.embedding_process = MultiConvBlock(256, 256, 256, kernel_size=3, depth=3, norm=True) + + self.filter_conv = ConvGnSilu(nf, nf, activation=True, norm=False, bias=True) + self.reduction_blocks = nn.ModuleList([HalvingProcessingBlock(nf * 2 ** i) for i in range(reductions)]) + reduction_filters = nf * 2 ** reductions + self.processing_blocks = nn.Sequential( + ConvGnSilu(reduction_filters + 256, reduction_filters + 256, kernel_size=1, activation=True, norm=False, bias=True), + ConvGnSilu(reduction_filters + 256, reduction_filters + 128, kernel_size=1, activation=True, norm=True, bias=False), + ConvGnSilu(reduction_filters + 128, reduction_filters, kernel_size=3, activation=True, norm=True, bias=False), + ConvGnSilu(reduction_filters, reduction_filters, kernel_size=3, activation=True, norm=True, bias=False)) + self.expansion_blocks = nn.ModuleList([ExpansionBlock2(reduction_filters // (2 ** i)) for i in range(reductions)]) + + gap = nf - multiplexer_channels + cbl1_out = ((nf - (gap // 2)) // 4) * 4 # Must be multiples of 4 to use with group norm. + self.cbl1 = ConvGnSilu(nf, cbl1_out, norm=True, bias=False, num_groups=4) + cbl2_out = ((nf - (3 * gap // 4)) // 4) * 4 + self.cbl2 = ConvGnSilu(cbl1_out, cbl2_out, norm=True, bias=False, num_groups=4) + self.cbl3 = ConvGnSilu(cbl2_out, multiplexer_channels, bias=True, norm=False) + + def forward(self, x, embedding): + x = self.filter_conv(x) + embedding = self.embedding_process(embedding) + + reduction_identities = [] + for b in self.reduction_blocks: + reduction_identities.append(x) + x = b(x) + x = self.processing_blocks(torch.cat([x, embedding], dim=1)) + for i, b in enumerate(self.expansion_blocks): + x = b(x, reduction_identities[-i - 1]) + + x = self.cbl1(x) + x = self.cbl2(x) + x = self.cbl3(x) + return x + +if __name__ == '__main__': + bb = BackboneEncoder(64) + emb = EmbeddingMultiplexer(64, 10) + x = torch.randn(4,3,64,64) + r = torch.randn(4,4,64,64) + xu = torch.randn(4,64,64,64) + cp = torch.zeros((4,2), dtype=torch.long) + + b = bb(x, r, cp) + emb(xu, b) \ No newline at end of file diff --git a/codes/models/archs/spinenet_arch.py b/codes/models/archs/spinenet_arch.py index 2e30b82b..e813781c 100644 --- a/codes/models/archs/spinenet_arch.py +++ b/codes/models/archs/spinenet_arch.py @@ -365,4 +365,4 @@ class SpineNet(nn.Module): if spec.is_output: output_feat[spec.level] = target_feat - return [self.endpoint_convs[str(level)](output_feat[level]) for level in self.output_level] \ No newline at end of file + return tuple([self.endpoint_convs[str(level)](output_feat[level]) for level in self.output_level]) \ No newline at end of file diff --git a/codes/models/networks.py b/codes/models/networks.py index 035cc0ae..8c8dd887 100644 --- a/codes/models/networks.py +++ b/codes/models/networks.py @@ -51,6 +51,12 @@ def define_G(opt, net_key='network_G', scale=None): xforms = opt_net['num_transforms'] if 'num_transforms' in opt_net.keys() else 8 netG = spsr.SwitchedSpsrWithRef2(in_nc=3, out_nc=3, nf=opt_net['nf'], xforms=xforms, upscale=opt_net['scale'], init_temperature=opt_net['temperature'] if 'temperature' in opt_net.keys() else 10) + elif which_model == "spsr4": + xforms = opt_net['num_transforms'] if 'num_transforms' in opt_net.keys() else 8 + netG = spsr.Spsr4(in_nc=3, out_nc=3, nf=opt_net['nf'], xforms=xforms, upscale=opt_net['scale'], + init_temperature=opt_net['temperature'] if 'temperature' in opt_net.keys() else 10) + elif which_model == "backbone_encoder": + netG = SwitchedGen_arch.BackboneEncoder(pretrained_backbone=opt_net['pretrained_spinenet']) else: raise NotImplementedError('Generator model [{:s}] not recognized'.format(which_model))