|
- # Copyright (c) Meta Platforms, Inc. and affiliates.
-
- # All rights reserved.
-
- # This source code is licensed under the license found in the
- # LICENSE file in the root directory of this source tree.
-
-
- import torch
- import torch.nn as nn
- import torch.nn.functional as F
- from timm.models.layers import trunc_normal_, DropPath
- from timm.models.registry import register_model
- import numpy as np
- import torchvision.models as models
- #import cv2
- from PIL import Image
- from torch.autograd import Variable
- from torch.autograd import Function
-
- class Block(nn.Module):
- r""" ConvNeXt Block. There are two equivalent implementations:
- (1) DwConv -> LayerNorm (channels_first) -> 1x1 Conv -> GELU -> 1x1 Conv; all in (N, C, H, W)
- (2) DwConv -> Permute to (N, H, W, C); LayerNorm (channels_last) -> Linear -> GELU -> Linear; Permute back
- We use (2) as we find it slightly faster in PyTorch
-
- Args:
- dim (int): Number of input channels.
- drop_path (float): Stochastic depth rate. Default: 0.0
- layer_scale_init_value (float): Init value for Layer Scale. Default: 1e-6.
- """
- def __init__(self, dim, drop_path=0., layer_scale_init_value=1e-6):
- super().__init__()
- self.dwconv = nn.Conv2d(dim, dim, kernel_size=7, padding=3, groups=dim) # depthwise conv
- self.norm = LayerNorm(dim, eps=1e-6)
- self.pwconv1 = nn.Linear(dim, 4 * dim) # pointwise/1x1 convs, implemented with linear layers
- self.act = nn.GELU()
- self.pwconv2 = nn.Linear(4 * dim, dim)
- self.gamma = nn.Parameter(layer_scale_init_value * torch.ones((dim)),
- requires_grad=True) if layer_scale_init_value > 0 else None
- self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
-
- def forward(self, x):
- input = x
- x = self.dwconv(x)
- x = x.permute(0, 2, 3, 1) # (N, C, H, W) -> (N, H, W, C)
- x = self.norm(x)
- x = self.pwconv1(x)
- x = self.act(x)
- x = self.pwconv2(x)
- if self.gamma is not None:
- x = self.gamma * x
- x = x.permute(0, 3, 1, 2) # (N, H, W, C) -> (N, C, H, W)
-
- x = input + self.drop_path(x)
- return x
-
- class ConvNeXt(nn.Module):
- r""" ConvNeXt
- A PyTorch impl of : `A ConvNet for the 2020s` -
- https://arxiv.org/pdf/2201.03545.pdf
-
- Args:
- in_chans (int): Number of input image channels. Default: 3
- num_classes (int): Number of classes for classification head. Default: 1000
- depths (tuple(int)): Number of blocks at each stage. Default: [3, 3, 9, 3]
- dims (int): Feature dimension at each stage. Default: [96, 192, 384, 768]
- drop_path_rate (float): Stochastic depth rate. Default: 0.
- layer_scale_init_value (float): Init value for Layer Scale. Default: 1e-6.
- head_init_scale (float): Init scaling value for classifier weights and biases. Default: 1.
- """
- def __init__(self, in_chans=3, num_classes=1000,
- depths=[3, 3, 9, 3], dims=[96, 192, 384, 768], drop_path_rate=0.,
- layer_scale_init_value=1e-6, head_init_scale=1.,
- ):
- super().__init__()
-
- self.downsample_layers = nn.ModuleList() # stem and 3 intermediate downsampling conv layers
- stem = nn.Sequential(
- nn.Conv2d(in_chans, dims[0], kernel_size=4, stride=4),
- LayerNorm(dims[0], eps=1e-6, data_format="channels_first")
- )
- self.downsample_layers.append(stem)
- for i in range(3):
- downsample_layer = nn.Sequential(
- LayerNorm(dims[i], eps=1e-6, data_format="channels_first"),
- nn.Conv2d(dims[i], dims[i+1], kernel_size=2, stride=2),
- )
- self.downsample_layers.append(downsample_layer)
-
- self.stages = nn.ModuleList() # 4 feature resolution stages, each consisting of multiple residual blocks
- dp_rates=[x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))]
- cur = 0
- for i in range(4):
- stage = nn.Sequential(
- *[Block(dim=dims[i], drop_path=dp_rates[cur + j],
- layer_scale_init_value=layer_scale_init_value) for j in range(depths[i])]
- )
- self.stages.append(stage)
- cur += depths[i]
-
- self.norm = nn.LayerNorm(dims[-1], eps=1e-6) # final norm layer
- self.head = nn.Linear(dims[-1], num_classes)
-
- self.apply(self._init_weights)
- self.head.weight.data.mul_(head_init_scale)
- self.head.bias.data.mul_(head_init_scale)
-
- def _init_weights(self, m):
- if isinstance(m, (nn.Conv2d, nn.Linear)):
- trunc_normal_(m.weight, std=.02)
- nn.init.constant_(m.bias, 0)
-
- def forward_features(self, x):
- for i in range(4):
- x = self.downsample_layers[i](x)
- x = self.stages[i](x)
- return self.norm(x.mean([-2, -1])) # global average pooling, (N, C, H, W) -> (N, C)
-
- def forward(self, x):
- #x = self.forward_features(x)
- #x = self.head(x)
- x0 = self.downsample_layers[0](x)
- x0 = self.stages[0](x0)
-
- x1 = self.downsample_layers[1](x0)
- x1 = self.stages[1](x1)
-
- x2 = self.downsample_layers[2](x1)
- x2 = self.stages[2](x2)
-
- x3 = self.downsample_layers[3](x2)
- x3 = self.stages[3](x3)
-
- #xx = self.norm(x3.mean([-2, -1]))
- #output = self.head(xx)
- return x0, x1, x2, x3#, xx, output
-
- class LayerNorm(nn.Module):
- r""" LayerNorm that supports two data formats: channels_last (default) or channels_first.
- The ordering of the dimensions in the inputs. channels_last corresponds to inputs with
- shape (batch_size, height, width, channels) while channels_first corresponds to inputs
- with shape (batch_size, channels, height, width).
- """
- def __init__(self, normalized_shape, eps=1e-6, data_format="channels_last"):
- super().__init__()
- self.weight = nn.Parameter(torch.ones(normalized_shape))
- self.bias = nn.Parameter(torch.zeros(normalized_shape))
- self.eps = eps
- self.data_format = data_format
- if self.data_format not in ["channels_last", "channels_first"]:
- raise NotImplementedError
- self.normalized_shape = (normalized_shape, )
-
- def forward(self, x):
- if self.data_format == "channels_last":
- return F.layer_norm(x, self.normalized_shape, self.weight, self.bias, self.eps)
- elif self.data_format == "channels_first":
- u = x.mean(1, keepdim=True)
- s = (x - u).pow(2).mean(1, keepdim=True)
- x = (x - u) / torch.sqrt(s + self.eps)
- x = self.weight[:, None, None] * x + self.bias[:, None, None]
- return x
-
-
- model_urls = {
- "convnext_tiny_1k": "https://dl.fbaipublicfiles.com/convnext/convnext_tiny_1k_224_ema.pth",
- "convnext_small_1k": "https://dl.fbaipublicfiles.com/convnext/convnext_small_1k_224_ema.pth",
- "convnext_base_1k": "https://dl.fbaipublicfiles.com/convnext/convnext_base_1k_224_ema.pth",
- "convnext_large_1k": "https://dl.fbaipublicfiles.com/convnext/convnext_large_1k_224_ema.pth",
- "convnext_tiny_22k": "https://dl.fbaipublicfiles.com/convnext/convnext_tiny_22k_224.pth",
- "convnext_small_22k": "https://dl.fbaipublicfiles.com/convnext/convnext_small_22k_224.pth",
- "convnext_base_22k": "https://dl.fbaipublicfiles.com/convnext/convnext_base_22k_224.pth",
- "convnext_large_22k": "https://dl.fbaipublicfiles.com/convnext/convnext_large_22k_224.pth",
- "convnext_xlarge_22k": "https://dl.fbaipublicfiles.com/convnext/convnext_xlarge_22k_224.pth",
- }
-
- @register_model
- def convnext_tiny(pretrained=False,in_22k=False, **kwargs):
- model = ConvNeXt(depths=[3, 3, 9, 3], dims=[96, 192, 384, 768], **kwargs)
- if pretrained:
- pretrained_dict = torch.load("/dataset/pth/convnext_tiny_1k_224_ema.pth")
- model_dict = model.state_dict()
- # 1. filter out unnecessary keys
- pretrained_dict = {k: v for k, v in pretrained_dict.items() if k in model_dict}
- # 2. overwrite entries in the existing state dict
- model_dict.update(pretrained_dict)
- model.load_state_dict(model_dict)
- return model
-
- @register_model
- def convnext_small(pretrained=False,in_22k=False, **kwargs):
- model = ConvNeXt(depths=[3, 3, 27, 3], dims=[96, 192, 384, 768], **kwargs)
- if pretrained:
- pretrained_dict = torch.load("/dataset/pth/convnext_small_1k_224_ema.pth")
- model_dict = model.state_dict()
- # 1. filter out unnecessary keys
- pretrained_dict = {k: v for k, v in pretrained_dict.items() if k in model_dict}
- # 2. overwrite entries in the existing state dict
- model_dict.update(pretrained_dict)
- model.load_state_dict(model_dict)
- return model
-
- @register_model
- def convnext_base(pretrained=False, in_22k=False, **kwargs):
- model = ConvNeXt(depths=[3, 3, 27, 3], dims=[128, 256, 512, 1024], **kwargs)
- if pretrained:
- pretrained_dict = torch.load("/dataset/pth/convnext_base_1k_224_ema.pth")
- model_dict = model.state_dict()
- # 1. filter out unnecessary keys
- pretrained_dict = {k: v for k, v in pretrained_dict.items() if k in model_dict}
- # 2. overwrite entries in the existing state dict
- model_dict.update(pretrained_dict)
- model.load_state_dict(model_dict)
- return model
-
- @register_model
- def convnext_large(pretrained=False, in_22k=False, **kwargs):
- model = ConvNeXt(depths=[3, 3, 27, 3], dims=[192, 384, 768, 1536], **kwargs)
- if pretrained:
- url = model_urls['convnext_large_22k'] if in_22k else model_urls['convnext_large_1k']
- checkpoint = torch.hub.load_state_dict_from_url(url=url, map_location="cpu")
- model.load_state_dict(checkpoint["model"])
- return model
-
- @register_model
- def convnext_xlarge(pretrained=False, in_22k=False, **kwargs):
- model = ConvNeXt(depths=[3, 3, 27, 3], dims=[256, 512, 1024, 2048], **kwargs)
- if pretrained:
- assert in_22k, "only ImageNet-22K pre-trained ConvNeXt-XL is available; please set in_22k=True"
- url = model_urls['convnext_xlarge_22k']
- checkpoint = torch.hub.load_state_dict_from_url(url=url, map_location="cpu")
- model.load_state_dict(checkpoint["model"])
- return model
-
- """ Function() reference!!!!!!!!!! """
- def cus_sample(feat, **kwargs):
- assert len(kwargs.keys()) == 1 and list(kwargs.keys())[0] in ["size", "scale_factor"]
- return F.interpolate(feat, **kwargs, mode="bilinear", align_corners=False)
-
- def rgb2gray(rgb):
- b, g, r = rgb[:, 0, :, :], rgb[:, 1, :, :], rgb[:, 2, :, :]
- gray = 0.2989*r + 0.5870*g + 0.1140*b
- gray = torch.unsqueeze(gray, 1)
- return gray
-
- class BayarConv2d(nn.Module):
- def __init__(self, in_channels, out_channels, kernel_size=5, stride=1, padding=0):
- self.in_channels = in_channels
- self.out_channels = out_channels
- self.kernel_size = kernel_size
- self.stride = stride
- self.padding = padding
- self.minus1 = (torch.ones(self.in_channels, self.out_channels, 1) * -1.000)
-
- super(BayarConv2d, self).__init__()
- # only (kernel_size ** 2 - 1) trainable params as the center element is always -1
- self.kernel = nn.Parameter(torch.rand(self.in_channels, self.out_channels, kernel_size ** 2 - 1),
- requires_grad=True)
-
-
- def bayarConstraint(self):
- self.kernel.data = self.kernel.permute(2, 0, 1)
- self.kernel.data = torch.div(self.kernel.data, self.kernel.data.sum(0))
- self.kernel.data = self.kernel.permute(1, 2, 0)
- ctr = self.kernel_size ** 2 // 2
- real_kernel = torch.cat((self.kernel[:, :, :ctr], self.minus1.to(self.kernel.device), self.kernel[:, :, ctr:]), dim=2)
- real_kernel = real_kernel.reshape((self.out_channels, self.in_channels, self.kernel_size, self.kernel_size))
- return real_kernel
-
- def forward(self, x):
- x = F.conv2d(x, self.bayarConstraint(), stride=self.stride, padding=self.padding)
- return x
-
-
- class SRMConv2d_Separate(nn.Module):
-
- def __init__(self, inc, outc, learnable=False):
- super(SRMConv2d_Separate, self).__init__()
- self.inc = inc
- self.truc = nn.Hardtanh(-3, 3)
- kernel = self._build_kernel(inc) # (3,3,5,5)
- self.kernel = nn.Parameter(data=kernel, requires_grad=learnable)
- # self.hor_kernel = self._build_kernel().transpose(0,1,3,2)
- self.out_conv = nn.Sequential(
- nn.Conv2d(3*inc, outc, 1, 1, 0, 1, 1, bias=False),
- nn.BatchNorm2d(outc),
- nn.ReLU(inplace=True)
- )
-
- for ly in self.out_conv.children():
- if isinstance(ly, nn.Conv2d):
- nn.init.kaiming_normal_(ly.weight, a=1)
-
- def forward(self, x):
- '''
- x: imgs (Batch, H, W, 3)
- '''
- out = F.conv2d(x, self.kernel, stride=1, padding=2, groups=self.inc)
- out = self.truc(out)
- out = self.out_conv(out)
-
- return out
-
- def _build_kernel(self, inc):
- # filter1: KB
- filter1 = [[0, 0, 0, 0, 0],
- [0, -1, 2, -1, 0],
- [0, 2, -4, 2, 0],
- [0, -1, 2, -1, 0],
- [0, 0, 0, 0, 0]]
- # filter2:KV
- filter2 = [[-1, 2, -2, 2, -1],
- [2, -6, 8, -6, 2],
- [-2, 8, -12, 8, -2],
- [2, -6, 8, -6, 2],
- [-1, 2, -2, 2, -1]]
- # # filter3:hor 2rd
- filter3 = [[0, 0, 0, 0, 0],
- [0, 0, 0, 0, 0],
- [0, 1, -2, 1, 0],
- [0, 0, 0, 0, 0],
- [0, 0, 0, 0, 0]]
-
- filter1 = np.asarray(filter1, dtype=float) / 4.
- filter2 = np.asarray(filter2, dtype=float) / 12.
- filter3 = np.asarray(filter3, dtype=float) / 2.
- # statck the filters
- filters = [[filter1],#, filter1, filter1],
- [filter2],#, filter2, filter2],
- [filter3]]#, filter3, filter3]] # (3,3,5,5)
- filters = np.array(filters)
- # filters = np.repeat(filters, inc, axis=1)
- filters = np.repeat(filters, inc, axis=0)
- filters = torch.FloatTensor(filters) # (3,3,5,5)
- # print(filters.size())
- return filters
-
- def DCT_mat(size):
- m = [[ (np.sqrt(1./size) if i == 0 else np.sqrt(2./size)) * np.cos((j + 0.5) * np.pi * i / size) for j in range(size)] for i in range(size)]
- return m
- # Filter Module
- class Filter(nn.Module):
- def __init__(self, size, band_start, band_end, use_learnable=True, norm=False):
- super(Filter, self).__init__()
- self.use_learnable = use_learnable
-
- self.base = nn.Parameter(torch.tensor(generate_filter(band_start, band_end, size)), requires_grad=False)
- if self.use_learnable:
- self.learnable = nn.Parameter(torch.randn(size, size), requires_grad=True)
- self.learnable.data.normal_(0., 0.1)
- # Todo
- # self.learnable = nn.Parameter(torch.rand((size, size)) * 0.2 - 0.1, requires_grad=True)
-
- self.norm = norm
- if norm:
- self.ft_num = nn.Parameter(torch.sum(torch.tensor(generate_filter(band_start, band_end, size))), requires_grad=False)
-
-
- def forward(self, x):
- if self.use_learnable:
- filt = self.base + norm_sigma(self.learnable)
- else:
- filt = self.base
-
- if self.norm:
- y = x * filt / self.ft_num
- else:
- y = x * filt
- return y
-
- # LFS Module
- class LFS_Head(nn.Module):
- def __init__(self, size, window_size, M):
- super(LFS_Head, self).__init__()
-
- self.window_size = window_size
- self._M = M
-
- # init DCT matrix
- self._DCT_patch = nn.Parameter(torch.tensor(DCT_mat(window_size)).float(), requires_grad=False)
- self._DCT_patch_T = nn.Parameter(torch.transpose(torch.tensor(DCT_mat(window_size)).float(), 0, 1), requires_grad=False)
-
- self.unfold = nn.Unfold(kernel_size=(window_size, window_size), stride=2, padding=4)
-
- # init filters
- self.filters = nn.ModuleList([Filter(window_size, window_size * 2. / M * i, window_size * 2. / M * (i+1), norm=True) for i in range(M)])
-
- def forward(self, x):
-
- N, C, W, H = x.size()
- S = self.window_size
- size_after = int((W - S + 8)/2) + 1
- #assert size_after == 149
-
- # sliding window unfold and DCT
- x_unfold = self.unfold(x) # [N, C * S * S, L] L:block num
- L = x_unfold.size()[2]
- x_unfold = x_unfold.transpose(1, 2).reshape(N, L, C, S, S) # [N, L, C, S, S]
- x_dct = self._DCT_patch @ x_unfold @ self._DCT_patch_T
-
- # M kernels filtering
- y_list = []
- for i in range(self._M):
- y = torch.abs(x_dct)
- y = torch.log10(y + 1e-15)
- y = self.filters[i](y)
- y = torch.sum(y, dim=[2,3,4])
- y = y.reshape(N, size_after, size_after).unsqueeze(dim=1) # [N, 1, 149, 149]
- y_list.append(y)
- out = torch.cat(y_list, dim=1) # [N, M, 149, 149]
- return out
-
- def generate_filter(start, end, size):
- return [[0. if i + j > end or i + j < start else 1. for j in range(size)] for i in range(size)]
-
- def norm_sigma(x):
- return 2. * torch.sigmoid(x) - 1.
-
- """ Net!!!!!!!!!! """
- class ei_Net_Resnet50(nn.Module):
- def __init__(self):
- super(ei_Net_Resnet50, self).__init__()
-
- self.convnext_backbone = convnext_tiny(pretrained=True)
- #self.convnext_backbone = convnext_small(pretrained=True)
-
- self.upsample_2 = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True)
-
- self.constrain_conv = BayarConv2d(in_channels=1, out_channels=3, padding=2)
-
- self.srm_conv1 = SRMConv2d_Separate(96, 96)
- self.srm_conv2 = SRMConv2d_Separate(192, 192)
- self.srm_conv3 = SRMConv2d_Separate(384, 384)
- self.srm_conv4 = SRMConv2d_Separate(768, 768)
-
- self.LFS_head1 = LFS_Head(80, 10, 8)
- self.LFS_head2 = LFS_Head(40, 10, 8)
- self.LFS_head3 = LFS_Head(20, 10, 8)
- self.LFS_head4 = LFS_Head(10, 10, 8)
-
- self.convqq1 = nn.Conv2d(96, 32, 3, 1, 1)
- self.convqq2 = nn.Conv2d(192, 32, 3, 1, 1)
- self.convqq3 = nn.Conv2d(384, 32, 3, 1, 1)
- self.convqq4 = nn.Conv2d(768, 32, 3, 1, 1)
-
- self.convlow = nn.Conv2d(1, 32, 3, 1, 1)
- self.convhigh = nn.Conv2d(7, 32, 3, 1, 1)
-
- self.conv1 = nn.Conv2d(96+32, 32, 3, 1, 1)
- self.gn1 = nn.GroupNorm(32, 32)
- self.conv2 = nn.Conv2d(192+32+32, 32, 3, 1, 1)
- self.gn2 = nn.GroupNorm(32, 32)
- self.conv3 = nn.Conv2d(384+32+32, 32, 3, 1, 1)
- self.gn3 = nn.GroupNorm(32, 32)
- self.conv4 = nn.Conv2d(768+32+32, 256, 3, 1, 1)
- self.gn4 = nn.GroupNorm(256, 256)
- self.relu = nn.ReLU(True)
-
- self.conv_32 = nn.Conv2d(32, 32, 3, 1, 1)
- self.gn = nn.GroupNorm(32, 32)
-
- self.conv_r1 = nn.Conv2d(96+32, 32, 3, 1, 1)
- self.conv_r2 = nn.Conv2d(192+32+32, 32, 3, 1, 1)
- self.conv_r3 = nn.Conv2d(384+32+32, 32, 3, 1, 1)
- self.conv_r4 = nn.Conv2d(768+32+32, 256, 3, 1, 1)
- self.gn4 = nn.GroupNorm(256, 256)
- self.relu = nn.ReLU(True)
-
- self.conv1_2 = nn.Conv2d(96, 192, 3, 1, 1)
- self.conv2_3 = nn.Conv2d(192, 384, 3, 1, 1)
- self.conv3_4 = nn.Conv2d(384, 768, 3, 1, 1)
-
- #self.down = nn.Conv2d(768*2, 256, 3, 1, 1)
-
- self.flat1 = nn.Conv2d(256, 128, kernel_size=1)
- self.flat2 = nn.Conv2d(128, 128, kernel_size=2)
-
- self.downsample = nn.AvgPool2d((2, 2), stride=2)
-
- self.conv__3 = nn.Conv2d(128, 128, 3, 1, 1)
- self.gn_128 = nn.GroupNorm(128, 128)
-
- self.classifier = nn.Conv2d(256, 1, 1)
-
- def forward(self, x):
-
- x1, x2, x3, x4 = self.convnext_backbone(x)
-
- s1 = self.srm_conv1(x1)
- s2 = self.srm_conv2(x2)
- s3 = self.srm_conv3(x3)
- s4 = self.srm_conv4(x4)
-
- l1 = self.LFS_head1(self.relu(self.gn(self.convqq1(x1))))
- l2 = self.LFS_head2(self.relu(self.gn(self.convqq2(x2))))
- l3 = self.LFS_head3(self.relu(self.gn(self.convqq3(x3))))
- l4 = self.LFS_head4(self.relu(self.gn(self.convqq4(x4))))
-
- #print(l1.shape)
-
- list_of_l1 = torch.split(l1, [1,7], dim=1)
- list_of_l2 = torch.split(l2, [1,7], dim=1)
- list_of_l3 = torch.split(l3, [1,7], dim=1)
- list_of_l4 = torch.split(l4, [1,7], dim=1)
-
- low_l1 = list_of_l1[0]
- high_l1 = list_of_l1[1]
- low_l1 = self.relu(self.gn(self.convlow(low_l1)))
- high_l1 = self.relu(self.gn(self.convhigh(high_l1)))
- low_l1 = F.interpolate(low_l1, x1.size()[2:], mode="bilinear", align_corners=False)
- high_l1 = F.interpolate(high_l1, s1.size()[2:], mode="bilinear", align_corners=False)
- #print(low_l1.shape, high_l1.shape)
-
- low_l2 = list_of_l2[0]
- high_l2 = list_of_l2[1]
- low_l2 = self.relu(self.gn(self.convlow(low_l2)))
- high_l2 = self.relu(self.gn(self.convhigh(high_l2)))
- low_l2 = F.interpolate(low_l2, x2.size()[2:], mode="bilinear", align_corners=False)
- high_l2 = F.interpolate(high_l2, s2.size()[2:], mode="bilinear", align_corners=False)
- #print(low_l2.shape, high_l2.shape)
-
- low_l3 = list_of_l3[0]
- high_l3 = list_of_l3[1]
- low_l3 = self.relu(self.gn(self.convlow(low_l3)))
- high_l3 = self.relu(self.gn(self.convhigh(high_l3)))
- low_l3 = F.interpolate(low_l3, x3.size()[2:], mode="bilinear", align_corners=False)
- high_l3 = F.interpolate(high_l3, s3.size()[2:], mode="bilinear", align_corners=False)
- #print(low_l3.shape, high_l3.shape)
-
- low_l4 = list_of_l4[0]
- high_l4 = list_of_l4[1]
- low_l4 = self.relu(self.gn(self.convlow(low_l4)))
- high_l4 = self.relu(self.gn(self.convhigh(high_l4)))
- low_l4 = F.interpolate(low_l4, x4.size()[2:], mode="bilinear", align_corners=False)
- high_l4 = F.interpolate(high_l4, s4.size()[2:], mode="bilinear", align_corners=False)
- #print(low_l4.shape, high_l4.shape)
-
- n1_cat = torch.cat([s1, high_l1], dim=1)
- n1_cat = self.relu(self.gn1(self.conv1(n1_cat)))
- n1_cat = F.interpolate(n1_cat, s2.size()[2:], mode="bilinear", align_corners=False)
- n1_cat = self.relu(self.gn(self.conv_32(n1_cat)))
-
- n2_cat = torch.cat([s2, high_l2, n1_cat], dim=1)
- n2_cat = self.relu(self.gn2(self.conv2(n2_cat)))
- n2_cat = F.interpolate(n2_cat, s3.size()[2:], mode="bilinear", align_corners=False)
- n2_cat = self.relu(self.gn(self.conv_32(n2_cat)))
-
- n3_cat = torch.cat([s3, high_l3, n2_cat], dim=1)
- n3_cat = self.relu(self.gn3(self.conv3(n3_cat)))
- n3_cat = F.interpolate(n3_cat, s4.size()[2:], mode="bilinear", align_corners=False)
- n3_cat = self.relu(self.gn(self.conv_32(n3_cat)))
-
- n4_cat = torch.cat([s4, high_l4, n3_cat], dim=1)
- n4_cat = self.relu(self.gn4(self.conv4(n4_cat)))
- #print(n4_cat.shape)
-
- r1_cat = torch.cat([x1, low_l1], dim=1)
- r1_cat = self.relu(self.gn1(self.conv_r1(r1_cat)))
- r1_cat = F.interpolate(r1_cat, x2.size()[2:], mode="bilinear", align_corners=False)
- r1_cat = self.relu(self.gn(self.conv_32(r1_cat)))
- #print(r1_cat.shape)
-
- r2_cat = torch.cat([x2, low_l2, r1_cat], dim=1)
- r2_cat = self.relu(self.gn2(self.conv_r2(r2_cat)))
- r2_cat = F.interpolate(r2_cat, x3.size()[2:], mode="bilinear", align_corners=False)
- r2_cat = self.relu(self.gn(self.conv_32(r2_cat)))
- #print(r2_cat.shape)
-
- r3_cat = torch.cat([x3, low_l3, r2_cat], dim=1)
- r3_cat = self.relu(self.gn3(self.conv_r3(r3_cat)))
- r3_cat = F.interpolate(r3_cat, x4.size()[2:], mode="bilinear", align_corners=False)
- r3_cat = self.relu(self.gn(self.conv_32(r3_cat)))
- #print(r3_cat.shape)
-
- r4_cat = torch.cat([x4, low_l4, r3_cat], dim=1)
- r4_cat = self.relu(self.gn4(self.conv_r4(r4_cat)))
- #print(r4_cat.shape)
-
- n1 = self.flat1(n4_cat)
- n2 = self.flat1(r4_cat)
- nt1 = self.flat2(n1)
- nt2 = self.flat2(n1)
- n1_down = self.downsample(nt1)
- n2_down = self.downsample(nt2)
- n1_2 = nn.Sigmoid()(self.relu(self.gn_128(self.conv__3(F.interpolate(n1_down, nt1.size()[2:], mode="bilinear", align_corners=False)+ nt1))))
- n2_2 = nn.Sigmoid()(self.relu(self.gn_128(self.conv__3(F.interpolate(n2_down, nt2.size()[2:], mode="bilinear", align_corners=False)+ nt2))))
-
- np1 = n2.mul(F.interpolate(n1_2, n1.size()[2:], mode="bilinear", align_corners=False))
- np2 = n1.mul(F.interpolate(n2_2, n2.size()[2:], mode="bilinear", align_corners=False))
- n2 = (self.relu(self.gn_128(self.conv__3(np2+ n2))))
- n1 = (self.relu(self.gn_128(self.conv__3(np1+ n1))))
- output = torch.cat([n1, n2], dim=1)
- output = F.interpolate(output, x.size()[2:], mode="bilinear", align_corners=False)
- output = self.classifier(output)
-
- return output
-
- class ei_Net_Resnet50_base(nn.Module):
- def __init__(self):
- super(ei_Net_Resnet50_base, self).__init__()
-
- self.convnext_backbone = convnext_base(pretrained=True)
-
- self.upsample_2 = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True)
-
- self.constrain_conv = BayarConv2d(in_channels=1, out_channels=3, padding=2)
-
- self.srm_conv1 = SRMConv2d_Separate(128, 128)
- self.srm_conv2 = SRMConv2d_Separate(256, 256)
- self.srm_conv3 = SRMConv2d_Separate(512, 512)
- self.srm_conv4 = SRMConv2d_Separate(1024, 1024)
-
- self.LFS_head1 = LFS_Head(80, 10, 8)
- self.LFS_head2 = LFS_Head(40, 10, 8)
- self.LFS_head3 = LFS_Head(20, 10, 8)
- self.LFS_head4 = LFS_Head(10, 10, 8)
-
- self.convqq1 = nn.Conv2d(128, 32, 3, 1, 1)
- self.convqq2 = nn.Conv2d(256, 32, 3, 1, 1)
- self.convqq3 = nn.Conv2d(512, 32, 3, 1, 1)
- self.convqq4 = nn.Conv2d(1024, 32, 3, 1, 1)
-
- self.convlow = nn.Conv2d(1, 32, 3, 1, 1)
- self.convhigh = nn.Conv2d(7, 32, 3, 1, 1)
-
- self.conv1 = nn.Conv2d(128+32, 32, 3, 1, 1)
- self.gn1 = nn.GroupNorm(32, 32)
- self.conv2 = nn.Conv2d(256+32+32, 32, 3, 1, 1)
- self.gn2 = nn.GroupNorm(32, 32)
- self.conv3 = nn.Conv2d(512+32+32, 32, 3, 1, 1)
- self.gn3 = nn.GroupNorm(32, 32)
- self.conv4 = nn.Conv2d(1024+32+32, 256, 3, 1, 1)
- self.gn4 = nn.GroupNorm(256, 256)
- self.relu = nn.ReLU(True)
-
- self.conv_32 = nn.Conv2d(32, 32, 3, 1, 1)
- self.gn = nn.GroupNorm(32, 32)
-
- self.conv_r1 = nn.Conv2d(128+32, 32, 3, 1, 1)
- self.conv_r2 = nn.Conv2d(256+32+32, 32, 3, 1, 1)
- self.conv_r3 = nn.Conv2d(512+32+32, 32, 3, 1, 1)
- self.conv_r4 = nn.Conv2d(1024+32+32, 256, 3, 1, 1)
- self.gn4 = nn.GroupNorm(256, 256)
- self.relu = nn.ReLU(True)
-
- self.conv1_2 = nn.Conv2d(128, 256, 3, 1, 1)
- self.conv2_3 = nn.Conv2d(256, 512, 3, 1, 1)
- self.conv3_4 = nn.Conv2d(512, 1024, 3, 1, 1)
-
- #self.down = nn.Conv2d(768*2, 256, 3, 1, 1)
-
- self.flat1 = nn.Conv2d(256, 128, kernel_size=1)
- self.flat2 = nn.Conv2d(128, 128, kernel_size=2)
-
- self.downsample = nn.AvgPool2d((2, 2), stride=2)
-
- self.conv__3 = nn.Conv2d(128, 128, 3, 1, 1)
- self.gn_128 = nn.GroupNorm(128, 128)
-
- self.classifier = nn.Conv2d(256, 1, 1)
-
- def forward(self, x):
-
- x1, x2, x3, x4 = self.convnext_backbone(x)
-
- s1 = self.srm_conv1(x1)
- s2 = self.srm_conv2(x2)
- s3 = self.srm_conv3(x3)
- s4 = self.srm_conv4(x4)
-
- l1 = self.LFS_head1(self.relu(self.gn(self.convqq1(x1))))
- l2 = self.LFS_head2(self.relu(self.gn(self.convqq2(x2))))
- l3 = self.LFS_head3(self.relu(self.gn(self.convqq3(x3))))
- l4 = self.LFS_head4(self.relu(self.gn(self.convqq4(x4))))
-
- #print(l1.shape)
-
- list_of_l1 = torch.split(l1, [1,7], dim=1)
- list_of_l2 = torch.split(l2, [1,7], dim=1)
- list_of_l3 = torch.split(l3, [1,7], dim=1)
- list_of_l4 = torch.split(l4, [1,7], dim=1)
-
- low_l1 = list_of_l1[0]
- high_l1 = list_of_l1[1]
- low_l1 = self.relu(self.gn(self.convlow(low_l1)))
- high_l1 = self.relu(self.gn(self.convhigh(high_l1)))
- low_l1 = F.interpolate(low_l1, x1.size()[2:], mode="bilinear", align_corners=False)
- high_l1 = F.interpolate(high_l1, s1.size()[2:], mode="bilinear", align_corners=False)
- #print(low_l1.shape, high_l1.shape)
-
- low_l2 = list_of_l2[0]
- high_l2 = list_of_l2[1]
- low_l2 = self.relu(self.gn(self.convlow(low_l2)))
- high_l2 = self.relu(self.gn(self.convhigh(high_l2)))
- low_l2 = F.interpolate(low_l2, x2.size()[2:], mode="bilinear", align_corners=False)
- high_l2 = F.interpolate(high_l2, s2.size()[2:], mode="bilinear", align_corners=False)
- #print(low_l2.shape, high_l2.shape)
-
- low_l3 = list_of_l3[0]
- high_l3 = list_of_l3[1]
- low_l3 = self.relu(self.gn(self.convlow(low_l3)))
- high_l3 = self.relu(self.gn(self.convhigh(high_l3)))
- low_l3 = F.interpolate(low_l3, x3.size()[2:], mode="bilinear", align_corners=False)
- high_l3 = F.interpolate(high_l3, s3.size()[2:], mode="bilinear", align_corners=False)
- #print(low_l3.shape, high_l3.shape)
-
- low_l4 = list_of_l4[0]
- high_l4 = list_of_l4[1]
- low_l4 = self.relu(self.gn(self.convlow(low_l4)))
- high_l4 = self.relu(self.gn(self.convhigh(high_l4)))
- low_l4 = F.interpolate(low_l4, x4.size()[2:], mode="bilinear", align_corners=False)
- high_l4 = F.interpolate(high_l4, s4.size()[2:], mode="bilinear", align_corners=False)
- #print(low_l4.shape, high_l4.shape)
-
- n1_cat = torch.cat([s1, high_l1], dim=1)
- n1_cat = self.relu(self.gn1(self.conv1(n1_cat)))
- n1_cat = F.interpolate(n1_cat, s2.size()[2:], mode="bilinear", align_corners=False)
- n1_cat = self.relu(self.gn(self.conv_32(n1_cat)))
-
- n2_cat = torch.cat([s2, high_l2, n1_cat], dim=1)
- n2_cat = self.relu(self.gn2(self.conv2(n2_cat)))
- n2_cat = F.interpolate(n2_cat, s3.size()[2:], mode="bilinear", align_corners=False)
- n2_cat = self.relu(self.gn(self.conv_32(n2_cat)))
-
- n3_cat = torch.cat([s3, high_l3, n2_cat], dim=1)
- n3_cat = self.relu(self.gn3(self.conv3(n3_cat)))
- n3_cat = F.interpolate(n3_cat, s4.size()[2:], mode="bilinear", align_corners=False)
- n3_cat = self.relu(self.gn(self.conv_32(n3_cat)))
-
- n4_cat = torch.cat([s4, high_l4, n3_cat], dim=1)
- n4_cat = self.relu(self.gn4(self.conv4(n4_cat)))
- #print(n4_cat.shape)
-
- r1_cat = torch.cat([x1, low_l1], dim=1)
- r1_cat = self.relu(self.gn1(self.conv_r1(r1_cat)))
- r1_cat = F.interpolate(r1_cat, x2.size()[2:], mode="bilinear", align_corners=False)
- r1_cat = self.relu(self.gn(self.conv_32(r1_cat)))
- #print(r1_cat.shape)
-
- r2_cat = torch.cat([x2, low_l2, r1_cat], dim=1)
- r2_cat = self.relu(self.gn2(self.conv_r2(r2_cat)))
- r2_cat = F.interpolate(r2_cat, x3.size()[2:], mode="bilinear", align_corners=False)
- r2_cat = self.relu(self.gn(self.conv_32(r2_cat)))
- #print(r2_cat.shape)
-
- r3_cat = torch.cat([x3, low_l3, r2_cat], dim=1)
- r3_cat = self.relu(self.gn3(self.conv_r3(r3_cat)))
- r3_cat = F.interpolate(r3_cat, x4.size()[2:], mode="bilinear", align_corners=False)
- r3_cat = self.relu(self.gn(self.conv_32(r3_cat)))
- #print(r3_cat.shape)
-
- r4_cat = torch.cat([x4, low_l4, r3_cat], dim=1)
- r4_cat = self.relu(self.gn4(self.conv_r4(r4_cat)))
- #print(r4_cat.shape)
-
- n1 = self.flat1(n4_cat)
- n2 = self.flat1(r4_cat)
- nt1 = self.flat2(n1)
- nt2 = self.flat2(n1)
- n1_down = self.downsample(nt1)
- n2_down = self.downsample(nt2)
- n1_2 = nn.Sigmoid()(self.relu(self.gn_128(self.conv__3(F.interpolate(n1_down, nt1.size()[2:], mode="bilinear", align_corners=False)+ nt1))))
- n2_2 = nn.Sigmoid()(self.relu(self.gn_128(self.conv__3(F.interpolate(n2_down, nt2.size()[2:], mode="bilinear", align_corners=False)+ nt2))))
-
- np1 = n2.mul(F.interpolate(n1_2, n1.size()[2:], mode="bilinear", align_corners=False))
- np2 = n1.mul(F.interpolate(n2_2, n2.size()[2:], mode="bilinear", align_corners=False))
- n2 = (self.relu(self.gn_128(self.conv__3(np2+ n2))))
- n1 = (self.relu(self.gn_128(self.conv__3(np1+ n1))))
- output = torch.cat([n1, n2], dim=1)
- output = F.interpolate(output, x.size()[2:], mode="bilinear", align_corners=False)
- output = self.classifier(output)
-
- return output
-
- if __name__ == "__main__":
-
- x = torch.randn(1,3,320,320)
- net = ei_Net_Resnet50()
- #net = ei_Net_Resnet50_base()
- output = net(x)
- print(output.shape)
- print(sum([x.nelement() for x in net.parameters()]))
- print('Total params: %.2fM' % (sum(p.numel() for p in net.parameters())/1000000.0))
|