学术
模块更新于 2026-11-21· 浏览 1· 下载 1

MRBlock 流形残差模块

把线性层改成几何锚点加低秩残差的 MR 块,在少样本全切片分类中保持病理基础模型特征的低维流形结构。

医学影像医学影像全切片图像少样本MIL流形学习ICLR2026MRBlock

结构图

MRBlock 流形残差模块结构图
MRBlock 流形残差模块结构图

把线性层改成几何锚点加低秩残差的 MR 块,在少样本全切片分类中保持病理基础模型特征的低维流形结构。

论文信息

  • 论文:Exploiting Low-Dimensional Manifold of Features for Few-Shot Whole Slide Image Classification
  • 出处:ICLR 2026

核心痛点

少样本全切片图像分类容易过拟合,根源之一是 MIL 模型里的线性层会扭曲病理基础模型特征的低维流形几何。

模块亮点

  • 双路径解耦:固定随机矩阵作几何锚点,保留拓扑并锐化频谱;可训练低秩残差路径负责任务适配。
  • 低秩瓶颈显式镜像特征的有效低秩结构,把学习任务简化为残差拟合,参数更少。
  • 在多个少样本 WSI 基准上以更少参数取得 SOTA,可直接替换 MIL/Transformer 中的线性层。

适用场景

适合病理全切片图像的少样本分类与 MIL 模型,也可用于其他依赖预训练特征几何结构的参数高效适配。

插入位置建议

  • 替换 MIL/ABMIL/Transformer 中的线性投影层,保持输入输出维度一致;两条路径相加。
  • 接入时核对低秩瓶颈与特征有效秩,固定随机矩阵按原配置初始化。

适用任务

  • 少样本 WSI 分类
  • 病理 MIL
  • 特征几何保持

完整代码

mrblock.py
"""150_MRBlock_ICLR2026: 官方核心模块的单文件提取。

官方源码: https://github.com/BearCleverProud/MR-Block/blob/a71fb28262fdb9aa61265c86c3978080c07ac966/models/mr_block.py
源码 SHA256: 202f0546633fb75069440ee684acbb95db5ab0e7aa88af99578339dd00212739
提取核心: LowRankResidualPath, ManifoldResidualBlock, replace_linear
整理说明: 完整保留官方低秩非线性残差路径及线性层替换函数。main 关闭权重合并:GELU 非线性残差无法等价合并为单一线性权重,直接使用非合并前向。
形状验证只说明接口可用,不代表已复现论文指标。初始化/辅助输入遵循原仓库;
需要语义特征、掩码、时间等条件的模块不能省略对应条件。
"""
from __future__ import annotations

# Upstream repository license: LICENSE
# MIT License
# 
# Copyright (c) 2026 Conghao Xiong
# 
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# 
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
# 
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import torch
from torch import nn
import torch.nn.functional as F
import math


class LowRankResidualPath(nn.Module):

    def __init__(self, in_features, out_features, rank, alpha=1, dropout=0.0):
        super().__init__()
        self.rank = rank
        self.scaling = alpha / rank
        self.dropout = nn.Dropout(p=dropout) if dropout > 0.0 else lambda x: x
        self.down_projection = nn.Parameter(torch.zeros(rank, in_features))
        self.up_projection = nn.Parameter(torch.zeros(out_features, rank))
        self.activation = nn.GELU()

    def reset_parameters(self):
        nn.init.kaiming_uniform_(self.down_projection, a=math.sqrt(5))
        nn.init.zeros_(self.up_projection)

    def forward(self, x):
        hidden = self.dropout(x) @ self.down_projection.transpose(0, 1)
        hidden = self.activation(hidden)
        return hidden @ self.up_projection.transpose(0, 1) * self.scaling

    def delta_weight(self):
        return self.up_projection @ self.down_projection * self.scaling


class ManifoldResidualBlock(nn.Linear):

    def __init__(self, in_features, out_features, rank=0, residual_alpha=1, residual_dropout=0.0, fan_in_fan_out=False, merge_weights=True, **kwargs):
        nn.Linear.__init__(self, in_features, out_features, **kwargs)
        self.rank = rank
        self.fan_in_fan_out = fan_in_fan_out
        self.merge_weights = merge_weights
        self.merged = False
        if rank > 0:
            self.residual_path = LowRankResidualPath(in_features, out_features, rank, alpha=residual_alpha, dropout=residual_dropout)
            self.weight.requires_grad = False
        self.reset_parameters()
        if fan_in_fan_out:
            self.weight.data = self.weight.data.transpose(0, 1)

    def reset_parameters(self):
        nn.Linear.reset_parameters(self)
        if hasattr(self, 'residual_path'):
            self.residual_path.reset_parameters()

    def _weight_view(self, weight):
        return weight.transpose(0, 1) if self.fan_in_fan_out else weight

    def train(self, mode: bool=True):
        nn.Linear.train(self, mode)
        if mode:
            if self.merge_weights and self.merged:
                if self.rank > 0:
                    self.weight.data -= self._weight_view(self.residual_path.delta_weight())
                self.merged = False
        elif self.merge_weights and (not self.merged):
            if self.rank > 0:
                self.weight.data += self._weight_view(self.residual_path.delta_weight())
            self.merged = True
        return self

    def forward(self, x: torch.Tensor):
        result = F.linear(x, self._weight_view(self.weight), bias=self.bias)
        if self.rank > 0 and (not self.merged):
            result = result + self.residual_path(x)
        return result


def replace_linear(module, path, rank=64, residual_alpha=1, residual_dropout=0.0):
    parent_path, child_name = path.rsplit('.', 1) if '.' in path else ('', path)
    parent = module.get_submodule(parent_path) if parent_path else module
    linear = parent._modules[child_name]
    if not isinstance(linear, nn.Linear):
        raise TypeError(f'{path} is {type(linear).__name__}, expected nn.Linear')
    replacement = ManifoldResidualBlock(linear.in_features, linear.out_features, rank=rank, residual_alpha=residual_alpha, residual_dropout=residual_dropout, bias=linear.bias is not None)
    replacement = replacement.to(device=linear.weight.device, dtype=linear.weight.dtype)
    with torch.no_grad():
        replacement.weight.copy_(linear.weight)
        if linear.bias is not None:
            replacement.bias.copy_(linear.bias)
    if replacement.bias is not None:
        replacement.bias.requires_grad = linear.bias.requires_grad
    parent._modules[child_name] = replacement


def main():
    """最小使用示例:创建模块,验证输入与输出形状。"""
    torch.manual_seed(0)
    module = ManifoldResidualBlock(32, 32, rank=8, merge_weights=False)
    input = torch.randn(2, 16, 32)
    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+

继续浏览

下一篇MSCA 多尺度交叉轴注意力原理创新:双平行轴向注意力分支做跨轴交互,融合多尺寸条状1D卷积编码多尺度空间信息,全局建模能力远优于普通轴向注意力。

相关资源