import time import math from functools import partial import numpy as np import torch…
Jump to turn (6)
- User
import time import math from functools import partial import numpy as np import torch import copy import torch.nn as nn import torch.nn.functional as F
class LDC(nn.Module): def init(self, in_channels, out_channels, kernel_size=3, stride=1, padding=1, dilation=1, groups=1, bias=False): # conv.weight.size() = [out_channels, in_channels, kernel_size, kernel_size] super(LDC, self).init() self.conv = nn.Conv2d(in_channels, out_channels, kernel_size=kernel_size, stride=stride, padding=padding, dilation=dilation, groups=groups, bias=bias) # [12,3,3,3]
self.center_mask = torch.tensor([[0, 0, 0],
[0, 1, 0],
[0, 0, 0]]).cuda()
self.base_mask = nn.Parameter(torch.ones(self.conv.weight.size()), requires_grad=False) # [12,3,3,3]
self.learnable_mask = nn.Parameter(torch.ones([self.conv.weight.size(0), self.conv.weight.size(1)]),
requires_grad=True) # [12,3]
self.learnable_theta = nn.Parameter(torch.ones(1) * 0.5, requires_grad=True) # [1]
# print(self.learnable_mask[:, :, None, None].shape)
def forward(self, x):
mask = self.base_mask - self.learnable_theta * self.learnable_mask[:, :, None, None] * \
self.center_mask * self.conv.weight.sum(2).sum(2)[:, :, None, None]
out_diff = F.conv2d(input=x, weight=self.conv.weight * mask, bias=self.conv.bias, stride=self.conv.stride,
padding=self.conv.padding,
groups=self.conv.groups)
return out_diff
class Differential_enhance(nn.Module): def init(self, nf=48): super(Differential_enhance, self).init()
self.global_avgpool = nn.AdaptiveAvgPool2d(1)
self.act = nn.Sigmoid()
self.lastconv = nn.Conv2d(nf,nf//2,1,1)
def forward(self, fuse, x1, x2):
b,c,h,w = x1.shape
sub_1_2 = x1 - x2
sub_w_1_2 = self.global_avgpool(sub_1_2)
w_1_2 = self.act(sub_w_1_2)
sub_2_1 = x2 - x1
sub_w_2_1 = self.global_avgpool(sub_2_1)
w_2_1 = self.act(sub_w_2_1)
D_F1 = torch.multiply(w_1_2, fuse)
D_F2 = torch.multiply(w_2_1, fuse)
F_1 = torch.add(D_F1, other=x1, alpha=1)
F_2 = torch.add(D_F2, other=x2, alpha=1)
return F_1, F_2
class Enhancement_texture_LDC(nn.Module): def init(self, in_channels, out_channels, kernel_size=3, stride=1, padding=1, dilation=1, groups=1, bias=False): # conv.weight.size() = [out_channels, in_channels, kernel_size, kernel_size] super(Enhancement_texture_LDC, self).init() self.conv = nn.Conv2d(in_channels, out_channels, kernel_size=kernel_size, stride=stride, padding=padding, dilation=dilation, groups=groups, bias=bias) # [12,3,3,3]
self.center_mask = torch.tensor([[0, 0, 0],
[0, 1, 0],
[0, 0, 0]]).cuda()
self.base_mask = nn.Parameter(torch.ones(self.conv.weight.size()), requires_grad=False) # [12,3,3,3]
self.learnable_mask = nn.Parameter(torch.ones([self.conv.weight.size(0), self.conv.weight.size(1)]),
requires_grad=True) # [12,3]
self.learnable_theta = nn.Parameter(torch.ones(1) * 0.5, requires_grad=True) # [1]
# print(self.learnable_mask[:, :, None, None].shape)
def forward(self, x):
mask = self.base_mask - self.learnable_theta * self.learnable_mask[:, :, None, None] * \
self.center_mask * self.conv.weight.sum(2).sum(2)[:, :, None, None]
out_diff = F.conv2d(input=x, weight=self.conv.weight * mask, bias=self.conv.bias, stride=self.conv.stride,
padding=self.conv.padding,
groups=self.conv.groups)
return out_diff
class DFEM(nn.Module): def init( self, hidden_dim: int = 0 ): super().init() self.d_model = hidden_dim self.texture_enhance1 = Enhancement_texture_LDC(self.d_model,self.d_model) self.texture_enhance2 = Enhancement_texture_LDC(self.d_model, self.d_model) self.Diff_enhance = Differential_enhance(self.d_model)
def forward(self, Fuse, x1,x2):
TX_x1 = self.texture_enhance1(x1)
TX_x2 = self.texture_enhance2(x2)
DF_x1, DF_x2 = self.Diff_enhance(Fuse, x1,x2)
F_1 = TX_x1 +DF_x1
F_2 = TX_x2 +DF_x2
return F_1, F_2
解读
This code defines several PyTorch neural network modules aimed at achieving feature enhancement using a concept called Local Differential Consistency (LDC) and the enhancement of texture information. Here's a breakdown of the main components:
LDC (Local Differential Consistency) Module:
nn.Module.nn.Conv2d).learnable_mask) and a learnable parameter (learnable_theta), which can adjust the behavior of the convolution kernel.forward() defines how inputs pass through the module. A mask is created and applied to the convolutional weights. This mask seems to reduce the influence of the central pixel based on learnable_theta and learnable_mask.F.conv2d() operation to produce the output.Differential Enhance Module:
x1 and x2.F_1 and F_2, that add these weighted differences to the original input tensors.Enhancement Texture using LDC:
DFEM (Differential Feature Enhancement Module):
Enhancement_texture_LDC and Differential_enhance classes.F_1 and F_2.Overall, the code appears to be focused on enhancing features in a neural network architecture by manipulating the local consistency and texture of input feature maps. The learnable masks and differential weights suggest a focus on adaptively adjusting the model to emphasize certain feature characteristics more heavily. If applied within a broader network, these modules would likely aim to improve the quality of learned feature representations, potentially useful in tasks like image enhancement or object recognition where feature distinction is crucial.
中午
你好!有什么我可以帮助你的吗?
写错了,是中文回答
明白了!如果你需要任何帮助或者有任何问题,请随时告诉我。
回答最开始的问题,中文回答
这段代码使用PyTorch定义了一些神经网络模块,主要目的是通过局部差分一致性(Local Differential Consistency, LDC)和纹理信息增强来提升特征的表现能力。以下是对主要组成部分的解释:
LDC(局部差分一致性)模块:
nn.Module。nn.Conv2d)。learnable_mask)和一个可学习的参数(learnable_theta),用于调整卷积核的行为。forward()方法定义了输入如何通过这个模块处理。通过创建一个掩码来应用于卷积权重,这个掩码会根据learnable_theta和learnable_mask来减弱中心像素的影响。F.conv2d()进行卷积运算得到输出。差分增强模块(Differential Enhance Module):
x1和x2之间差异的权重。F_1和F_2,它们通过将这些带权差异与原始输入张量相加得到。纹理增强LDC(Enhancement Texture using LDC):
DFEM(差分特征增强模块):
Enhancement_texture_LDC和Differential_enhance类的功能。F_1和F_2。总体来说,这段代码专注于在神经网络架构中增强特征表现,通过操控输入特征图的局部一致性和纹理信息。可学习的掩码和差异权重表明,该模型可以自适应地调整,以在某些特征特性上更加强调。这些模块如果在更大的网络中使用,可能用于提升特征表示的质量,这在图像增强或物体识别等需要高特征辨识度的任务中非常有用。
分析:import time import math from functools import partial import numpy as np import torch import copy import torch.nn as nn import torch.nn.functional as F from typing import Callable, Any from timm.models.layers import DropPath import torch.utils.checkpoint as checkpoint from einops import rearrange, repeat
try: from mamba_ssm.ops.selective_scan_interface import selective_scan_fn, selective_scan_ref except: pass
try: from .selective_scan import selective_scan_fn as selective_scan_fn_v1 from .selective_scan import selective_scan_ref as selective_scan_ref_v1 except: pass
class LDC(nn.Module): def init(self, in_channels, out_channels, kernel_size=3, stride=1, padding=1, dilation=1, groups=1, bias=False): # conv.weight.size() = [out_channels, in_channels, kernel_size, kernel_size] super(LDC, self).init() self.conv = nn.Conv2d(in_channels, out_channels, kernel_size=kernel_size, stride=stride, padding=padding, dilation=dilation, groups=groups, bias=bias) # [12,3,3,3]
self.center_mask = torch.tensor([[0, 0, 0],
[0, 1, 0],
[0, 0, 0]]).cuda()
self.base_mask = nn.Parameter(torch.ones(self.conv.weight.size()), requires_grad=False) # [12,3,3,3]
self.learnable_mask = nn.Parameter(torch.ones([self.conv.weight.size(0), self.conv.weight.size(1)]),
requires_grad=True) # [12,3]
self.learnable_theta = nn.Parameter(torch.ones(1) * 0.5, requires_grad=True) # [1]
# print(self.learnable_mask[:, :, None, None].shape)
def forward(self, x):
mask = self.base_mask - self.learnable_theta * self.learnable_mask[:, :, None, None] * \
self.center_mask * self.conv.weight.sum(2).sum(2)[:, :, None, None]
out_diff = F.conv2d(input=x, weight=self.conv.weight * mask, bias=self.conv.bias, stride=self.conv.stride,
padding=self.conv.padding,
groups=self.conv.groups)
return out_diff
这个Python代码定义了多个神经网络模块,旨在进行深度学习中的特征增强和自注意力机制的应用。以下是对这些关键模块的分析:
LDC(局部差分一致性)模块:
learnable_mask)来调节卷积核的中心像素影响。learnable_theta),这些参数调整卷积的权重以实现局部特征增强。eca_layer模块:
BiAttn模块:
LayerNorm和Linear层进行全局特征压缩和选择,可提升模型捕获全局信息的能力。Mlp模块:
SS2D模块:
Linear层进行状态和特征转换。VSSBlock_new模块:
eca_layer和BiAttn)和卷积特征提取(使用LDC)。selective_scan),支持特征的局部和全局交互。总体来看,这段代码构建了一个复杂的网络结构,通过结合卷积运算、有效注意力机制和多层感知机(MLP),提升了特征的鲁棒性和自适应性。此类网络架构适用于需要细致特征增强和注意力机制的任务,可能用于图像分类、目标检测等深度学习应用中。代码结构支持模块化设计,可以应用于不同的神经网络架构以增强模型的表现力。
他的调用如下:import math from functools import partial from typing import Callable
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import torch.utils.checkpoint as checkpoint from einops import rearrange, repeat from timm.models.layers import DropPath, trunc_normal_
from models.cross import VSSBlock_Cross_new from models.cross import VSSBlock_new
try: from mamba_ssm.ops.selective_scan_interface import selective_scan_fn, selective_scan_ref except: pass
try: from selective_scan import selective_scan_fn as selective_scan_fn_v1 from selective_scan import selective_scan_ref as selective_scan_ref_v1 except: pass
DropPath.repr = lambda self: f"timm.DropPath({self.drop_prob})"
def flops_selective_scan_ref(B=1, L=256, D=768, N=16, with_D=True, with_Z=False, with_Group=True, with_complex=False): """ u: r(B D L) delta: r(B D L) A: r(D N) B: r(B N L) C: r(B N L) D: r(D) z: r(B D L) delta_bias: r(D), fp32
This Python script defines a multi-module neural network architecture built using PyTorch. The focus of the architecture appears to be on feature extraction and fusion, leveraging various attention mechanisms and convolutional layers. Below is an analysis of the main components and their respective functions:
Patch Embedding and Merging:
Conv2d layers.Convolutional and Attention Layers:
Attention-Based Fusion and Processing:
Fusion and Final Output:
Fusion_network method performs cross-block fusion, integrating features from different skip connections.forward_final transforms the fused features into the desired output shape.class eca_layer(nn.Module):
def __init__(self, channel, k_size=3):
super(eca_layer, self).__init__()
self.avg_pool = nn.AdaptiveAvgPool2d(1)
self.conv = nn.Conv1d(1, 1, kernel_size=k_size, padding=(k_size - 1) // 2, bias=False)
self.sigmoid = nn.Sigmoid()
def forward(self, x):
# feature descriptor on the global spatial information
y = self.avg_pool(x)
# Two different branches of ECA module
y = self.conv(y.squeeze(-1).transpose(-1, -2)).transpose(-1, -2).unsqueeze(-1)
# Multi-scale information fusion
y = self.sigmoid(y)
return x * y.expand_as(x)
class BiAttn(nn.Module): def init(self, in_channels, act_ratio=0.125, act_fn=nn.GELU, gate_fn=nn.Sigmoid): super().init() reduce_channels = int(in_channels * act_ratio) self.norm = nn.LayerNorm(in_channels) self.global_reduce = nn.Linear(in_channels, reduce_channels) # self.local_reduce = nn.Linear(in_channels, reduce_channels) self.act_fn = act_fn() self.channel_select = nn.Linear(reduce_channels, in_channels) # self.spatial_select = nn.Linear(reduce_channels * 2, 1) self.gate_fn = gate_fn()
def forward(self, x):
ori_x = x
x = self.norm(x)
x_global = x.mean([1, 2], keepdim=True)
x_global = self.act_fn(self.global_reduce(x_global))
# x_local = self.act_fn(self.local_reduce(x))
c_attn = self.channel_select(x_global)
c_attn = self.gate_fn(c_attn)
attn = c_attn
out = ori_x * attn
return out
class Mlp(nn.Module): def init(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.,channels_first=False): super().init() out_features = out_features or in_features hidden_features = hidden_features or in_features
Linear = partial(nn.Conv2d, kernel_size=1, padding=0) if channels_first else nn.Linear
self.fc1 = Linear(in_features, hidden_features)
self.act = act_layer()
self.fc2 = Linear(hidden_features, out_features)
self.drop = nn.Dropout(drop)
def forward(self, x):
x = self.fc1(x)
x = self.act(x)
x = self.drop(x)
x = self.fc2(x)
x = self.drop(x)
return x
class SS2D(nn.Module): def init( self, d_model, d_state=16, # d_state="auto", # 20240109 d_conv=3, expand=2, dt_rank="auto", dt_min=0.001, dt_max=0.1, dt_init="random", dt_scale=1.0, dt_init_floor=1e-4, dropout=0., conv_bias=True, bias=False, device=None, dtype=None, **kwargs, ): factory_kwargs = {"device": device, "dtype": dtype} super().init() self.d_model = d_model self.d_state = d_state # self.d_state = math.ceil(self.d_model / 6) if d_state == "auto" else d_model # 20240109 self.d_conv = d_conv self.expand = expand self.d_inner = int(self.expand * self.d_model) self.dt_rank = math.ceil(self.d_model / 16) if dt_rank == "auto" else dt_rank
self.in_proj = nn.Linear(self.d_model, self.d_inner * 2, bias=bias, **factory_kwargs)
self.conv2d = nn.Conv2d(
in_channels=self.d_inner,
out_channels=self.d_inner,
groups=self.d_inner,
bias=conv_bias,
kernel_size=d_conv,
padding=(d_conv - 1) // 2,
**factory_kwargs,
)
self.act = nn.SiLU()
self.x_proj = (
nn.Linear(self.d_inner, (self.dt_rank + self.d_state * 2), bias=False, **factory_kwargs),
nn.Linear(self.d_inner, (self.dt_rank + self.d_state * 2), bias=False, **factory_kwargs),
nn.Linear(self.d_inner, (self.dt_rank + self.d_state * 2), bias=False, **factory_kwargs),
nn.Linear(self.d_inner, (self.dt_rank + self.d_state * 2), bias=False, **factory_kwargs),
)
self.x_proj_weight = nn.Parameter(torch.stack([t.weight for t in self.x_proj], dim=0)) # (K=4, N, inner)
del self.x_proj
self.dt_projs = (
self.dt_init(self.dt_rank, self.d_inner, dt_scale, dt_init, dt_min, dt_max, dt_init_floor,
**factory_kwargs),
self.dt_init(self.dt_rank, self.d_inner, dt_scale, dt_init, dt_min, dt_max, dt_init_floor,
**factory_kwargs),
self.dt_init(self.dt_rank, self.d_inner, dt_scale, dt_init, dt_min, dt_max, dt_init_floor,
**factory_kwargs),
self.dt_init(self.dt_rank, self.d_inner, dt_scale, dt_init, dt_min, dt_max, dt_init_floor,
**factory_kwargs),
)
self.dt_projs_weight = nn.Parameter(torch.stack([t.weight for t in self.dt_projs], dim=0)) # (K=4, inner, rank)
self.dt_projs_bias = nn.Parameter(torch.stack([t.bias for t in self.dt_projs], dim=0)) # (K=4, inner)
del self.dt_projs
self.A_logs = self.A_log_init(self.d_state, self.d_inner, copies=4, merge=True) # (K=4, D, N)
self.Ds = self.D_init(self.d_inner, copies=4, merge=True) # (K=4, D, N)
# self.selective_scan = selective_scan_fn
self.forward_core = self.forward_corev0
self.out_norm = nn.LayerNorm(self.d_inner)
self.out_proj = nn.Linear(self.d_inner, self.d_model, bias=bias, **factory_kwargs)
self.dropout = nn.Dropout(dropout) if dropout > 0. else None
@staticmethod
def dt_init(dt_rank, d_inner, dt_scale=1.0, dt_init="random", dt_min=0.001, dt_max=0.1, dt_init_floor=1e-4,
**factory_kwargs):
dt_proj = nn.Linear(dt_rank, d_inner, bias=True, **factory_kwargs)
# Initialize special dt projection to preserve variance at initialization
dt_init_std = dt_rank ** -0.5 * dt_scale
if dt_init == "constant":
nn.init.constant_(dt_proj.weight, dt_init_std)
elif dt_init == "random":
nn.init.uniform_(dt_proj.weight, -dt_init_std, dt_init_std)
else:
raise NotImplementedError
# Initialize dt bias so that F.softplus(dt_bias) is between dt_min and dt_max
dt = torch.exp(
torch.rand(d_inner, **factory_kwargs) * (math.log(dt_max) - math.log(dt_min))
+ math.log(dt_min)
).clamp(min=dt_init_floor)
# Inverse of softplus: https://github.com/pytorch/pytorch/issues/72759
inv_dt = dt + torch.log(-torch.expm1(-dt))
with torch.no_grad():
dt_proj.bias.copy_(inv_dt)
# Our initialization would set all Linear.bias to zero, need to mark this one as _no_reinit
dt_proj.bias._no_reinit = True
return dt_proj
@staticmethod
def A_log_init(d_state, d_inner, copies=1, device=None, merge=True):
# S4D real initialization
A = repeat(
torch.arange(1, d_state + 1, dtype=torch.float32, device=device),
"n -> d n",
d=d_inner,
).contiguous()
A_log = torch.log(A) # Keep A_log in fp32
if copies > 1:
A_log = repeat(A_log, "d n -> r d n", r=copies)
if merge:
A_log = A_log.flatten(0, 1)
A_log = nn.Parameter(A_log)
A_log._no_weight_decay = True
return A_log
@staticmethod
def D_init(d_inner, copies=1, device=None, merge=True):
# D "skip" parameter
D = torch.ones(d_inner, device=device)
if copies > 1:
D = repeat(D, "n1 -> r n1", r=copies)
if merge:
D = D.flatten(0, 1)
D = nn.Parameter(D) # Keep in fp32
D._no_weight_decay = True
return D
def forward_corev0(self, x: torch.Tensor):
self.selective_scan = selective_scan_fn
B, C, H, W = x.shape
L = H * W
K = 4
x_hwwh = torch.stack([x.view(B, -1, L), torch.transpose(x, dim0=2, dim1=3).contiguous().view(B, -1, L)],
dim=1).view(B, 2, -1, L)
xs = torch.cat([x_hwwh, torch.flip(x_hwwh, dims=[-1])], dim=1) # (b, k, d, l)
x_dbl = torch.einsum("b k d l, k c d -> b k c l", xs.view(B, K, -1, L), self.x_proj_weight)
# x_dbl = x_dbl + self.x_proj_bias.view(1, K, -1, 1)
dts, Bs, Cs = torch.split(x_dbl, [self.dt_rank, self.d_state, self.d_state], dim=2)
dts = torch.einsum("b k r l, k d r -> b k d l", dts.view(B, K, -1, L), self.dt_projs_weight)
# dts = dts + self.dt_projs_bias.view(1, K, -1, 1)
xs = xs.float().view(B, -1, L) # (b, k * d, l)
dts = dts.contiguous().float().view(B, -1, L) # (b, k * d, l)
Bs = Bs.float().view(B, K, -1, L) # (b, k, d_state, l)
Cs = Cs.float().view(B, K, -1, L) # (b, k, d_state, l)
Ds = self.Ds.float().view(-1) # (k * d)
As = -torch.exp(self.A_logs.float()).view(-1, self.d_state) # (k * d, d_state)
dt_projs_bias = self.dt_projs_bias.float().view(-1) # (k * d)
out_y = self.selective_scan(
xs, dts,
As, Bs, Cs, Ds, z=None,
delta_bias=dt_projs_bias,
delta_softplus=True,
return_last_state=False,
).view(B, K, -1, L)
assert out_y.dtype == torch.float
inv_y = torch.flip(out_y[:, 2:4], dims=[-1]).view(B, 2, -1, L)
wh_y = torch.transpose(out_y[:, 1].view(B, -1, W, H), dim0=2, dim1=3).contiguous().view(B, -1, L)
invwh_y = torch.transpose(inv_y[:, 1].view(B, -1, W, H), dim0=2, dim1=3).contiguous().view(B, -1, L)
return out_y[:, 0], inv_y[:, 0], wh_y, invwh_y
# an alternative to forward_corev1
def forward_corev1(self, x: torch.Tensor):
self.selective_scan = selective_scan_fn_v1
B, C, H, W = x.shape
L = H * W
K = 4
x_hwwh = torch.stack([x.view(B, -1, L), torch.transpose(x, dim0=2, dim1=3).contiguous().view(B, -1, L)],
dim=1).view(B, 2, -1, L)
xs = torch.cat([x_hwwh, torch.flip(x_hwwh, dims=[-1])], dim=1) # (b, k, d, l)
x_dbl = torch.einsum("b k d l, k c d -> b k c l", xs.view(B, K, -1, L), self.x_proj_weight)
# x_dbl = x_dbl + self.x_proj_bias.view(1, K, -1, 1)
dts, Bs, Cs = torch.split(x_dbl, [self.dt_rank, self.d_state, self.d_state], dim=2)
dts = torch.einsum("b k r l, k d r -> b k d l", dts.view(B, K, -1, L), self.dt_projs_weight)
# dts = dts + self.dt_projs_bias.view(1, K, -1, 1)
xs = xs.float().view(B, -1, L) # (b, k * d, l)
dts = dts.contiguous().float().view(B, -1, L) # (b, k * d, l)
Bs = Bs.float().view(B, K, -1, L) # (b, k, d_state, l)
Cs = Cs.float().view(B, K, -1, L) # (b, k, d_state, l)
Ds = self.Ds.float().view(-1) # (k * d)
As = -torch.exp(self.A_logs.float()).view(-1, self.d_state) # (k * d, d_state)
dt_projs_bias = self.dt_projs_bias.float().view(-1) # (k * d)
out_y = self.selective_scan(
xs, dts,
As, Bs, Cs, Ds,
delta_bias=dt_projs_bias,
delta_softplus=True,
).view(B, K, -1, L)
assert out_y.dtype == torch.float
inv_y = torch.flip(out_y[:, 2:4], dims=[-1]).view(B, 2, -1, L)
wh_y = torch.transpose(out_y[:, 1].view(B, -1, W, H), dim0=2, dim1=3).contiguous().view(B, -1, L)
invwh_y = torch.transpose(inv_y[:, 1].view(B, -1, W, H), dim0=2, dim1=3).contiguous().view(B, -1, L)
return out_y[:, 0], inv_y[:, 0], wh_y, invwh_y
def forward(self, x: torch.Tensor, **kwargs):
B, H, W, C = x.shape
xz = self.in_proj(x)
x, z = xz.chunk(2, dim=-1) # (b, h, w, d)
x = x.permute(0, 3, 1, 2).contiguous()
x = self.act(self.conv2d(x)) # (b, d, h, w)
y1, y2, y3, y4 = self.forward_core(x)
assert y1.dtype == torch.float32
y = y1 + y2 + y3 + y4
y = torch.transpose(y, dim0=1, dim1=2).contiguous().view(B, H, W, -1)
y = self.out_norm(y)
y = y * F.silu(z)
out = self.out_proj(y)
if self.dropout is not None:
out = self.dropout(out)
return out
class VSSBlock_new(nn.Module): def init( self, hidden_dim: int = 0, drop_path: float = 0, norm_layer: Callable[..., torch.nn.Module] = partial(nn.LayerNorm, eps=1e-6), # ============================= ssm_d_state: int = 16, ssm_ratio=2.0, ssm_rank_ratio=2.0, ssm_dt_rank: Any = "auto", ssm_act_layer=nn.SiLU, ssm_conv: int = 3, ssm_conv_bias=True, ssm_drop_rate: float = 0, ssm_simple_init=False, forward_type="v2", # ============================= mlp_ratio=4.0, mlp_act_layer=nn.GELU, mlp_drop_rate: float = 0.0, # ============================= use_checkpoint: bool = False, step_size=2, **kwargs, ): super().init() self.use_checkpoint = use_checkpoint self.norm = norm_layer(hidden_dim) self.op = SS2D( d_model=hidden_dim, d_state=ssm_d_state, ssm_ratio=ssm_ratio, ssm_rank_ratio=ssm_rank_ratio, dt_rank=ssm_dt_rank, act_layer=ssm_act_layer, # ========================== d_conv=ssm_conv, conv_bias=ssm_conv_bias, # ========================== dropout=ssm_drop_rate, simple_init=ssm_simple_init, # ========================== forward_type=forward_type, step_size=step_size, )
self.conv_branch = LDC(hidden_dim,hidden_dim)
self.self_attention_cross_channel = eca_layer(channel=hidden_dim)
self.se = BiAttn(hidden_dim)
self.drop_path = DropPath(drop_path)
self.mlp_branch = mlp_ratio > 0
if self.mlp_branch:
self.norm2 = norm_layer(hidden_dim)
mlp_hidden_dim = int(hidden_dim * mlp_ratio)
self.mlp = Mlp(in_features=hidden_dim, hidden_features=mlp_hidden_dim, act_layer=mlp_act_layer,
drop=mlp_drop_rate, channels_first=False)
def _forward(self, input: torch.Tensor):
x = self.norm(input)
x_ssm = self.op(x)
x_ = x_ssm.permute(0, 3, 1, 2) # (b, c, h, w )
#######
x_ = self.self_attention_cross_channel(x_) # (b, c, h, w)
x_ = x_.permute(0, 2, 3, 1)
#####
x = x_ssm +x_
x_conv = self.conv_branch(x.permute(0, 3, 1, 2)).permute(0, 2, 3, 1)
x = self.se(x_ssm) + self.se(x_conv)
x = input + self.drop_path(x)
if self.mlp_branch:
x = x + self.drop_path(self.mlp(self.norm2(x))) # FFN
return x
def forward(self, input: torch.Tensor):
if self.use_checkpoint:
return checkpoint.checkpoint(self._forward, input)
else:
return self._forward(input)
ignores:
[.float(), +, .softplus, .shape, new_zeros, repeat, stack, to(dtype), silu]
"""
import numpy as np
# fvcore.nn.jit_handles
def get_flops_einsum(input_shapes, equation):
np_arrs = [np.zeros(s) for s in input_shapes]
optim = np.einsum_path(equation, *np_arrs, optimize="optimal")[1]
for line in optim.split("\n"):
if "optimized flop" in line.lower():
# divided by 2 because we count MAC (multiply-add counted as one flop)
flop = float(np.floor(float(line.split(":")[-1]) / 2))
return flop
assert not with_complex
flops = 0 # below code flops = 0
if False:
...
"""
dtype_in = u.dtype
u = u.float()
delta = delta.float()
if delta_bias is not None:
delta = delta + delta_bias[..., None].float()
if delta_softplus:
delta = F.softplus(delta)
batch, dim, dstate = u.shape[0], A.shape[0], A.shape[1]
is_variable_B = B.dim() >= 3
is_variable_C = C.dim() >= 3
if A.is_complex():
if is_variable_B:
B = torch.view_as_complex(rearrange(B.float(), "... (L two) -> ... L two", two=2))
if is_variable_C:
C = torch.view_as_complex(rearrange(C.float(), "... (L two) -> ... L two", two=2))
else:
B = B.float()
C = C.float()
x = A.new_zeros((batch, dim, dstate))
ys = []
"""
flops += get_flops_einsum([[B, D, L], [D, N]], "bdl,dn->bdln")
if with_Group:
flops += get_flops_einsum([[B, D, L], [B, N, L], [B, D, L]], "bdl,bnl,bdl->bdln")
else:
flops += get_flops_einsum([[B, D, L], [B, D, N, L], [B, D, L]], "bdl,bdnl,bdl->bdln")
if False:
...
"""
deltaA = torch.exp(torch.einsum('bdl,dn->bdln', delta, A))
if not is_variable_B:
deltaB_u = torch.einsum('bdl,dn,bdl->bdln', delta, B, u)
else:
if B.dim() == 3:
deltaB_u = torch.einsum('bdl,bnl,bdl->bdln', delta, B, u)
else:
B = repeat(B, "B G N L -> B (G H) N L", H=dim // B.shape[1])
deltaB_u = torch.einsum('bdl,bdnl,bdl->bdln', delta, B, u)
if is_variable_C and C.dim() == 4:
C = repeat(C, "B G N L -> B (G H) N L", H=dim // C.shape[1])
last_state = None
"""
in_for_flops = B * D * N
if with_Group:
in_for_flops += get_flops_einsum([[B, D, N], [B, D, N]], "bdn,bdn->bd")
else:
in_for_flops += get_flops_einsum([[B, D, N], [B, N]], "bdn,bn->bd")
flops += L * in_for_flops
if False:
...
"""
for i in range(u.shape[2]):
x = deltaA[:, :, i] * x + deltaB_u[:, :, i]
if not is_variable_C:
y = torch.einsum('bdn,dn->bd', x, C)
else:
if C.dim() == 3:
y = torch.einsum('bdn,bn->bd', x, C[:, :, i])
else:
y = torch.einsum('bdn,bdn->bd', x, C[:, :, :, i])
if i == u.shape[2] - 1:
last_state = x
if y.is_complex():
y = y.real * 2
ys.append(y)
y = torch.stack(ys, dim=2) # (batch dim L)
"""
if with_D:
flops += B * D * L
if with_Z:
flops += B * D * L
if False:
...
"""
out = y if D is None else y + u * rearrange(D, "d -> d 1")
if z is not None:
out = out * F.silu(z)
out = out.to(dtype=dtype_in)
"""
return flops
class PatchEmbed2D(nn.Module): r""" Image to Patch Embedding Args: patch_size (int): Patch token size. Default: 4. in_chans (int): Number of input image channels. Default: 3. embed_dim (int): Number of linear projection output channels. Default: 96. norm_layer (nn.Module, optional): Normalization layer. Default: None """
def __init__(self, patch_size=4, in_chans=1, embed_dim=96, norm_layer=None, **kwargs):
super().__init__()
if isinstance(patch_size, int):
patch_size = (patch_size, patch_size)
self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=patch_size)
if norm_layer is not None:
self.norm = norm_layer(embed_dim)
else:
self.norm = None
def forward(self, x):
x = self.proj(x).permute(0, 2, 3, 1)
if self.norm is not None:
x = self.norm(x)
return x
class PatchMerging2D(nn.Module): r""" Patch Merging Layer. Args: input_resolution (tuple[int]): Resolution of input feature. dim (int): Number of input channels. norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm """
def __init__(self, dim, norm_layer=nn.LayerNorm):
super().__init__()
self.dim = dim
self.reduction = nn.Linear(4 * dim, 2 * dim, bias=False)
self.norm = norm_layer(4 * dim)
def forward(self, x):
B, H, W, C = x.shape
SHAPE_FIX = [-1, -1]
if (W % 2 != 0) or (H % 2 != 0):
print(f"Warning, x.shape {x.shape} is not match even ===========", flush=True)
SHAPE_FIX[0] = H // 2
SHAPE_FIX[1] = W // 2
x0 = x[:, 0::2, 0::2, :] # B H/2 W/2 C
x1 = x[:, 1::2, 0::2, :] # B H/2 W/2 C
x2 = x[:, 0::2, 1::2, :] # B H/2 W/2 C
x3 = x[:, 1::2, 1::2, :] # B H/2 W/2 C
if SHAPE_FIX[0] > 0:
x0 = x0[:, :SHAPE_FIX[0], :SHAPE_FIX[1], :]
x1 = x1[:, :SHAPE_FIX[0], :SHAPE_FIX[1], :]
x2 = x2[:, :SHAPE_FIX[0], :SHAPE_FIX[1], :]
x3 = x3[:, :SHAPE_FIX[0], :SHAPE_FIX[1], :]
x = torch.cat([x0, x1, x2, x3], -1) # B H/2 W/2 4*C
x = x.view(B, H // 2, W // 2, 4 * C) # B H/2*W/2 4*C
x = self.norm(x)
x = self.reduction(x)
return x
class PatchExpand2D(nn.Module): def init(self, dim, dim_scale=2, norm_layer=nn.LayerNorm): super().init() self.dim = dim * 2 self.dim_scale = dim_scale self.expand = nn.Linear(self.dim, dim_scale * self.dim, bias=False) self.norm = norm_layer(self.dim // dim_scale)
def forward(self, x):
B, H, W, C = x.shape
x = self.expand(x)
x = rearrange(x, 'b h w (p1 p2 c)-> b (h p1) (w p2) c', p1=self.dim_scale, p2=self.dim_scale,
c=C // self.dim_scale)
x = self.norm(x)
return x
class Final_PatchExpand2D(nn.Module): def init(self, dim, dim_scale=4, norm_layer=nn.LayerNorm): super().init() self.dim = dim self.dim_scale = dim_scale self.expand = nn.Linear(self.dim, dim_scale * self.dim, bias=False) self.norm = norm_layer(self.dim // dim_scale)
def forward(self, x):
B, H, W, C = x.shape
x = self.expand(x)
x = rearrange(x, 'b h w (p1 p2 c)-> b (h p1) (w p2) c', p1=self.dim_scale, p2=self.dim_scale,
c=C // self.dim_scale)
x = self.norm(x)
return x
class SS2D(nn.Module): def init( self, d_model, d_state=16, # d_state="auto", # 20240109 d_conv=3, expand=2, dt_rank="auto", dt_min=0.001, dt_max=0.1, dt_init="random", dt_scale=1.0, dt_init_floor=1e-4, dropout=0., conv_bias=True, bias=False, device=None, dtype=None, **kwargs, ): factory_kwargs = {"device": device, "dtype": dtype} super().init() self.d_model = d_model self.d_state = d_state # self.d_state = math.ceil(self.d_model / 6) if d_state == "auto" else d_model # 20240109 self.d_conv = d_conv self.expand = expand self.d_inner = int(self.expand * self.d_model) self.dt_rank = math.ceil(self.d_model / 16) if dt_rank == "auto" else dt_rank
self.in_proj = nn.Linear(self.d_model, self.d_inner * 2, bias=bias, **factory_kwargs)
self.conv2d = nn.Conv2d(
in_channels=self.d_inner,
out_channels=self.d_inner,
groups=self.d_inner,
bias=conv_bias,
kernel_size=d_conv,
padding=(d_conv - 1) // 2,
**factory_kwargs,
)
self.act = nn.SiLU()
self.x_proj = (
nn.Linear(self.d_inner, (self.dt_rank + self.d_state * 2), bias=False, **factory_kwargs),
nn.Linear(self.d_inner, (self.dt_rank + self.d_state * 2), bias=False, **factory_kwargs),
nn.Linear(self.d_inner, (self.dt_rank + self.d_state * 2), bias=False, **factory_kwargs),
nn.Linear(self.d_inner, (self.dt_rank + self.d_state * 2), bias=False, **factory_kwargs),
)
self.x_proj_weight = nn.Parameter(torch.stack([t.weight for t in self.x_proj], dim=0)) # (K=4, N, inner)
del self.x_proj
self.dt_projs = (
self.dt_init(self.dt_rank, self.d_inner, dt_scale, dt_init, dt_min, dt_max, dt_init_floor,
**factory_kwargs),
self.dt_init(self.dt_rank, self.d_inner, dt_scale, dt_init, dt_min, dt_max, dt_init_floor,
**factory_kwargs),
self.dt_init(self.dt_rank, self.d_inner, dt_scale, dt_init, dt_min, dt_max, dt_init_floor,
**factory_kwargs),
self.dt_init(self.dt_rank, self.d_inner, dt_scale, dt_init, dt_min, dt_max, dt_init_floor,
**factory_kwargs),
)
self.dt_projs_weight = nn.Parameter(torch.stack([t.weight for t in self.dt_projs], dim=0)) # (K=4, inner, rank)
self.dt_projs_bias = nn.Parameter(torch.stack([t.bias for t in self.dt_projs], dim=0)) # (K=4, inner)
del self.dt_projs
self.A_logs = self.A_log_init(self.d_state, self.d_inner, copies=4, merge=True) # (K=4, D, N)
self.Ds = self.D_init(self.d_inner, copies=4, merge=True) # (K=4, D, N)
# self.selective_scan = selective_scan_fn
self.forward_core = self.forward_corev0
self.out_norm = nn.LayerNorm(self.d_inner)
self.out_proj = nn.Linear(self.d_inner, self.d_model, bias=bias, **factory_kwargs)
self.dropout = nn.Dropout(dropout) if dropout > 0. else None
@staticmethod
def dt_init(dt_rank, d_inner, dt_scale=1.0, dt_init="random", dt_min=0.001, dt_max=0.1, dt_init_floor=1e-4,
**factory_kwargs):
dt_proj = nn.Linear(dt_rank, d_inner, bias=True, **factory_kwargs)
# Initialize special dt projection to preserve variance at initialization
dt_init_std = dt_rank ** -0.5 * dt_scale
if dt_init == "constant":
nn.init.constant_(dt_proj.weight, dt_init_std)
elif dt_init == "random":
nn.init.uniform_(dt_proj.weight, -dt_init_std, dt_init_std)
else:
raise NotImplementedError
# Initialize dt bias so that F.softplus(dt_bias) is between dt_min and dt_max
dt = torch.exp(
torch.rand(d_inner, **factory_kwargs) * (math.log(dt_max) - math.log(dt_min))
+ math.log(dt_min)
).clamp(min=dt_init_floor)
# Inverse of softplus: https://github.com/pytorch/pytorch/issues/72759
inv_dt = dt + torch.log(-torch.expm1(-dt))
with torch.no_grad():
dt_proj.bias.copy_(inv_dt)
# Our initialization would set all Linear.bias to zero, need to mark this one as _no_reinit
dt_proj.bias._no_reinit = True
return dt_proj
@staticmethod
def A_log_init(d_state, d_inner, copies=1, device=None, merge=True):
# S4D real initialization
A = repeat(
torch.arange(1, d_state + 1, dtype=torch.float32, device=device),
"n -> d n",
d=d_inner,
).contiguous()
A_log = torch.log(A) # Keep A_log in fp32
if copies > 1:
A_log = repeat(A_log, "d n -> r d n", r=copies)
if merge:
A_log = A_log.flatten(0, 1)
A_log = nn.Parameter(A_log)
A_log._no_weight_decay = True
return A_log
@staticmethod
def D_init(d_inner, copies=1, device=None, merge=True):
# D "skip" parameter
D = torch.ones(d_inner, device=device)
if copies > 1:
D = repeat(D, "n1 -> r n1", r=copies)
if merge:
D = D.flatten(0, 1)
D = nn.Parameter(D) # Keep in fp32
D._no_weight_decay = True
return D
def forward_corev0(self, x: torch.Tensor):
self.selective_scan = selective_scan_fn
B, C, H, W = x.shape
L = H * W
K = 4
x_hwwh = torch.stack([x.view(B, -1, L), torch.transpose(x, dim0=2, dim1=3).contiguous().view(B, -1, L)],
dim=1).view(B, 2, -1, L)
xs = torch.cat([x_hwwh, torch.flip(x_hwwh, dims=[-1])], dim=1) # (b, k, d, l)
x_dbl = torch.einsum("b k d l, k c d -> b k c l", xs.view(B, K, -1, L), self.x_proj_weight)
# x_dbl = x_dbl + self.x_proj_bias.view(1, K, -1, 1)
dts, Bs, Cs = torch.split(x_dbl, [self.dt_rank, self.d_state, self.d_state], dim=2)
dts = torch.einsum("b k r l, k d r -> b k d l", dts.view(B, K, -1, L), self.dt_projs_weight)
# dts = dts + self.dt_projs_bias.view(1, K, -1, 1)
xs = xs.float().view(B, -1, L) # (b, k * d, l)
dts = dts.contiguous().float().view(B, -1, L) # (b, k * d, l)
Bs = Bs.float().view(B, K, -1, L) # (b, k, d_state, l)
Cs = Cs.float().view(B, K, -1, L) # (b, k, d_state, l)
Ds = self.Ds.float().view(-1) # (k * d)
As = -torch.exp(self.A_logs.float()).view(-1, self.d_state) # (k * d, d_state)
dt_projs_bias = self.dt_projs_bias.float().view(-1) # (k * d)
out_y = self.selective_scan(
xs, dts,
As, Bs, Cs, Ds, z=None,
delta_bias=dt_projs_bias,
delta_softplus=True,
return_last_state=False,
).view(B, K, -1, L)
assert out_y.dtype == torch.float
inv_y = torch.flip(out_y[:, 2:4], dims=[-1]).view(B, 2, -1, L)
wh_y = torch.transpose(out_y[:, 1].view(B, -1, W, H), dim0=2, dim1=3).contiguous().view(B, -1, L)
invwh_y = torch.transpose(inv_y[:, 1].view(B, -1, W, H), dim0=2, dim1=3).contiguous().view(B, -1, L)
return out_y[:, 0], inv_y[:, 0], wh_y, invwh_y
# an alternative to forward_corev1
def forward_corev1(self, x: torch.Tensor):
self.selective_scan = selective_scan_fn_v1
B, C, H, W = x.shape
L = H * W
K = 4
x_hwwh = torch.stack([x.view(B, -1, L), torch.transpose(x, dim0=2, dim1=3).contiguous().view(B, -1, L)],
dim=1).view(B, 2, -1, L)
xs = torch.cat([x_hwwh, torch.flip(x_hwwh, dims=[-1])], dim=1) # (b, k, d, l)
x_dbl = torch.einsum("b k d l, k c d -> b k c l", xs.view(B, K, -1, L), self.x_proj_weight)
# x_dbl = x_dbl + self.x_proj_bias.view(1, K, -1, 1)
dts, Bs, Cs = torch.split(x_dbl, [self.dt_rank, self.d_state, self.d_state], dim=2)
dts = torch.einsum("b k r l, k d r -> b k d l", dts.view(B, K, -1, L), self.dt_projs_weight)
# dts = dts + self.dt_projs_bias.view(1, K, -1, 1)
xs = xs.float().view(B, -1, L) # (b, k * d, l)
dts = dts.contiguous().float().view(B, -1, L) # (b, k * d, l)
Bs = Bs.float().view(B, K, -1, L) # (b, k, d_state, l)
Cs = Cs.float().view(B, K, -1, L) # (b, k, d_state, l)
Ds = self.Ds.float().view(-1) # (k * d)
As = -torch.exp(self.A_logs.float()).view(-1, self.d_state) # (k * d, d_state)
dt_projs_bias = self.dt_projs_bias.float().view(-1) # (k * d)
out_y = self.selective_scan(
xs, dts,
As, Bs, Cs, Ds,
delta_bias=dt_projs_bias,
delta_softplus=True,
).view(B, K, -1, L)
assert out_y.dtype == torch.float
inv_y = torch.flip(out_y[:, 2:4], dims=[-1]).view(B, 2, -1, L)
wh_y = torch.transpose(out_y[:, 1].view(B, -1, W, H), dim0=2, dim1=3).contiguous().view(B, -1, L)
invwh_y = torch.transpose(inv_y[:, 1].view(B, -1, W, H), dim0=2, dim1=3).contiguous().view(B, -1, L)
return out_y[:, 0], inv_y[:, 0], wh_y, invwh_y
def forward(self, x: torch.Tensor, **kwargs):
B, H, W, C = x.shape
xz = self.in_proj(x)
x, z = xz.chunk(2, dim=-1) # (b, h, w, d)
x = x.permute(0, 3, 1, 2).contiguous()
x = self.act(self.conv2d(x)) # (b, d, h, w)
y1, y2, y3, y4 = self.forward_core(x)
assert y1.dtype == torch.float32
y = y1 + y2 + y3 + y4
y = torch.transpose(y, dim0=1, dim1=2).contiguous().view(B, H, W, -1)
y = self.out_norm(y)
y = y * F.silu(z)
out = self.out_proj(y)
if self.dropout is not None:
out = self.dropout(out)
return out
class ConvLeakyRelu2d(nn.Module): # convolution # leaky relu def init(self, in_channels, out_channels, kernel_size=3, padding=1, stride=1, dilation=1, groups=1): super(ConvLeakyRelu2d, self).init() self.conv = nn.Conv2d(in_channels, out_channels, kernel_size=kernel_size, padding=padding, stride=stride, dilation=dilation, groups=groups) # self.bn = nn.BatchNorm2d(out_channels)
def forward(self, x):
# print(x.size())
return F.leaky_relu(self.conv(x), negative_slope=0.2)
class Conv1(nn.Module): def init(self, in_channels, out_channels, kernel_size=1, padding=0, stride=1, dilation=1, groups=1): super(Conv1, self).init() self.conv = nn.Conv2d(in_channels, out_channels, kernel_size=kernel_size, padding=padding, stride=stride, dilation=dilation, groups=groups)
def forward(self, x):
return self.conv(x)
class Sobelxy(nn.Module): def init(self, channels, kernel_size=3, padding=1, stride=1, dilation=1, groups=1): super(Sobelxy, self).init() sobel_filter = np.array([[1, 0, -1], [2, 0, -2], [1, 0, -1]]) self.convx = nn.Conv2d(channels, channels, kernel_size=kernel_size, padding=padding, stride=stride, dilation=dilation, groups=channels, bias=False) self.convx.weight.data.copy_(torch.from_numpy(sobel_filter)) self.convy = nn.Conv2d(channels, channels, kernel_size=kernel_size, padding=padding, stride=stride, dilation=dilation, groups=channels, bias=False) self.convy.weight.data.copy_(torch.from_numpy(sobel_filter.T))
def forward(self, x):
sobelx = self.convx(x)
sobely = self.convy(x)
x = torch.abs(sobelx) + torch.abs(sobely)
return x
class Conv2d_Hori_Veri_Cross(nn.Module): def init(self, in_channels, out_channels, kernel_size=3, stride=1, padding=1, dilation=1, groups=1, bias=False, theta=0.7):
super(Conv2d_Hori_Veri_Cross, self).__init__()
self.conv = nn.Conv2d(in_channels, out_channels, kernel_size=(1, 5), stride=stride, padding=padding,
dilation=dilation, groups=groups, bias=bias)
self.theta = theta
def forward(self, x):
[C_out, C_in, H_k, W_k] = self.conv.weight.shape
tensor_zeros = torch.FloatTensor(C_out, C_in, 1).fill_(0).cuda()
conv_weight = torch.cat((tensor_zeros, self.conv.weight[:, :, :, 0], tensor_zeros, self.conv.weight[:, :, :, 1],
self.conv.weight[:, :, :, 2], self.conv.weight[:, :, :, 3], tensor_zeros,
self.conv.weight[:, :, :, 4], tensor_zeros), 2)
conv_weight = conv_weight.contiguous().view(C_out, C_in, 3, 3)
out_normal = F.conv2d(input=x, weight=conv_weight, bias=self.conv.bias, stride=self.conv.stride,
padding=self.conv.padding)
if math.fabs(self.theta - 0.0) < 1e-8:
return out_normal
else:
# pdb.set_trace()
[C_out, C_in, kernel_size, kernel_size] = self.conv.weight.shape
kernel_diff = self.conv.weight.sum(2).sum(2)
kernel_diff = kernel_diff[:, :, None, None]
out_diff = F.conv2d(input=x, weight=kernel_diff, bias=self.conv.bias, stride=self.conv.stride, padding=0,
groups=self.conv.groups)
return out_normal - self.theta * out_diff
class Conv2d_Diag_Cross(nn.Module): def init(self, in_channels, out_channels, kernel_size=3, stride=1, padding=1, dilation=1, groups=1, bias=False, theta=0.7):
super(Conv2d_Diag_Cross, self).__init__()
self.conv = nn.Conv2d(in_channels, out_channels, kernel_size=(1, 5), stride=stride, padding=padding,
dilation=dilation, groups=groups, bias=bias)
self.theta = theta
def forward(self, x):
[C_out, C_in, H_k, W_k] = self.conv.weight.shape
tensor_zeros = torch.FloatTensor(C_out, C_in, 1).fill_(0).cuda()
conv_weight = torch.cat((self.conv.weight[:, :, :, 0], tensor_zeros, self.conv.weight[:, :, :, 1], tensor_zeros,
self.conv.weight[:, :, :, 2], tensor_zeros, self.conv.weight[:, :, :, 3], tensor_zeros,
self.conv.weight[:, :, :, 4]), 2)
conv_weight = conv_weight.contiguous().view(C_out, C_in, 3, 3)
out_normal = F.conv2d(input=x, weight=conv_weight, bias=self.conv.bias, stride=self.conv.stride,
padding=self.conv.padding)
if math.fabs(self.theta - 0.0) < 1e-8:
return out_normal
else:
# pdb.set_trace()
[C_out, C_in, kernel_size, kernel_size] = self.conv.weight.shape
kernel_diff = self.conv.weight.sum(2).sum(2)
kernel_diff = kernel_diff[:, :, None, None]
out_diff = F.conv2d(input=x, weight=kernel_diff, bias=self.conv.bias, stride=self.conv.stride, padding=0,
groups=self.conv.groups)
return out_normal - self.theta * out_diff
class Conv2d_CDC(nn.Module): def init(self, in_channels, basic_conv1=Conv2d_Hori_Veri_Cross, basic_conv2=Conv2d_Diag_Cross, theta=0.8): super(Conv2d_CDC, self).init() self.conv1 = nn.Sequential( nn.Conv2d(in_channels,in_channels//2,1,1), basic_conv1(in_channels//2, in_channels//2, kernel_size=3, stride=1, padding=1, bias=False, theta=theta), nn.BatchNorm2d(in_channels//2), nn.ReLU(), )
self.conv1_2 = nn.Sequential(
nn.Conv2d(in_channels, in_channels // 2, 1, 1),
basic_conv2(in_channels//2, in_channels//2, kernel_size=3, stride=1, padding=1, bias=False, theta=theta),
nn.BatchNorm2d(in_channels//2),
nn.ReLU(),
)
self.lastconv3 = nn.Sequential(
nn.Conv2d(in_channels, in_channels, kernel_size=1, stride=1, padding=0, bias=False),
nn.ReLU(),
)
self.theta = theta
def forward(self, x):
x_H = self.conv1(x)
x_D = self.conv1_2(x)
depth = torch.cat((x_H, x_D), dim=1)
depth = self.lastconv3(depth) # x [1, 32, 32]
return depth
class LDC(nn.Module): def init(self, in_channels, out_channels, kernel_size=3, stride=1, padding=1, dilation=1, groups=1, bias=False): # conv.weight.size() = [out_channels, in_channels, kernel_size, kernel_size] super(LDC, self).init() self.conv = nn.Conv2d(in_channels, out_channels, kernel_size=kernel_size, stride=stride, padding=padding, dilation=dilation, groups=groups, bias=bias) # [12,3,3,3]
self.center_mask = torch.tensor([[0, 0, 0],
[0, 1, 0],
[0, 0, 0]]).cuda()
self.base_mask = nn.Parameter(torch.ones(self.conv.weight.size()), requires_grad=False) # [12,3,3,3]
self.learnable_mask = nn.Parameter(torch.ones([self.conv.weight.size(0), self.conv.weight.size(1)]),
requires_grad=True) # [12,3]
self.learnable_theta = nn.Parameter(torch.ones(1) * 0.5, requires_grad=True) # [1]
# print(self.learnable_mask[:, :, None, None].shape)
def forward(self, x):
mask = self.base_mask - self.learnable_theta * self.learnable_mask[:, :, None, None] * \
self.center_mask * self.conv.weight.sum(2).sum(2)[:, :, None, None]
out_diff = F.conv2d(input=x, weight=self.conv.weight * mask, bias=self.conv.bias, stride=self.conv.stride,
padding=self.conv.padding,
groups=self.conv.groups)
return out_diff
class VSSBlock(nn.Module): def init( self, hidden_dim: int = 0, drop_path: float = 0, norm_layer: Callable[..., torch.nn.Module] = partial(nn.LayerNorm, eps=1e-6), attn_drop_rate: float = 0, d_state: int = 16, **kwargs, ): super().init() self.ln_1 = norm_layer(hidden_dim) self.self_attention = SS2D(d_model=hidden_dim, dropout=attn_drop_rate, d_state=d_state, **kwargs) self.drop_path = DropPath(drop_path) self.CDC_block = LDC(hidden_dim, hidden_dim)
def forward(self, input: torch.Tensor):
x_ = input.permute(0, 3, 1, 2) # (1,64,64,96)
Grad_x = (self.CDC_block(x_)).permute(0, 2, 3, 1)
x = input + self.drop_path(self.self_attention(self.ln_1(input))) + Grad_x
return x
class VSSLayer(nn.Module):
def __init__(
self,
dim,
depth,
attn_drop=0.,
drop_path=0.,
norm_layer=nn.LayerNorm,
downsample=None,
use_checkpoint=False,
d_state=16,
**kwargs,
):
super().__init__()
self.dim = dim
self.use_checkpoint = use_checkpoint
self.blocks = nn.ModuleList([
VSSBlock_new(
hidden_dim=dim,
drop_path=drop_path[i] if isinstance(drop_path, list) else drop_path,
norm_layer=norm_layer,
attn_drop_rate=attn_drop,
d_state=d_state,
)
for i in range(depth)])
if True: # is this really applied? Yes, but been overriden later in VSSM!
def _init_weights(module: nn.Module):
for name, p in module.named_parameters():
if name in ["out_proj.weight"]:
p = p.clone().detach_() # fake init, just to keep the seed ....
nn.init.kaiming_uniform_(p, a=math.sqrt(5))
self.apply(_init_weights)
if downsample is not None:
self.downsample = downsample(dim=dim, norm_layer=norm_layer)
else:
self.downsample = None
def forward(self, x):
for blk in self.blocks:
if self.use_checkpoint:
x = checkpoint.checkpoint(blk, x)
else:
x = blk(x)
if self.downsample is not None:
x = self.downsample(x)
return x
class VSSLayer_up(nn.Module):
def __init__(
self,
dim,
depth,
attn_drop=0.,
drop_path=0.,
norm_layer=nn.LayerNorm,
upsample=None,
use_checkpoint=False,
d_state=16,
**kwargs,
):
super().__init__()
self.dim = dim
self.use_checkpoint = use_checkpoint
self.blocks = nn.ModuleList([
VSSBlock_new(
hidden_dim=dim,
drop_path=drop_path[i] if isinstance(drop_path, list) else drop_path,
norm_layer=norm_layer,
attn_drop_rate=attn_drop,
d_state=d_state,
)
for i in range(depth)])
if True: # is this really applied? Yes, but been overriden later in VSSM!
def _init_weights(module: nn.Module):
for name, p in module.named_parameters():
if name in ["out_proj.weight"]:
p = p.clone().detach_() # fake init, just to keep the seed ....
nn.init.kaiming_uniform_(p, a=math.sqrt(5))
self.apply(_init_weights)
if upsample is not None:
self.upsample = upsample(dim=dim, norm_layer=norm_layer)
else:
self.upsample = None
def forward(self, x):
if self.upsample is not None:
x = self.upsample(x)
for blk in self.blocks:
if self.use_checkpoint:
x = checkpoint.checkpoint(blk, x)
else:
x = blk(x)
return x
class VSSM_Fusion(nn.Module): def init(self, patch_size=4, in_chans=1, num_classes=1000, depths=[2, 2, 9, 2], depths_decoder=[2, 9, 2, 2], dims=[96, 192, 384, 768], dims_decoder=[768, 384, 192, 96], d_state=16, drop_rate=0., attn_drop_rate=0., drop_path_rate=0.1, norm_layer=nn.LayerNorm, patch_norm=True, use_checkpoint=False, **kwargs): super().init() self.num_classes = num_classes self.num_layers = len(depths) if isinstance(dims, int): dims = [int(dims * 2 ** i_layer) for i_layer in range(self.num_layers)] self.embed_dim = dims[0] self.num_features = dims[-1] self.dims = dims
self.patch_embed1 = PatchEmbed2D(patch_size=patch_size, in_chans=in_chans, embed_dim=self.embed_dim,
norm_layer=norm_layer if patch_norm else None)
self.patch_embed2 = PatchEmbed2D(patch_size=patch_size, in_chans=in_chans, embed_dim=self.embed_dim,
norm_layer=norm_layer if patch_norm else None)
# WASTED absolute position embedding ======================
self.ape = False
if self.ape:
self.patches_resolution = self.patch_embed.patches_resolution
self.absolute_pos_embed1 = nn.Parameter(torch.zeros(1, *self.patches_resolution, self.embed_dim))
self.absolute_pos_embed2 = nn.Parameter(torch.zeros(1, *self.patches_resolution, self.embed_dim))
trunc_normal_(self.absolute_pos_embed, std=.02)
self.pos_drop = nn.Dropout(p=drop_rate)
dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))] # stochastic depth decay rule
dpr_decoder = [x.item() for x in torch.linspace(0, drop_path_rate, sum(depths_decoder))][::-1]
self.layers = nn.ModuleList()
for i_layer in range(self.num_layers): # VSS Block
layer = VSSLayer(
dim=dims[i_layer],
depth=depths[i_layer],
d_state=math.ceil(dims[0] / 6) if d_state is None else d_state,
drop=drop_rate,
attn_drop=attn_drop_rate,
drop_path=dpr[sum(depths[:i_layer]):sum(depths[:i_layer + 1])],
norm_layer=norm_layer,
downsample=PatchMerging2D if (i_layer < self.num_layers - 1) else None,
use_checkpoint=use_checkpoint,
)
self.layers.append(layer)
self.layers_up = nn.ModuleList()
for i_layer in range(self.num_layers):
layer = VSSLayer_up(
dim=dims_decoder[i_layer],
depth=depths_decoder[i_layer],
d_state=math.ceil(dims[0] / 6) if d_state is None else d_state, # 20240109
drop=drop_rate,
attn_drop=attn_drop_rate,
drop_path=dpr_decoder[sum(depths_decoder[:i_layer]):sum(depths_decoder[:i_layer + 1])],
norm_layer=norm_layer,
upsample=PatchExpand2D if (i_layer != 0) else None,
use_checkpoint=use_checkpoint,
)
self.layers_up.append(layer)
self.final_up = Final_PatchExpand2D(dim=dims_decoder[-1], dim_scale=4, norm_layer=norm_layer)
self.final_conv = nn.Conv2d(dims_decoder[-1] // 4, 1, 1)
self.Cross_block = nn.ModuleList()
for cross_layer in range(self.num_layers): # VSS Block
clayer = VSSBlock_Cross_new(
hidden_dim=dims[cross_layer],
drop_path=drop_rate,
norm_layer=norm_layer,
attn_drop_rate=attn_drop_rate,
d_state=d_state,
)
self.Cross_block.append(clayer)
self.apply(self._init_weights)
def _init_weights(self, m: nn.Module):
if isinstance(m, nn.Linear):
trunc_normal_(m.weight, std=.02)
if isinstance(m, nn.Linear) and m.bias is not None:
nn.init.constant_(m.bias, 0)
elif isinstance(m, nn.LayerNorm):
nn.init.constant_(m.bias, 0)
nn.init.constant_(m.weight, 1.0)
@torch.jit.ignore
def no_weight_decay(self):
return {'absolute_pos_embed'}
@torch.jit.ignore
def no_weight_decay_keywords(self):
return {'relative_position_bias_table'}
def forward_features_1(self, x):
skip_list = []
x = self.patch_embed1(x)
if self.ape:
x = x + self.absolute_pos_embed1
x = self.pos_drop(x)
for layer in self.layers:
skip_list.append(x)
x = layer(x)
return x, skip_list
def forward_features_2(self, x):
skip_list = []
x = self.patch_embed2(x)
if self.ape:
x = x + self.absolute_pos_embed2
x = self.pos_drop(x)
for layer in self.layers:
skip_list.append(x)
x = layer(x)
return x, skip_list
def Fusion_network(self, skip_list1, skip_list2):
fused_skip_list = []
for Cross_layer, skip1, skip2 in zip(self.Cross_block, skip_list1, skip_list2):
fused_skip = Cross_layer(skip1, skip2)
fused_skip_list.append(fused_skip)
return fused_skip_list
def forward_features_up(self, x, skip_list):
for inx, layer_up in enumerate(self.layers_up):
if inx == 0:
x = layer_up(x)
else:
x = layer_up(x + skip_list[-inx])
return x
def forward_final(self, x):
x = self.final_up(x)
x = x.permute(0, 3, 1, 2)
x = self.final_conv(x)
return x
def forward_backbone(self, x):
x = self.patch_embed(x)
if self.ape:
x = x + self.absolute_pos_embed
x = self.pos_drop(x)
for layer in self.layers:
x = layer(x)
return x
def forward(self, x1, x2):
x_1 = x1
x_2 = x2
x1, skip_list1 = self.forward_features_1(x1)
x2, skip_list2 = self.forward_features_2(x2)
x = x1 + x2
skip_list = self.Fusion_network(skip_list1,skip_list2)
x = self.forward_features_up(x, skip_list)
x = self.forward_final(x) + x_1 + x_2
return x
if name == "main": net = VSSM_Fusion(patch_size=4, in_chans=1, num_classes=1000, depths=[2, 2, 9, 2], depths_decoder=[2, 9, 2, 2], dims=[96, 192, 384, 768], dims_decoder=[768, 384, 192, 96], d_state=16, drop_rate=0., attn_drop_rate=0., drop_path_rate=0.1, norm_layer=nn.LayerNorm, patch_norm=True, use_checkpoint=False).cuda() x1 = torch.rand((4, 1, 256, 256)).cuda() x2 = torch.rand((4, 1, 256, 256)).cuda() a = net(x1, x2).cuda() print(a.shape)
forward method processes two different image inputs (or channels), passes them through embedding, fusion, attention, and final expansion layers to produce the model’s output.At execution, the script constructs an instance of VSSM_Fusion. This instance processes two synthetic inputs representing two separate image channels. The overall structure resembles an attention-based image processing network aimed at tasks like image segmentation, enhancement, or classification through feature fusion from multiple sources.
__init__), multiple layers and blocks are configured. The forward pass is executed using torch tensors as input, where methods are called in sequence to pass data through the network.Such a model architecture could be suitable for scenarios requiring complex feature extraction or fusion, such as multi-spectral imaging, stereo image processing, or any application benefiting from fusing different feature representations. The code setup showcases considerable flexibility, with parameterization allowing adjustments for a variety of dataset characteristics and learning tasks.