局部卷积后将特征重排为 (B,块内位置,块数,dim),以三层 Transformer 在相同块内位置之间进行跨块注意力,再折叠回二维并与输入拼接融合。
(2, 32, 8, 8) · 32 通道,8×8;patch_size=2(2, 32, 8, 8) · 拼接原输入后卷积恢复 32 通道822,560 个参数 · CPU / eval / FP32;sum(p.numel());轻量视觉骨干特征混合。配置 MobileViTAttention(in_channel=32,dim=64,patch_size=2)forward() 数据流顺序拆解 · 点击任意子模块方块可同步查看对应源码切片局部卷积后将特征重排为 (B,块内位置,块数,dim),以三层 Transformer 在相同块内位置之间进行跨块注意力,再折叠回二维并与输入拼接融合。
79 self.conv1=nn.Conv2d(in_channel,in_channel,kernel_size=kernel_size,padding=kernel_size//2)80 self.conv2=nn.Conv2d(in_channel,dim,kernel_size=1)82 self.trans=Transformer(dim=dim,depth=3,heads=8,head_dim=64,mlp_dim=1024)84 self.conv3=nn.Conv2d(dim,in_channel,kernel_size=1)85 self.conv4=nn.Conv2d(2*in_channel,in_channel,kernel_size=kernel_size,padding=kernel_size//2)91 y=self.conv2(self.conv1(x)) #bs,dim,h,w95 y=rearrange(y,'bs dim (nh ph) (nw pw) -> bs (ph pw) (nh nw) dim',ph=self.ph,pw=self.pw) #bs,h,w,dim96 y=self.trans(y)97 y=rearrange(y,'bs (ph pw) (nh nw) dim -> bs dim (nh ph) (nw pw)',ph=self.ph,pw=self.pw,nh=h//self.ph,nw=w//self.pw) #bs,dim,h,w100 y=self.conv3(y) #bs,dim,h,w101 y=torch.cat([x,y],1) #bs,2*dim,h,w102 y=self.conv4(y) #bs,c,h,w
将 MobileViTAttention.py 所在目录加入 Python 搜索路径后使用。32 通道,8×8;patch_size=2。下面给出与参数卡一致的构造配置,输入张量 x 应采用上方实测形状。
from MobileViTAttention import MobileViTAttention block = MobileViTAttention(in_channel=32,dim=64,patch_size=2).eval() y = block(x)
Method 动机参考:卷积提供局部结构,跨块序列传递远处上下文,末端卷积融合原始特征。
| 消融变体 | 结构配置 | 验证目的 |
|---|---|---|
| 局部分支 | 去掉 Transformer | 检查跨块上下文 |
| 块大小 | patch_size=2 / 4 | 比较序列长度与开销 |
| 完整模块 | 卷积 + Transformer + 拼接 | 比较任务指标、延迟与显存 |