模块更新于 2026-11-20· 浏览 1· 下载 0
ReMoE 区域感知混合专家模块
三粒度专家互补:全局专家聚合整图上下文,中心专家专注中央区域,区域专家各管一块空间分区,直接替换 ViT 块里的标准 FFN,补上区域级归纳偏置
结构图

三粒度专家互补:全局专家聚合整图上下文,中心专家专注中央区域,区域专家各管一块空间分区,直接替换 ViT 块里的标准 FFN,补上区域级归纳偏置
论文信息
- 论文:ReMoE: Region-Mixture Experts for Adversarially-Robust Vision Transformers
- 出处:CVPR 2026
核心痛点
ViT 缺乏区域级语义建模——全局耦合的自注意力会把局部扰动扩散到整个特征空间,空间均匀的 FFN 分不清被污染和干净的 patch;而对抗扰动恰恰是局部且空间结构化的,几个关键 patch 能先瓦解区域语义、再拖垮全局表现。
模块亮点
- 三粒度专家互补:全局专家聚合整图上下文,中心专家专注中央区域,区域专家各管一块空间分区,直接替换 ViT 块里的标准 FFN,补上区域级归纳偏置
- 注意力引导门控:AEA 复用块内自注意力图,把各区域 patch 注意力聚合成得分加权区域专家(P2R),再按原位置散回(R2P),不引入额外参数;DeiT-T / CIFAR-10 门控消融中 AA 48.93,高于均匀门控的 46.73
- 涨点实代价小:CIFAR-10 + SAT 下 DeiT-S 的 AA 从 47.47% 提到 50.16%;ViT-S 上 FLOPs 仅从 4.69G 到 4.70G
适用场景
领域为 ViT 对抗鲁棒性 / 图像分类;原文在 CIFAR-10、ImageNet 上用 SAT、TRADES 训练,验证了 FGSM、PGD、AutoAttack 攻击下的鲁棒性;也可迁移到分类、检测等 ViT 类骨干任务。
插入位置建议
- 直接替换 ViT / DeiT Transformer 块中的标准 FFN,把块内自注意力图传给 AEA 做区域门控
- 按原文默认插在第 6 层和第 10 层,消融显示中层位置最稳
- 配合 SAT / TRADES 对抗训练,联合区域自适应对抗损失与区域对齐损失一起优化
适用任务
- ViT 对抗鲁棒性
- 图像分类
完整代码
remoe.py
"""07_ReMoE_CVPR2026: 官方核心模块的单文件提取。
官方源码: https://github.com/zhongskr0114/ReMoE/blob/d7b6af2a6cfba29766b70e9d513e4847701de9af/model_for_cifar/vit.py
源码 SHA256: ec8c342dd2cdfdb79d0c2315ee16883326f977599bbc11728c33dee2f60677ed
提取核心: ProjectedExpert, Mlp_, Attention_
整理说明: 保留区域专家、中心专家、共享专家及注意力引导门控。移除强制 CUDA,临时张量跟随输入;源码 token_len 用于区域划分,实际应传空间 token 数64,而输入另含 CLS 为65。需要对应注意力权重,不能仅随机路由替代。
形状验证只说明接口可用,不代表已复现论文指标。初始化/辅助输入遵循原仓库;
需要语义特征、掩码、时间等条件的模块不能省略对应条件。
"""
from __future__ import annotations
import torch
from torch import nn
import torch.nn.functional as F
import math
from timm.layers import Mlp
class ProjectedExpert(nn.Module):
def __init__(self, n_tokens, dim_in, dim_proj, bottle_ratio, dim_out, act_layer=nn.GELU, drop=0.0):
super().__init__()
self.n_tokens = n_tokens
self.dim_in = dim_in
self.dim_proj = dim_proj
self.dim_out = dim_out
self.token_down = nn.Linear(dim_in, dim_proj)
self.expert = nn.Sequential(nn.Linear(dim_proj * n_tokens, int(dim_proj * n_tokens * bottle_ratio)), act_layer(), nn.Dropout(drop), nn.Linear(int(dim_proj * n_tokens * bottle_ratio), dim_proj * n_tokens), nn.Dropout(drop))
self.token_up = nn.Linear(dim_proj, dim_out)
def forward(self, x):
B = x.size(0)
x = self.token_down(x)
x = x.view(B, self.n_tokens * self.dim_proj)
x = self.expert(x)
x = x.view(B, self.n_tokens, self.dim_proj)
x = self.token_up(x)
return x
class Mlp_(nn.Module):
def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.0, region_num=4, token_len=65, region_method='rect', experts_num=8, attn=None, center_filt_circle=2, attn_pooling='max', pre_softmax=False, guide_rate=0.5, shift_region=False, add_rate=None):
super().__init__()
self.region_num = region_num
self.experts_num = experts_num
self.token_len = token_len
self.region_method = region_method
self.region_weights = None
self.shift_region_weights = None
self.out_features = out_features or in_features
self.hidden_features = hidden_features or in_features
self.attn_pooling = attn_pooling
self.pre_softmax = pre_softmax
self.guide_rate = guide_rate
self.shift_region = shift_region
self.add_rate = add_rate
self.spatial_len = token_len - 1
self.grid_size = int(math.sqrt(self.spatial_len))
self.bottle_ratio = 0.1
proj_dim = int(in_features * 0.1)
self.shared_expert = Mlp(in_features, hidden_features, out_features, act_layer=act_layer, drop=drop)
self.attn = attn
self.region_with_tokens = self.token_len // self.region_num
self.region_experts = nn.ModuleList([ProjectedExpert(n_tokens=self.region_with_tokens, dim_in=in_features, dim_proj=proj_dim, bottle_ratio=self.bottle_ratio, dim_out=self.out_features, act_layer=act_layer, drop=drop) for _ in range(self.region_num)])
if self.shift_region:
self.shift_region_experts = nn.ModuleList([Mlp(in_features * self.region_with_tokens, int(in_features * self.region_with_tokens * self.bottle_ratio), self.out_features * self.region_with_tokens, act_layer, drop) for _ in range(region_num)])
def calculate_center_indices_count(token_num, center_filt_circle):
root = math.sqrt(token_num)
if int(root + 0.5) ** 2 != token_num:
raise ValueError('token_num 必须是可平方数')
side_length = int(root)
if 2 * center_filt_circle >= side_length:
raise ValueError('过滤圈数太多,没有中间区域了')
middle_side_length = side_length - 2 * center_filt_circle
return middle_side_length ** 2
self.center_in_num = calculate_center_indices_count(token_len, center_filt_circle)
self.center_expert = ProjectedExpert(n_tokens=self.center_in_num, dim_in=in_features, dim_proj=proj_dim, bottle_ratio=self.bottle_ratio, dim_out=self.out_features, act_layer=act_layer, drop=drop)
def _split_rectangle(self, token_num, region_num) -> torch.Tensor:
"""生成区域索引张量,形状为 (num_region, region_h, region_w)"""
root = math.sqrt(token_num)
if int(root + 0.5) ** 2 != token_num:
raise ValueError('token_num 必须是可平方数')
if token_num % region_num != 0:
raise ValueError('token_num 必须能被 region_num 整除')
side_length = int(math.sqrt(token_num))
sub_side_length = int(math.sqrt(token_num / region_num))
result = []
for i in range(0, side_length, sub_side_length):
for j in range(0, side_length, sub_side_length):
region = []
for x in range(i, i + sub_side_length):
for y in range(j, j + sub_side_length):
region.append(x * side_length + y)
result.append(region)
return result
def split_features(self, x, region_indices):
"""
按照 region_indices 将特征分组为若干 region,但不拼接 token。
:param x: 输入特征,形状为 (B, L, C)
:param region_indices: list[list[int]],每个子列表表示一个区域内的 token 索引
:return: 合并后的特征,形状为 (B, region_num, tokens_per_region, C)
"""
B, L, C = x.shape
region_features = []
for indices in region_indices:
selected = x[:, indices, :]
region_features.append(selected)
new_x = torch.stack(region_features, dim=1)
return new_x
def restore_original_order(self, region_output, regions, token_dim):
"""
将处理后的region_output恢复为原始token顺序
:param region_output: 区域处理后的输出,形状 [B, region_num, region_dim]
:param regions: 区域划分结果,形状 [region_num, tokens_per_region]
:param token_dim: 每个token的维度
:return: 恢复后的原始token顺序,形状 [B, token_num, token_dim]
"""
B, region_num, region_dim = region_output.shape
tokens_per_region = len(regions[0])
token_num = sum((len(r) for r in regions))
assert region_dim % tokens_per_region == 0, 'region_dim必须能被tokens_per_region整除'
assert region_dim // tokens_per_region == token_dim, '特征维度不匹配'
original_output = region_output.new_zeros(B, token_num, token_dim)
for region_idx, region in enumerate(regions):
region_features = region_output[:, region_idx, :]
split_features = region_features.reshape(B, tokens_per_region, token_dim)
for token_idx_in_region, original_pos in enumerate(region):
original_output[:, original_pos, :] = split_features[:, token_idx_in_region, :]
return original_output
def process_regions(self):
small_region_num = 16
region_num = 4
ori_small_regions = self._split_rectangle(token_num=self.token_len, region_num=small_region_num)
adjusted_indices = [5, 6, 9, 10, 7, 4, 11, 8, 13, 14, 15, 12, 0, 1, 2, 3]
final_regions = []
for i in range(0, len(adjusted_indices), 4):
combined_region = []
for idx in adjusted_indices[i:i + 4]:
combined_region.extend(ori_small_regions[idx])
final_regions.append(combined_region)
return torch.tensor(final_regions)
def filter_middle_tokens(self, token_num, filt_circle):
"""
过滤掉边缘的 token,只保留中间区域的 token
:param token_num: 输入的 token 数量,必须是可平方数
:param filt_circle: 过滤掉的边缘圈数
:return: 中间区域的 token 列表
"""
root = math.sqrt(token_num)
if int(root + 0.5) ** 2 != token_num:
raise ValueError('token_num 必须是可平方数')
side_length = int(root)
start = filt_circle
end = side_length - filt_circle
middle_tokens = []
for i in range(start, end):
for j in range(start, end):
index = i * side_length + j
middle_tokens.append(index)
return middle_tokens
def select_center_features(self, x, center_indices):
"""
从输入张量 x 中选取中间区域的特征,不再拼接,直接返回 (B, C, dim)
:param x: 输入张量,形状为 (B, L, dim)
:param center_indices: 中间区域的索引列表
:return: 选取后的特征张量,形状为 (B, C, dim)
"""
selected_features = x[:, center_indices, :]
return selected_features
def restore_with_zeros(self, processed_center_token, center_indices, original_token_num):
"""
将处理后的 center token 按原始顺序恢复,并补齐未使用的 token 为零向量
:param processed_center_token: 处理后的 center_token,形状为 (B, C, token_dim)
:param center_indices: 提取的 token 索引列表
:param original_token_num: 原始 token 数量
:return: 恢复后的完整 token 序列,形状为 (B, original_token_num, token_dim)
"""
B, C, token_dim = processed_center_token.shape
restored_tokens = torch.zeros(B, original_token_num, token_dim, device=processed_center_token.device, dtype=processed_center_token.dtype)
for i, idx in enumerate(center_indices):
restored_tokens[:, idx, :] = processed_center_token[:, i, :]
return restored_tokens
def forward(self, x, guide_weights=None, shift_guide_weights=None):
"""
'eval':
"""
original_x = x
cls_token = x[:, :1, :]
x = x[:, 1:, :]
B, L, C = x.shape
'\n 1. 共享专家: token直接过\n '
shared_output = self.shared_expert(x)
shared_cls = self.shared_expert(cls_token)
"\n 2. 区域专家:\n (1) 获得每个区域的token索引region_indices\n (2) 按region_indices将n个token concat 为region_num个region_token\n (3) 根据region_indices和attn获得region_weights\n (4) 将region_token分别过对应的region expert,并乘region_weights=>region_token'\n (5) region_token'再拆分回token并按原来的顺序排好\n "
region_indices = self._split_rectangle(self.token_len, self.region_num)
self.region_indices = region_indices
region_x = self.split_features(x, region_indices)
if self.pre_softmax:
attn = self.attn.get_attn()[1]
else:
attn = self.attn.get_attn()[0]
attn_mean = attn.mean(dim=1)
C = attn_mean.mean(dim=1)
C = C[:, 1:]
region_means = x.new_zeros(B, self.region_num)
for i, indices in enumerate(region_indices):
region_C = C[:, indices]
region_C = torch.clamp(region_C, min=-1000000000.0, max=1000000000.0)
region_C = region_C.nan_to_num()
if self.attn_pooling == 'mean':
region_mean = torch.mean(region_C, dim=1)
else:
region_mean = torch.max(region_C, dim=1).values
region_means[:, i] = region_mean
if guide_weights == None:
if not self.pre_softmax:
region_weights = F.softmax(region_means, dim=-1)
else:
region_weights = F.softmax(region_means / 0.005, dim=-1)
self.region_weights = region_weights
else:
if not self.pre_softmax:
region_weights = F.softmax((1 - self.guide_rate) * region_means + self.guide_rate * guide_weights, dim=-1)
else:
region_weights = (1 - self.guide_rate) * region_means + self.guide_rate * guide_weights
self.region_weights = region_weights
B, region_num, _, o = region_x.shape
region_output = []
for i in range(region_num):
current_region = region_x[:, i, :, :]
current_region_weight = region_weights[:, i].unsqueeze(1).unsqueeze(1)
expert_output = current_region_weight * self.region_experts[i](current_region)
region_output.append(expert_output)
region_output = torch.cat(region_output, dim=1)
"\n 3. center专家:\n (1)找出中心token并拼接为center_token (B, 1, out_features*center_in_num)\n (2)过center_expert (B, 1, out_features*center_in_num)\n (3)center_token' 拆分,且未参与的token补0 (B, L, out_features)\n "
if not self.shift_region:
center_indices = self.filter_middle_tokens(self.token_len, 2)
center_x = self.select_center_features(x, center_indices)
center_output = self.center_expert(center_x)
center_output = self.restore_with_zeros(center_output, center_indices, original_token_num=self.token_len)
if self.shift_region:
shift_region_indices = self.process_regions()
self.shift_region_indices = shift_region_indices
shift_region_x = self.merge_features(x, shift_region_indices)
shift_region_means = x.new_zeros(B, self.region_num)
for i, indices in enumerate(shift_region_indices):
shift_region_C = C[:, indices]
shift_region_C = torch.clamp(shift_region_C, min=-1000000000.0, max=1000000000.0)
shift_region_C = shift_region_C.nan_to_num()
if self.attn_pooling == 'mean':
shift_region_mean = torch.mean(shift_region_C, dim=1)
else:
shift_region_mean = torch.max(shift_region_C, dim=1).values
shift_region_means[:, i] = shift_region_mean
if shift_guide_weights == None:
if not self.pre_softmax:
shift_region_weights = F.softmax(shift_region_means, dim=-1)
else:
shift_region_weights = shift_region_means
self.shift_region_weights = shift_region_weights
else:
if not self.pre_softmax:
shift_region_weights = F.softmax((1 - self.guide_rate) * shift_region_means + self.guide_rate * shift_guide_weights, dim=-1)
else:
shift_region_weights = (1 - self.guide_rate) * shift_region_means + self.guide_rate * shift_guide_weights
self.shift_region_weights = shift_region_weights
B, region_num, _ = shift_region_x.shape
shift_region_output = []
shift_region_cls = x.new_zeros(B, 1, self.out_features * self.region_with_tokens)
for i in range(region_num):
current_region = shift_region_x[:, i, :]
current_region_weight = shift_region_weights[:, i].unsqueeze(1)
expert_output = current_region_weight * self.region_experts[i](current_region)
shift_region_cls = shift_region_cls + expert_output.unsqueeze(1)
shift_region_output.append(expert_output)
shift_region_output = torch.stack(shift_region_output, dim=1)
shift_region_cls = shift_region_cls
shift_region_output = self.restore_original_order(shift_region_output, shift_region_indices, token_dim=self.out_features)
cls = shared_cls
if self.shift_region:
s_output = shared_output + region_output + shift_region_output
else:
s_output = shared_output + region_output + center_output
output = torch.cat([cls, s_output], dim=1)
return output
def get_region_weights(self):
return self.region_weights
def get_shift_region_weights(self):
return self.shift_region_weights
class Attention_(nn.Module):
def __init__(self, dim, num_heads=8, qkv_bias=False, attn_drop=0.0, proj_drop=0.0):
super().__init__()
self.num_heads = num_heads
head_dim = dim // num_heads
self.scale = head_dim ** (-0.5)
self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
self.attn_drop = nn.Dropout(attn_drop)
self.proj = nn.Linear(dim, dim)
self.proj_drop = nn.Dropout(proj_drop)
self.v_mask = nn.Identity()
self.attn = None
self.pre_attn = None
def forward(self, x):
B, N, C = x.shape
qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
q, k, v = (qkv[0], qkv[1], qkv[2])
v = self.v_mask(v)
attn = q @ k.transpose(-2, -1) * self.scale
self.pre_attn = attn
attn = attn.softmax(dim=-1)
self.attn = attn
attn = self.attn_drop(attn)
x = (attn @ v).transpose(1, 2).reshape(B, N, C)
x = self.proj(x)
x = self.proj_drop(x)
return x
def get_attn(self):
return (self.pre_attn, self.attn)
def main():
"""最小使用示例:创建模块,验证输入与输出形状。"""
torch.manual_seed(0)
attention = Attention_(dim=32,num_heads=4)
module = Mlp_(32,hidden_features=64,out_features=32,token_len=64,region_num=4,attn=attention,center_filt_circle=2)
input = torch.randn(2,65,32)
attention(input)
output = module(input)
assert input.shape == output.shape, (input.shape, output.shape)
assert torch.isfinite(output).all(), "output contains NaN/Inf"
print("input shape:", tuple(input.shape))
print("output shape:", tuple(output.shape))
return module, input, output
if __name__ == "__main__":
main()
环境与依赖
Python 3.9+
继续浏览
下一篇RepHMS 重参数化异构多尺度模块异构大小核并行:同一层内同时处理大核与多个小核卷积,横向扩感受野又保小目标细节;配合 GHFKS 分层选核(骨干核尺寸逐层递增、颈部引入 5、7、9 大核),纵向捕获跨空间层级上下文相关资源
模块2026-11-20
IQPIR 图像质量先验条件模块
分数即条件,免改结构:用预训练 NR-IQA 模型给图像打质量分,分数离散化后经 Embedding 变成与特征图同尺寸的向量相加,再送入码预测 Transformer;推理时把分数拉满即输出最高感知质量,无需改结构
计算机视觉图像复原IQPIR
计算机视觉MIT
模块2026-11-20
AFW 自适应帧加权模块
按质量给帧打分:对每一帧特征估计"帧质量",经 Softmax 得到权重,动态突出信息量大的帧、压低模糊 / 遮挡帧
计算机视觉姿态估计AFW
计算机视觉MIT
模块2026-11-20
Agent Attention 代理注意力
代理聚合广播:在 (Q,K,V) 之外引入少量 Agent token,先代理 Query 从 K、V 聚合全局信息,再广播回每个 Query,兼得 Softmax 表达力与线性复杂度
计算机视觉注意力机制AgentAttention
计算机视觉MIT