【AAAI 2027即插即用】Mamba模块篇 | MUB曼巴上采样模块,特别适用于图像恢复、图像超分辨率、图像恢复、暗光增强、遥感任务、目标检测、图像分割 和 医学影像分析等CV任务通用,涨点起飞 - __init__()
本文目录
1.论文介绍:
2.论文创新点:
3.方法描述:
4.MUB 即插即用模块作用:
MUB模块作用:
MUB模块实现:
5.适用任务场景:
1. 图像超分辨率(Super-Resolution):
2. 图像恢复(Image Restoration):
3. 目标检测(Object Detection):
4. 图像分割(Image Segmentation):
5. 医学影像分析:
6.即插即用模块代码:
1.论文介绍:
AAAI 2026顶会
论文题目:MFmamba: A Multi-function Network for Panchromatic Image Resolution Restoration Based on State-Space Model
中文题目:MFmamba:一种基于状态空间模型的全色图像分辨率恢复多功能网络
所属单位:云南大学
摘要:遥感图像在军事和地球资源勘探中越来越普及。由于单一传感器的限制,我们可以获得高空间分辨率的灰度全色(PAN)图像和低空间分辨率的彩色多光谱(MS)图像。因此,一个重要的问题是在只有PAN图像作为输入时,如何获得高空间分辨率的彩色图像。现有的方法通过超分辨率(SR)技术提高空间分辨率,并通过着色技术进行光谱恢复。然而,SR技术无法提高光谱分辨率,着色技术也无法提高空间分辨率。此外,全色锐化(pansharpening)方法需要两个已配准的输入,并且无法实现超分辨率。因此,需要一种综合的方法。为了应对上述问题,我们设计了一种新型多功能模型(MFmamba),能够通过三种不同输入实现SR、光谱恢复以及SR与光谱恢复的联合任务。首先,MFmamba采用UNet++作为骨干网络,并将Mamba上采样模块(MUB)与UNet++结合。其次,设计了双池注意力(DPA)来替换UNet++中的跳跃连接。最后,提出了多尺度混合交叉模块(MHCB)用于初始特征提取。大量实验表明,MFmamba在评估指标和视觉效果上具有竞争力,并且在仅使用PAN图像输入时,在三项任务中均表现良好。
2.论文创新点:
本文提出了一种多功能分辨率恢复模型 MFmamba,旨在提升遥感图像的空间分辨率和光谱分辨率。本文的主要创新点包括:
多功能模型设计:MFmamba 集成了图像超分辨率(SR)和光谱恢复(colorization),能够通过单一输入(PAN 图像)实现三种任务:SR、光谱恢复、以及联合 SR 和光谱恢复。这种集成的模型避免了现有方法中 SR 和光谱恢复任务分开处理的问题。 Mamba Upsample Block (MUB):本文提出了 MUB 模块,结合了状态空间模型来增强模型的上下文建模能力。该模块通过不同的扫描方向(包括斜向扫描)有效地捕捉长程依赖关系,从而提升了图像分辨率恢复的性能。 Multi-scale Hybrid Cross Block (MHCB):为了解决多尺度特征提取问题,设计了 MHCB 模块,通过并行卷积路径和不同卷积核大小来提取多尺度的特征信息。此模块可以有效捕捉图像的局部和全局信息,提升细节特征提取能力。 Dual Pool Attention (DPA):本文提出了 DPA 模块,通过双池化架构动态调整通道权重,增强了特征通道的表示能力,能够使模型更加聚焦于图像中关键的特征通道。这一模块在图像恢复中起到了提升模型性能的重要作用。 多任务联合学习:MFmamba 实现了多任务联合学习,通过单一的输入图像同时进行超分辨率和光谱恢复任务,从而在多个图像恢复任务中获得了良好的表现。 实验验证和对比:通过在多个遥感数据集(如 Potsdam、NWPU 等)上进行广泛的实验,本文验证了 MFmamba 在超分辨率、光谱恢复和联合恢复任务中的优越性。与现有方法相比,MFmamba 在多个评估指标上表现优异,尤其在处理遥感图像中的细节和关键信息时,显示出了强大的能力。
MFmamba 通过结合多个创新模块,提出了一种高效的遥感图像分辨率恢复方法,能够同时处理超分辨率和光谱恢复任务,取得了显著的性能提升。
3.方法描述:
MFmamba(Multi-function Mamba)是一种针对遥感图像的多功能分辨率恢复方法,旨在通过单一输入实现图像超分辨率(SR)和光谱恢复(colorization)任务。MFmamba 模型设计的核心目标是同时提升遥感图像的空间分辨率和光谱分辨率,解决了传统方法需要分别处理这两种任务的瓶颈。
方法概述:
多功能模型设计:MFmamba 集成了图像超分辨率(SR)和光谱恢复(colorization)任务,通过单一输入(PAN 图像)同时完成这两个任务。该方法避免了传统模型将空间分辨率恢复和光谱恢复分开处理的做法,实现了任务的联合优化。 Mamba Upsample Block (MUB):MFmamba 提出了 MUB 模块,结合状态空间模型来增强上下文建模能力。MUB 通过多个扫描方向(包括斜向扫描)有效捕捉图像的长程依赖,从而提升空间分辨率恢复性能。 Multi-scale Hybrid Cross Block (MHCB):为了更好地进行多尺度特征提取,MFmamba 引入了 MHCB 模块。该模块通过并行卷积路径和不同大小的卷积核,能够提取图像的局部和全局特征,从而提升细节恢复的能力。 Dual Pool Attention (DPA):DPA 模块通过双池化结构来动态调整通道的权重,提升了通道特征的表示能力,使模型能够聚焦于图像中的关键信息。这一模块在图像恢复中提高了模型的整体性能。 联合任务学习:MFmamba 实现了多任务学习,通过单一输入图像同时处理超分辨率和光谱恢复任务。这样不仅提升了恢复质量,还提高了训练效率。 实验与验证:MFmamba 在多个遥感数据集上进行了测试(如 Potsdam、NWPU),并在多个评估指标上超越了现有方法,特别是在细节恢复和关键信息提取方面表现优异。
4.MUB 即插即用模块作用:
MUB模块作用:
提升图像分辨率:MUB模块能够通过卷积操作和像素重排(PixelShuffle)上采样,提升输入图像的空间分辨率,使得图像更加清晰,细节更加丰富。 增强特征表达能力:通过多个卷积层和残差连接,MUB模块能有效地提取输入图像的多层次特征,并增强这些特征的表示能力。 细节恢复:MUB模块结合了卷积、注意力和MLP操作,使得模型能够在超分辨率任务中恢复图像中的细节,特别是在低分辨率图像中。
MUB模块实现:
卷积层和激活函数:MUB模块包括多个卷积层(通常是3x3卷积)和激活函数(如ReLU或GELU),用于逐步提取输入图像的特征。通过逐步增加卷积层和通道数,增强特征表示能力。 PixelShuffle(像素重排):通过使用 PixelShuffle 层,MUB模块实现了上采样操作。PixelShuffle 会将高维度特征图重新排列,以提升空间分辨率,这对超分辨率任务尤为重要。 残差连接:MUB模块使用残差连接(skip connections)将输入与处理后的特征相加,以防止梯度消失并提高模型的训练稳定性。 多尺度特征融合:MUB模块通过逐层处理输入图像,融合来自不同尺度的特征,提升图像恢复的质量。它可以结合多个卷积核大小来提取图像的局部和全局特征。 MLP和注意力机制:MUB模块结合了感知机(MLP)和注意力机制(如通道注意力机制),帮助模型聚焦于图像中的关键信息,提高图像细节恢复的能力。
5.适用任务场景:
MUB模块的适用计算机视觉任务:
1. 图像超分辨率(Super-Resolution):
MUB模块非常适合超分辨率任务,能够通过上采样操作提升低分辨率图像的空间分辨率,并恢复图像中的细节,使图像更加清晰。通过PixelShuffle操作,MUB模块在高分辨率图像的恢复中发挥了重要作用。
2. 图像恢复(Image Restoration):
MUB模块能在图像去噪、去雾、去雨等图像恢复任务中有效提取细节,恢复图像中的关键信息。它通过多层卷积和残差连接增强了图像的特征表示,帮助恢复复杂场景中的丢失信息。
3. 目标检测(Object Detection):
在目标检测任务中,MUB模块可以提升图像的分辨率,并增强图像细节,使得模型能够更准确地识别目标,特别是在图像分辨率较低的情况下,能显著提高检测精度。
4. 图像分割(Image Segmentation):
MUB模块可以帮助提高图像分割任务中的精度,特别是在细粒度分割中,能够提供更多的细节信息,帮助模型精确地分割图像中的物体或区域。
5. 医学影像分析:
在医学影像(如MRI、CT扫描等)的恢复和增强中,MUB模块能够提升医学图像的清晰度和细节,帮助更好地识别病变区域和重要结构,支持医学图像的精确分析。
6.即插即用模块代码:
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from functools import partial
from typing import Callable
from timm.models.layers import DropPath,to_2tuple
from mamba_ssm.ops.selective_scan_interface import selective_scan_fn, selective_scan_ref
from einops import repeat
NEG_INF = -1000000
class PatchEmbed(nn.Module):
def __init__(self, img_size=224, patch_size=4, in_chans=3, embed_dim=96, norm_layer=None):
super().__init__()
img_size = to_2tuple(img_size)
patch_size = to_2tuple(patch_size)
patches_resolution = [img_size[0] // patch_size[0], img_size[1] // patch_size[1]]
self.img_size = img_size
self.patch_size = patch_size
self.patches_resolution = patches_resolution
self.num_patches = patches_resolution[0] * patches_resolution[1]
self.in_chans = in_chans
self.embed_dim = embed_dim
if norm_layer is not None:
self.norm = norm_layer(embed_dim)
else:
self.norm = None
def forward(self, x):
x = x.flatten(2).transpose(1, 2)
if self.norm is not None:
x = self.norm(x)
return x
def flops(self):
flops = 0
h, w = self.img_size
if self.norm is not None:
flops += h * w * self.embed_dim
return flops
class PatchUnEmbed(nn.Module):
def __init__(self, img_size=224, patch_size=4, in_chans=3, embed_dim=96, norm_layer=None):
super().__init__()
img_size = to_2tuple(img_size)
patch_size = to_2tuple(patch_size)
patches_resolution = [img_size[0] // patch_size[0], img_size[1] // patch_size[1]]
self.img_size = img_size
self.patch_size = patch_size
self.patches_resolution = patches_resolution
self.num_patches = patches_resolution[0] * patches_resolution[1]
self.in_chans = in_chans
self.embed_dim = embed_dim
def forward(self, x, x_size):
x = x.transpose(1, 2).view(x.shape[0], self.embed_dim, x_size[0], x_size[1])
return x
def flops(self):
flops = 0
return flops
class Upsample(nn.Sequential):
def __init__(self, scale, num_feat):
m = []
if (scale & (scale - 1)) == 0:
for _ in range(int(math.log(scale, 2))):
m.append(nn.Conv2d(num_feat, 4 * num_feat, 3, 1, 1))
m.append(nn.PixelShuffle(2))
elif scale == 3:
m.append(nn.Conv2d(num_feat, 9 * num_feat, 3, 1, 1))
m.append(nn.PixelShuffle(3))
else:
raise ValueError(f'scale {scale} is not supported. Supported scales: 2^n and 3.')
super(Upsample, self).__init__(*m)
class ChannelAttention(nn.Module):
"""Channel attention used in RCAN.
Args:
num_feat (int): Channel number of intermediate features.
squeeze_factor (int): Channel squeeze factor. Default: 16.
"""
def __init__(self, num_feat, squeeze_factor=16):
super(ChannelAttention, self).__init__()
self.attention = nn.Sequential(
nn.AdaptiveAvgPool2d(1),
nn.Conv2d(num_feat, num_feat // squeeze_factor, 1, padding=0),
nn.ReLU(inplace=True),
nn.Conv2d(num_feat // squeeze_factor, num_feat, 1, padding=0),
nn.Sigmoid())
def forward(self, x):
y = self.attention(x)
return x * y
class CAB(nn.Module):
def __init__(self, num_feat, is_light_sr= False, compress_ratio=3,squeeze_factor=30):
super(CAB, self).__init__()
self.cab = nn.Sequential(
nn.Conv2d(num_feat, num_feat // compress_ratio, 3, 1, 1),
nn.GELU(),
nn.Conv2d(num_feat // compress_ratio, num_feat, 3, 1, 1),
ChannelAttention(num_feat, squeeze_factor)
)
def forward(self, x):
return self.cab(x)
class SEAttention(nn.Module):
def __init__(self, num_feat, reduction=16):
super(SEAttention, self).__init__()
self.avg_pool = nn.AdaptiveAvgPool2d(1)
self.fc = nn.Sequential(
nn.Linear(num_feat, num_feat // reduction, bias=False),
nn.ReLU(inplace=True),
nn.Linear(num_feat // reduction, num_feat, bias=False),
nn.Sigmoid()
)
def forward(self, x):
b, c, _, _ = x.size()
y = self.avg_pool(x).view(b, c)
y = self.fc(y).view(b, c, 1, 1)
# print('se.shape:', (x * y.expand_as(x)).shape)
return x * y.expand_as(x)
class Mlp(nn.Module):
def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.):
super().__init__()
out_features = out_features or in_features
hidden_features = hidden_features or in_features
self.fc1 = nn.Linear(in_features, hidden_features)
self.act = act_layer()
self.fc2 = nn.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 DynamicPosBias(nn.Module):
def __init__(self, dim, num_heads):
super().__init__()
self.num_heads = num_heads
self.pos_dim = dim // 4
self.pos_proj = nn.Linear(2, self.pos_dim)
self.pos1 = nn.Sequential(
nn.LayerNorm(self.pos_dim),
nn.ReLU(inplace=True),
nn.Linear(self.pos_dim, self.pos_dim),
)
self.pos2 = nn.Sequential(
nn.LayerNorm(self.pos_dim),
nn.ReLU(inplace=True),
nn.Linear(self.pos_dim, self.pos_dim)
)
self.pos3 = nn.Sequential(
nn.LayerNorm(self.pos_dim),
nn.ReLU(inplace=True),
nn.Linear(self.pos_dim, self.num_heads)
)
def forward(self, biases):
pos = self.pos3(self.pos2(self.pos1(self.pos_proj(biases))))
return pos
def flops(self, N):
flops = N * 2 * self.pos_dim
flops += N * self.pos_dim * self.pos_dim
flops += N * self.pos_dim * self.pos_dim
flops += N * self.pos_dim * self.num_heads
return flops
class SS2D(nn.Module):
def __init__(
self,
d_model,
d_state=16,
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_conv = d_conv
self.expand = expand
self.d_inner = int(self.expand * self.d_model)
# self.conv_blk = CAB(self.d_inner)
# self.conv_se = SEAttention(self.d_inner)
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))
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))
self.dt_projs_bias = nn.Parameter(torch.stack([t.bias for t in self.dt_projs], dim=0))
del self.dt_projs
self.A_logs = self.A_log_init(self.d_state, self.d_inner, copies=4, merge=True)
self.Ds = self.D_init(self.d_inner, copies=4, merge=True)
self.selective_scan = selective_scan_fn
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)
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
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)
inv_dt = dt + torch.log(-torch.expm1(-dt))
with torch.no_grad():
dt_proj.bias.copy_(inv_dt)
dt_proj.bias._no_reinit = True
return dt_proj
@staticmethod
def A_log_init(d_state, d_inner, copies=1, device=None, merge=True):
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)
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 = 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)
D._no_weight_decay = True
return D
def forward_core(self, x: torch.Tensor):
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)
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)
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)
xs = xs.float().view(B, -1, L)
dts = dts.contiguous().float().view(B, -1, L)
Bs = Bs.float().view(B, K, -1, L)
Cs = Cs.float().view(B, K, -1, L)
Ds = self.Ds.float().view(-1)
As = -torch.exp(self.A_logs.float()).view(-1, self.d_state)
dt_projs_bias = self.dt_projs_bias.float().view(-1)
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)
# 提取第五个视角并进行变换
view5_y = torch.transpose(out_y[:, 3].view(B, -1, W, H), dim0=2, dim1=3).contiguous().view(B, -1, L)
inv_view5_y = torch.flip(view5_y, dims=[-1]).view(B, -1, L)
# 提取第六个视角并进行变换
view6_y = torch.transpose(out_y[:, 3].view(B, -1, W, H), dim0=2, dim1=3).contiguous().view(B, -1, L)
inv_view6_y = torch.flip(view6_y, dims=[-1]).view(B, -1, L)
return out_y[:, 0], inv_y[:, 0], wh_y, invwh_y, inv_view5_y, inv_view6_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)
x = x.permute(0, 3, 1, 2).contiguous()
x = self.act(self.conv2d(x))
y1, y2, y3, y4, y5, y6 = self.forward_core(x)
assert y1.dtype == torch.float32
y = y1 + y2 + y3 + y4 + y5 + y6
y = torch.transpose(y, dim0=1, dim1=2).contiguous().view(B, H, W, -1)
y = self.out_norm(y) # [1, 128, 128, 360]
# y = self.conv_se(y.permute(0, 3, 1, 2).contiguous()).permute(0, 2, 3, 1).contiguous()
y = y * F.silu(z)
out = self.out_proj(y)
if self.dropout is not None:
out = self.dropout(out)
return out
class MUB(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,
mlp_ratio: float = 2.,
**kwargs,
):
super().__init__()
self.ln_1 = norm_layer(hidden_dim)
self.self_attention = SS2D(d_model=hidden_dim, d_state=d_state,expand=mlp_ratio,dropout=attn_drop_rate, **kwargs)
self.drop_path = DropPath(drop_path)
self.skip_scale= nn.Parameter(torch.ones(hidden_dim))
self.conv_blk = CAB(hidden_dim)
self.conv_se = SEAttention(hidden_dim) # [1, 180, 128, 128]
self.ln_2 = nn.LayerNorm(hidden_dim)
self.skip_scale2 = nn.Parameter(torch.ones(hidden_dim))
mlp_hidden_dim = int(hidden_dim * mlp_ratio) # MLP感知层
self.mlp = Mlp(in_features=hidden_dim, hidden_features=mlp_hidden_dim, act_layer=nn.GELU, drop=0.) # MLP感知层
def forward(self, input, x_size):
B, L, C = input.shape
input = input.view(B, *x_size, C).contiguous() # [B,H,W,C]
x = self.ln_1(input)
x1 = self.conv_blk(self.ln_2(x).permute(0, 3, 1, 2).contiguous()).permute(0, 2, 3, 1).contiguous()
x2 = self.drop_path(self.self_attention(x))
x = input * self.skip_scale + x1 + x2
x = x * self.skip_scale2 + self.drop_path(self.mlp(self.ln_2(x)))
# x = self.conv_se(x.permute(0, 3, 1, 2).contiguous()).permute(0, 2, 3, 1).contiguous()
x = x.view(B, -1, C).contiguous()
return x
if __name__ == "__main__":
# 定义 MUB 模块实例
model = MUB(hidden_dim=64, drop_path=0.1, attn_drop_rate=0.1)
# 创建随机输入张量,形状为 [batch_size, sequence_length, channels]
input_tensor = torch.randn(2, 128, 64) # [2, 128, 64]:Batch size: 2, Sequence length: 128, Channels: 64
# 定义输入的大小(H, W)
x_size = (128, 128)
# 前向传播
output_tensor = model(input_tensor, x_size)
# 输出结果的形状
print("MUB输入特征层维度:", input_tensor.shape) # 输出输入特征的形状
print("MUB输出特征层维度:", output_tensor .shape) # 输出输出特征的形状