Explore / Programming 分析一下:class LinearAttention(nn.Module): def init(self, dim): super(LinearAttention,… Save Share Download ▾ ReportJump to turn (29) 1 分析一下:class LinearAttention(nn.Module): def init(self, dim): super(LinearAttentio 2 分析一下当前的操作中,注意力机制引入的计算量。 3 那么就不要这个注意力 4 你知道PINN吗? 5 那么PINN在目标跟踪任务中能用吗?可以 解决什么问题? 6 PINN可以和vision Mamba或者CNN结合吗? 7 模型是:# Copyright (c) 2015-present, Facebook, Inc. All rights reserved. import tor 8 模型的Loss设计为:from . import BaseActor from lib.utils.misc import NestedTensor from 9 综上,分析一下PINN可以集成在什么位置?起到什么作用? 10 给出结合PINN的代码 11 分析一下当前双模态网络存在什么问题?在交互中,还可以增加什么操作?当前的双模态是互补的。 12 分析一下当前双模态交互中存在的问题是什么? 13 分析一下# -------------------------------------------------------------------------- 14 那么在# Copyright (c) 2015-present, Facebook, Inc. All rights reserved. import torc 15 那么在VisionMamba模型中,增加StateFusion 和 StructureAwareSSM 组件,可以先增加一个,给出代码 16 把forwardfeatures部分写全 17 这是原始的def forwardfeatures(self, z, x, inferenceparams=None, ifrandomclstokenposit 18 当前在x = self.hinblock(x) z = self.hinblock(z) x = self.patchembed(x) #x.shape = t 19 那么statefusion呢 20 这里存在的问题是 hinblock 和 stateFusion两个模块的作用是否重复了? 21 那么stateFusion是否能集成在mambaBlock中? 22 把 def forward( self, hiddenstates: Tensor, residual: Optional[Tensor] = None, in 23 但是当前shape是(20,320,384) 24 但是320开方不整 25 那么StructureAwareSSM模块呢,是否能集成进来,作用是什么? 26 我们想在crossMamba处进行创新设计,对于双模态特征交互,还可以如何设计? 27 那么分别给出上述建议对应的代码 28 这里的层次式特征融合是什么原理 29 那么将HierarchicalFeatureFusion集成到import math import torch import torch.nn as nn im 分析一下:class LinearAttention(nn.Module):
def init (self, dim):
super(LinearAttention, self).init ()
self.query_proj = nn.Linear(dim, dim)
self.key_proj = nn.Linear(dim, dim)
self.value_proj = nn.Linear(dim, dim)
self.softmax = nn.Softmax(dim=-1)
code Copy code
def forward(self, x):
B, N, C = x.size() # B: batch size, N: sequence length, C: channels
# Linear projections
queries = self.query_proj(x) # B, N, C
keys = self.key_proj(x) # B, N, C
values = self.value_proj(x) # B, N, C
# Softmax over the last dimension (keys)
keys = self.softmax(keys)
# Compute linear attention
keys_T = keys.transpose(1, 2) # B, C, N
attention = torch.bmm(queries, keys_T) # B, N, N
out = torch.bmm(attention, values) # B, N, C
return out
Show full message · 44 lines Copy first prompt Copy first response
Details
Provider OpenAI
Model provenance As recorded by source dataset
Turns 29 (58 messages)
Language zh
Conversation date Nov 13, 2024
Added to archive Nov 16, 2026
ID 01m7h428gzahzce82jvbxwzrqjSource & license Imported from WildChat-4.8M (AI2) (source ). Imported records earn no Research Points.
Upstream record: e892a7d2f6617a42ea28fb3ba876d965
Zhao et al., WildChat: 1M ChatGPT Interaction Logs in the Wild (ICLR 2024). Contains information from WildChat-4.8M, made available under the ODC Attribution License.
License: ODC-BY-1.0
class CrossMamba(nn.Module):
def init (self, dim):
super(CrossMamba, self).init ()
self.cross_mamba = Mamba(dim, bimamba_type="v3")
self.norm1 = nn.LayerNorm(dim)
self.norm2 = nn.LayerNorm(dim)
self.attention = LinearAttention(dim)
self.compress_layer = nn.Linear(2 * dim, dim)
code Copy code
def forward(self, m1, m1_resi, m2):
m1_resi = m1 + m1_resi
m1_att = self.attention(m1_resi)
m2_att = self.attention(m2)
combined_feat = torch.cat([m1_att, m2_att], dim=-1) # B, N, 2*C
global_f = self.compress_layer(combined_feat) # B, N, C
global_f = self.cross_mamba(global_f, extra_emb=m2)
global_f = self.norm1(global_f)
return global_f中,讨论一下包含的操作有哪些?
Assistant2024-11-13 08:00 UTC Copy response
这个代码片段定义了两个神经网络模块 LinearAttention 和 CrossMamba,它们涉及了一些常见的深度学习操作,尤其是在处理序列和注意力机制时。下面我将逐步分析这两个类和它们包含的操作。
LinearAttention 类
初始化操作 :
三个线性层(query_proj, key_proj, value_proj),用于将输入向量映射到查询、键和值的表示。
一个 Softmax 层,用来对键进行归一化操作。
前向传播操作 :
输入 x 的大小为 (B, N, C):
B 是批量大小(batch size)。
N 是序列长度。
C 是特征的通道数。
使用线性层对输入向量投影以获得 queries, keys, 和 values。
对 keys 进行 Softmax 归一化,得到的结果维持在最后一个维度。
将 keys 转置以便于后续的批量矩阵乘法(torch.bmm)。
执行两次批量矩阵乘法:第一次 torch.bmm(queries, keys_T) 计算注意力权重,第二次 torch.bmm(attention, values) 得出注意力后的输出。
CrossMamba 类
初始化操作 :
从 Mamba 类初始化一个 cross_mamba 的实例,注意这里的 bimamba_type="v3" 显示了某种配置选项。
两个层归一化层(norm1, norm2),用于标准化每个特征维度来减小不同批次间的偏差。
一个 LinearAttention 实例。
一个线性压缩层(compress_layer),用于将维度从 2 * dim 压缩到 dim。
前向传播操作 :
根据残差连接原则,先对 m1_resi 和 m1 加和以形成一个新的输入。
对 m1_resi 和 m2 通过 LinearAttention 分别计算注意力输出。
将两个注意力结果沿着最后一个维度进行连接(torch.cat),形成一个更大的特征表示。
使用压缩层将连接后的特征降维。
通过 cross_mamba 进行进一步处理,并传入 extra_emb=m2。
最后,对生成的特征进行归一化。
总结一下,这个设计涉及了许多深度学习中常用的技术,如注意力机制(LinearAttention), 残差连接, 特征合并与压缩(compress_layer),以及标准化(LayerNorm)。这些操作共同作用,用于处理特定输入的特征,生成复杂的输出表示。
Assistant2024-11-13 08:01 UTC Copy response
在分析 LinearAttention 和 CrossMamba 中的注意力机制引入的计算量之前,我们需要明确涉及的矩阵操作及它们的计算复杂度。
LinearAttention中的计算量
LinearAttention 类中主要的计算操作包括:
线性投影 :
对每个 query_proj, key_proj, value_proj 进行线性变换。每个变换的复杂度为 (O(B \times N \times C^2)),因为要为每个输入向量(有 N 个)应用一个 (C \times C) 的变换矩阵。
Softmax :
对每个 keys 的向量进行 Softmax 操作,复杂度为 (O(B \times N \times C))。
矩阵转置 :
将 keys 转换为 keys_T,该操作主要是重排维度,一般不涉及大量计算,因此计算量是可以忽略的。
注意力计算 :
通过批量矩阵乘法 torch.bmm(queries, keys_T) 计算注意力权重,复杂度为 (O(B \times N \times C \times N))。
接下来一次矩阵乘法 torch.bmm(attention, values),复杂度也为 (O(B \times N \times N \times C))。
总结,LinearAttention 的总计算量主要由线性投影和两次矩阵乘法决定,其复杂度为 (O(B \times N \times C^2 + B \times N^2 \times C))。
CrossMamba中的计算量
CrossMamba 中与注意力机制相关的计算主要集中在对 m1_resi 和 m2 的两次 LinearAttention 调用上:
Attention计算 :
每个 LinearAttention 调用本身的复杂度已经分析为 (O(B \times N \times C^2 + B \times N^2 \times C))。
因为在 CrossMamba 中对 m1_resi 和 m2 分别调用了两次 LinearAttention,所以注意力机制相关的操作总复杂度相比一个 LinearAttention 多了一倍。
特征合并和压缩 :
torch.cat 操作的计算量较低,属于维度操作,不会明显增加复杂度。
随后的线性层 compress_layer,计算复杂度为 (O(B \times N \times 2C \times C)),即 (O(B \times N \times C^2))。
因此,CrossMamba 中注意力机制特别是 LinearAttention 的两次调用,占据了大部分的计算开销。当输入序列长度 N 很大时,注意力机制的计算复杂度主要受 (N) 的平方项影响,即 (O(B \times N^2 \times C)),这在长序列中可能会导致计算瓶颈。
优化这部分注意力计算可能需要考虑如何减少 N^2 的依赖,比如通过稀疏矩阵或低秩近似等技术。
Assistant2024-11-13 08:01 UTC Copy response
如果不想使用注意力机制,有几种替代方法可以处理序列数据或特征交互,根据具体问题的需求和架构的不同,这些方法可能会更高效或更适合你的应用场景:
1. 全连接层
替代注意力机制,可使用一个或多个全连接层(MLP)来直接处理输入数据的上下文交互。这种方法简单直接,但可能无法捕捉长距离的依赖关系。
2. 卷积神经网络(CNN)
CNN 可以用来提取序列或特征中的局部模式,适合于捕捉短程依赖。
一维卷积能够处理序列数据,通过堆叠多层卷积可以捕捉不同规模的特征。
3. 循环神经网络(RNN)
RNN 和其变种(如 LSTM、GRU)专为序列数据设计,适合处理时间序列或需要捕捉长程依赖的任务。
相比于注意力机制,RNN 的计算复杂度对序列长度更友好(理论上是线性的)。
4. 自回归模型
自回归模型根据历史输入预测当前输出,也可以应用于一些序列预测问题。
5. 聚合和池化操作
通过池化层对特征进行聚合(如最大池化或平均池化),减少元素维度,简化信息,并保留关键特征。
6. 使用预训练特征
如果可以接受用预训练模型提取特征,再在这些特征上进行简单操作(如线性层),这可能简化整体模型。
7. 图神经网络(GNN)
如果数据具备图结构或需要表达复杂的节点之间关系,GNN 可以是一种选择。
使用上述方法时,需要根据应用的具体需求和数据特征权衡。例如,RNN 和 CNN 很适合时间序列或自然语言数据,而全连接层可能适合一些非序列型特征的简单组合。去掉注意力机制后,模型的复杂性和功能性可能会有所降低,但在处理长序列时能显著减少计算量。
Assistant2024-11-13 08:03 UTC Copy response
是的,PINN(Physics-Informed Neural Networks)是一种融合物理知识与神经网络的方法,用于求解偏微分方程(PDE)和其他涉及物理约束的问题。PINN 的基本思想是在神经网络的训练过程中,除了数据驱动的损失,还引入物理方程的约束,从而更好地预测和模拟物理现象。这里是一些细节:
核心思想
联合损失函数 :
PINN 同时考虑了数据损失和物理约束损失。通常的神经网络仅通过最小化数据误差(如均方误差)来训练,而在 PINN 中,还会将偏微分方程的残差加入到损失函数中。
自动差分 :
PINN 利用自动微分技术来计算神经网络输出的导数,从而构建用于物理约束的残差损失。这对于高维度和复杂方程特别有用。
逼近偏微分方程 :
通过训练,网络不断调整以逼近满足物理约束(如连续性方程、动量方程等)的解。在应用中,PINN 可以用于求解各种条件下的 PDE,包括边界值问题、初值问题等。
应用
PINN 被广泛应用于流体力学、热传导、电磁学、生物力学等领域,解决常见 PDE 所描述的物理问题。
在科学计算中,PINN 能够提供一种相对简单但有效的替代方法,与传统的数值求解方法(如有限元素法、有限差分法)进行互补。
优势与挑战
优势 :
物理一致性 :由于将物理约束直接嵌入训练过程,网络输出通常更符合物理规律。
较少数据依赖 :相比于纯数据驱动的方法,PINN 可以在数据稀缺的条件下依然有效,因为它利用了物理信息。
通用性 :通过改变物理约束条件,PINN 可以自然地适应不同的物理问题。
挑战 :
训练难度 :物理损失的引入可能导致训练过程收敛缓慢,网络需要能够处理复杂的多任务训练。
复杂性 :对于某些高度复杂的问题,设计合适的网络架构和损失函数是一个挑战。
计算效率 :在高维问题中,自动微分的计算成本可能很高。
总的来说,PINN 代表了一种融合物理模型与数据模型的新范式,为许多科学和工程领域的难题提供了新思路。
那么PINN在目标跟踪任务中能用吗?可以 解决什么问题?
Assistant2024-11-13 08:04 UTC Copy response
将 Physics-Informed Neural Networks (PINNs) 应用于目标跟踪任务是一种创新的思路。目标跟踪领域主要关注在视频或传感器数据中定位和跟踪运动物体。虽然传统上 PINNs 是用于求解与物理相关约束的问题,但它们在目标跟踪中仍然有潜在应用,尤其是在以下场景和问题中:
应用场景
动态建模 :
如果跟踪的目标涉及复杂的物理运动(如弹道运动或流体动力学),PINN 可以集成这些运动学或动力学方程以提供物理一致的轨迹预测。
应用在需要精确理解物体如何在物理环境中交互的场景中。
多传感器数据融合 :
将物理模型与通过多个传感器获取的数据整合,增强对环境的理解和目标轨迹的持续跟踪,比如在自动驾驶应用中结合 LIDAR、雷达和摄像头数据。
环境中的物理限制 :
在有明显物理限制的环境中(如水下或空中),目标的运动受到特定的物理约束,PINN 可以利用这些约束来提高跟踪精度和鲁棒性。
边缘条件或事件检测 :
一些目标可能触发特定物理事件(如碰撞、弹跳),PINN 可以用于捕捉这些事件并更新跟踪状态,以提供更及时的响应。
解决的问题
鲁棒性提高 :
利用物理约束来增强神经网络对于杂波和噪声数据的鲁棒性,提高跟踪精度。
少样本学习 :
通过嵌入物理模型,可以在数据不足的情况下实现有效的目标跟踪,因为部分信息由物理模型提供。
轨迹预测 :
更准确地预测目标的未来位置,尤其是在物体运动符合特定动力学时,PINN 可以利用这些动力学方程进行短期或长期预测。
优化计算资源 :
在边缘计算环境或实时系统中,物理模型可以起到约束搜索空间的作用,减少计算复杂度,提高效率。
挑战
模型复杂性 :构建能准确描述目标物理行为的模型,可能需要较高的领域知识和复杂的模型设计。
实时性要求 :在实时性要求极高的应用中,PINN 的计算负担可能较重,需要优化。
数据集成 :如何有效集成数据驱动的组件和物理模型,且在变化的环境中维持良好性能。
总的来说,尽管 PINN 原本并不专注于目标跟踪,但其引入物理约束的特性,确实能够在复杂动态环境中提供许多潜在的优势。研究如何将其与传统跟踪方法结合将是一条有趣的发展途径。
PINN可以和vision Mamba或者CNN结合吗?
Assistant2024-11-13 08:04 UTC Copy response
是的,Physics-Informed Neural Networks (PINNs) 可以与 Vision Transformers(如 Vision Mamba)或卷积神经网络(CNN)结合,以解决涉及物理约束的复杂视觉问题。这样的结合能够充分利用不同技术的优势,从而增强模型的功能性和适用性。
结合方法
特征提取与物理约束结合 :
使用 CNN 或 Vision Mamba 提取丰富的图像或视频帧特征。这些特征可以为物理建模提供高层次的信息。
将提取的特征作为输入,传递到 PINN 中处理。这允许物理约束在高维特征空间内引导和调整模型的行为。
多任务学习 :
将视觉任务(如分类、检测)与物理任务(如预测运动轨迹、模拟物理现象)共同建模。通过多任务学习,可以在一个网络内同时优化这两种任务。
共享权重或交叉损失函数是这类组合策略的常见方法。
端到端训练 :
构建一个端到端的模型框架,使用 CNN 或 Vision Mamba 先处理视觉信号,并通过 PINN 集成物理约束进行后续计算。
这种设计允许在一个连续的训练流程中同时优化视觉和物理模块。
融合层设计 :
在视觉模型的输出和 PINN 的输入之间,设计融合层以确保视觉信息和物理信息的有效交互。这可能涉及一些定制的神经网络层或算子。
应用场景
物理事件检测 :在需要物理事件识别的场景(如抓取、碰撞检测)中,结合视觉信息和物理模型可以提高检测的准确性。
运动和行为预测 :对运动中的物体进行视觉跟踪,并整合物理方程预测其行为和轨迹变化。
科学计算与工程应用 :在涉及复杂几何和物理环境的应用(如医学影像、结构分析)中,融合模型可以用来准确捕捉和模拟物理动态。
面临的挑战
总体而言,将 PINN 与 CNN 或 Vision Mamba 结合,可以用来解决很多具有物理属性的视觉问题。这种结合能够利用视觉模型的高效特征提取能力和物理模型的约束能力,从而构建功能更为强大的混合模型。
模型是:# Copyright (c) 2015-present, Facebook, Inc.
All rights reserved.
import torch
import torch.nn as nn
from functools import partial
from torch import Tensor
from typing import Optional
from timm.models.vision_transformer import VisionTransformer, cfg
from timm.models.registry import register_model
from timm.models.layers import trunc_normal , lecun_normal_
from timm.models.layers import DropPath, to_2tuple
from timm.models.vision_transformer import _load_weights
import math
from collections import namedtuple
from mamba_ssm.modules.mamba_simple import Mamba
from mamba_ssm.utils.generation import GenerationMixin
from mamba_ssm.utils.hf import load_config_hf, load_state_dict_hf
from lib.models.mamba_fetrack.rope import *
import random
from lib.models.layers.head import build_box_head
import importlib
import lib.train.admin.settings as ws_settings
from .utils import combine_tokens, recover_tokens
try:
from mamba_ssm.ops.triton.layernorm import RMSNorm, layer_norm_fn, rms_norm_fn
except ImportError:
RMSNorm, layer_norm_fn, rms_norm_fn = None, None, None
all = [
'vim_tiny_patch16_224', 'vim_small_patch16_224', 'vim_base_patch16_224',
'vim_tiny_patch16_384', 'vim_small_patch16_384', 'vim_base_patch16_384',
]
class PatchEmbed(nn.Module):
""" 2D Image to Patch Embedding
"""
def init (self, img_size=224, patch_size=16, stride=16, in_chans=3, embed_dim=768, norm_layer=None, flatten=True):
super().init ()
img_size = to_2tuple(img_size)
patch_size = to_2tuple(patch_size)
self.img_size = img_size
self.patch_size = patch_size
self.grid_size = ((img_size[0] - patch_size[0]) // stride + 1, (img_size[1] - patch_size[1]) // stride + 1)
self.num_patches = self.grid_size[0] * self.grid_size[1]
self.flatten = flatten
code Copy code
self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=stride)
self.norm = norm_layer(embed_dim) if norm_layer else nn.Identity()
def forward(self, x):
B, C, H, W = x.shape
# assert H == self.img_size[0] and W == self.img_size[1], \
# f"Input image size ({H}*{W}) doesn't match model ({self.img_size[0]}*{self.img_size[1]})."
x = self.proj(x)
if self.flatten:
x = x.flatten(2).transpose(1, 2) # BCHW -> BNC
x = self.norm(x)
return x
class Block(nn.Module):
def (
self, dim, mixer_cls, norm_cls=nn.LayerNorm, fused_add_norm=False, residual_in_fp32=False,drop_path=0.,
):
"""
Simple block wrapping a mixer class with LayerNorm/RMSNorm and residual connection"
Show full message · 754 lines Assistant2024-11-13 08:05 UTC Copy response
将Physics-Informed Neural Networks (PINNs)与Vision Mamba或卷积神经网络(CNN)结合是一种创新的方法,可以在需要物理约束的视觉任务中得到应用。下面分析如何将PINNs与所给两个模型结合,以及可以解决的问题和需要考虑的方面。
结合方法
特征提取与后续物理建模 :
使用Vision Mamba提取视觉特征。这些特征可以通过CNN嵌入维度较低的空间,作为PINN后续物理建模的输入。
PINN根据提取的图像特征和已知的物理模型(如运动学方程或动力学方程)来进行后续处理或预测。例如,在实际跟踪任务中,可以利用物理定律预测目标的未来位置。
损失函数结合 :
组合视觉模型的损失函数(如分类损失、定位损失)和物理约束的损失函数(例如,依据PDE的误差)以获得更一致的结果。
利用多目标优化方法,处理视觉损失和物理损失之间的平衡。
分步训练与微调 :
分别训练视觉模型(如使用Mamba FEtrack进行目标定位和特征提取)和PINN模型,再通过微调技术将二者结合,使网络能有效处理视觉和物理输出信息。
应用场景
运动追踪 :在复杂运动物体的追踪中,结合视觉特征提取和物理运动模型,更准确地预测目标轨迹。
增强现实和仿真 :结合实际环境的物理规则,使视觉模型生成的增强信息或仿真片段更加真实可信。
工业检测 :利用物理模型更精确地估计设备运作中的关键数据,识别潜在问题。
面临的挑战
计算复杂性 :结合模式可能导致模型复杂性和计算要求提升,需要合理设计架构以平衡精度和效率。
训练难度 :如何生成适合不同场景的物理模型约束,以及如何巧妙地与视觉模型相融合,也是个挑战。
物理模型的准确性 :选择和设计合适的物理方程去描述不同的视觉问题,需要领域知识的深度参与。
将PINNs与视觉模型结合是一个多学科交叉的课题,以特定问题与场景为基础展开详细设计和实验,是进一步探索这一领域的有效途径。
模型的Loss设计为:from . import BaseActor
from lib.utils.misc import NestedTensor
from lib.utils.box_ops import box_cxcywh_to_xyxy, box_xywh_to_xyxy
import torch
from lib.utils.merge import merge_template_search
from ...utils.heapmap_utils import generate_heatmap
from ...utils.ce_utils import generate_mask_cond, adjust_keep_rate
class Mamba_FETrackActor(BaseActor):
""" Actor for training Mamba_FETrack models """
Show full message · 122 lines Assistant2024-11-13 08:06 UTC Copy response
在Mamba_FETrack模型的训练过程中,损失函数的设计是至关重要的,它结合了多个部分的损失计算,以实现更准确和更鲁棒的跟踪能力。具体来说,这个损失函数是由以下几个部分组成的:
损失函数组成
GIoU损失 (giou_loss):
广义交并比(Generalized Intersection over Union,GIoU)损失是一种改进的IoU损失,用于更好地捕捉边界框之间的重叠。
计算方式涉及预测框和真实框之间的GIoU差异,当预测框远离真实框时,该损失会更大。
L1损失 (l1_loss):
也称为绝对误差损失,L1损失计算预测框和真实框坐标之间的L1距离。
它对异常值不敏感,是一种相对简单和直观的距离度量。
位置损失/焦点损失 (location_loss):
使用Focal Loss来处理平衡类不平衡问题,尤其是在二分类任务中,目标框的定位的高斯热图与预测的评分图 (score_map) 之间的差异。
这种设计可以减小负样本对网络训练的影响,提升对正样本的关注度。
计算流程
数据前向传播 :
模型接收输入数据(模板、搜索区域、事件模板和事件搜索),计算特征,并获得预测的边界框和评分图。
生成真实数据的热图 :
通过真实的边界框生成热图,这在实际应用中用于引导网络学习。
损失计算 :
对每个损失项(GIoU、L1、位置/焦点)分别计算损失。
所有损失项按预定义的权重 (self.loss_weight) 进行加权求和,形成最终的训练损失值。
返回损失和状态信息 :
返回计算的总损失以及每个子损失和IoU的状态报告,便于监控训练过程中的性能。
设计考量
组合多种损失 :这样的设计考虑了检测任务中的多个方面,确保模型不仅能预测精确的边界框,还关注框与图像中特定对象之间的定位关系。
避免输出异常 :通过监控输出中的NAN值,防止输出出现非法数值影响训练。
这种组合损失函数策略可以显著提高目标跟踪任务中的精度和鲁棒性,尤其是在复杂背景和噪声数据中。随着任务需要的变化,还可以通过调整权重或新增/修改损失项以适应新的应用场景。
综上,分析一下PINN可以集成在什么位置?起到什么作用?
Assistant2024-11-13 08:07 UTC Copy response
在分析如何将Physics-Informed Neural Networks (PINN)集成到当前Mamba_FETrack模型框架时,我们需要考虑PINN的优势,即将物理约束引入深度学习模型中,以提高预测的精准性和一致性。以下是一些可能的集成位置及其作用:
1. 特征提取后集成
位置:
可以在Mamba_FETrack模型特征提取后的阶段,即在backbone网络(VisionMamba)计算出特征后,将这些特征作为输入到PINN模块中。
作用:
物理一致性 :在特征提取之后,利用PINN来确保这些特征满足物理约束,例如目标的运动轨迹遵循特定运动学或动力学规律。
复杂环境下的鲁棒性 :通过物理模型的引导,可以提高在复杂环境中目标跟踪的鲁棒性,例如考虑空气阻力、摩擦等因素。
2. 损失函数中作为物理约束部分
位置:
PINN可以在损失函数中作为一个额外的约束项引入,以减少物理不一致性。
作用:
额外物理监督 :在损失计算中,可以加入与物理模型相关的偏微分方程作为约束。这样可以确保网络在优化过程中不仅仅关注数据驱动的误差,还要符合物理规律。
长远预测 :PINN可以增强对目标位置远期预测的能力,通过引入动力学模型,在缺乏数据的情况下依然可以进行合理的轨迹推断。
3. 数据增强与预处理
位置:
用于处理输入数据,尤其是预处理阶段。在输入模板和搜索区域时,通过PINN模块转换或增强数据,使之更易于被后续的深度神经网络模型处理。
作用:
物理一致的数据增强 :利用物理模型模拟某些复杂情况下的数据(如环境变化、多个目标交互等),增强模型的多样性。
降噪 :通过物理模型可以去除伪造的数据噪声,提升输入数据的质量。
4. 在CrossMamba中以模块化形式集成
位置:
在CrossMamba层中,用PINN替代一部分交互机制,通过物理方程指导双模态(如RGB和事件数据)的交互。
作用:
多模态交互的一致性 :利用物理模型来约束和指导不同模态数据之间的交互,使得整合之后的特征更加符合物理逻辑。
引导特征的转化和融合 :在进行模态转换或特征融合时,结合物理指导,模型能更好的完成感知与决策过程。
综上所述
通过上述几种方式,PINN不仅可以约束模型的输出,使得其预测结果符合物理规律,还能作为数据处理和增强的重要工具,为复杂场景下的目标跟踪提供额外的准确性和鲁棒性支持。结合具体的任务需求和数据特性,PINN的实施可以进一步调整和优化,以确保最佳性能和效率。
Assistant2024-11-13 08:07 UTC Copy response
将 Physics-Informed Neural Networks (PINNs) 集成到现有的 Mamba_FETrack 模型中涉及几个步骤。具体实现方式可以因任务需求和物理约束的特性而异。下面是一种可能的简单实现,旨在帮助您入门如何在特征提取后融入 PINN 以进一步优化跟踪结果。
代码示例
假设我们想在特征提取之后引入 PINN 来进行物理一致性约束,这里我们将 PINN 作为一个单独的模块与 VisionMamba 的输出结合使用。
python Copy code
import torch
import torch.nn as nn
class PINN(nn.Module):
def __init__(self, input_dim, hidden_dim, output_dim):
super(PINN, self).__init__()
# 定义 PINN 的全连接层,这里仅作为一个简单示例
self.fc1 = nn.Linear(input_dim, hidden_dim)
self.fc2 = nn.Linear(hidden_dim, output_dim)
self.activation = torch.tanh
def forward(self, x):
# 前向计算,传播经过几层网络结构
x = self.activation(self.fc1(x))
x = self.fc2(x)
return x
class Mamba_FETrack_with_PINN(nn.Module):
def __init__(self, visionmamba, cross_mamba, box_head, pinn, aux_loss=False, head_type="CORNER"):
super().__init__()
self.backbone = visionmamba
self.cross_mamba = cross_mamba
self.box_head = box_head
self.pinn = pinn
self.aux_loss = aux_loss
self.head_type = head_type
if head_type == "CORNER" or head_type == "CENTER":
self.feat_sz_s = int(box_head.feat_sz)
self.feat_len_s = int(box_head.feat_sz ** 2)
if self.aux_loss:
self.box_head = _get_clones(self.box_head, 6)
def forward(self, template, search, event_template, event_search, ce_template_mask=None, ce_keep_rate=None, return_last_attn=False):
# 从 VisionMamba 获取视觉特征
rgb_feature = self.backbone.forward_features(z=template, x=search)
event_feature = self.backbone.forward_features(z=event_template, x=event_search)
# 使用 PINN 处理输出特征
rgb_feature_pinn = self.pinn(rgb_feature)
event_feature_pinn = self.pinn(event_feature)
# CrossMamba的特征交互
residual_event_f = 0
residual_rgb_f = 0
event_f = self.cross_mamba(event_feature_pinn, residual_event_f, rgb_feature_pinn) + event_feature_pinn
rgb_f = self.cross_mamba(rgb_feature_pinn, residual_rgb_f, event_feature_pinn) + rgb_feature_pinn
event_search = event_f[:, -self.feat_len_s:]
rgb_search = rgb_f[:, -self.feat_len_s:]
x = torch.cat((event_search, rgb_search), dim=-1)
# 使用Box Head处理特征
feat_last = x
if isinstance(x, list):
feat_last = x[-1]
out = self.forward_head(feat_last, None)
out['backbone_feat'] = x
return out
分析一下当前双模态网络存在什么问题?在交互中,还可以增加什么操作?当前的双模态是互补的。
Assistant2024-11-13 08:21 UTC Copy response
在双模态网络中,结合多种数据类型(例如,RGB图像和事件数据)来增强模型的表现力和鲁棒性。双模态网络设计的核心在于如何有效地进行信息融合及特征交互,以便从不同模态中提取和整合信息。以下是一些现有双模态网络可能存在的问题以及可增强的交互方式:
当前双模态网络可能存在的问题
模态融合不足 :
如果两个模态的信息仅在简单的特征级别上进行融合(如直接拼接),可能会导致信息丢失或相关性没有被充分利用,无法充分捕捉多模态协作带来的优势。
特征不对齐 :
不同模态之间的特征可能具备不同的分布特性,直接操作可能导致特征不对齐,从而影响最终性能。
交互复杂度 :
交互操作过于简单可能无法充分利用多模态的互补性,而过于复杂的交互又可能导致计算开销和模型复杂度过高。
信息冗余 :
在模态方法整合过程中,冗余信息可能导致不必要的计算,影响实时性或资源使用。
增强模态交互的可能措施
更精细的注意力机制 :
使用交叉注意力(Cross-Attention)机制使得一个模态引导另一个模态的信息提取,可以更好地聚焦于有意义的特征上。
通过注意力分配识别和强化不同模态间的相关特征。
自适应融合策略 :
使用自适应加权机制来动态平衡不同模态的贡献,如通过加权合并特征来实现动态融合。
模态对齐(Alignment) :
引入模态对齐技术,如利用对抗网络使特征分布接近实现对齐,或者使用对齐层进行分布标准化。
层级式特征整合 :
在多个网络层进行多级特征融合和互动,不仅限于单一层面上的简单组合,逐步获得更加详细的多模态信息互动。
多任务学习 :
在融合网络中引入多任务学习框架,不同模态的特征针对不同的小任务进行优化,从而使得整体网络受益。
总结
双模态网络设计的关键在于高效地挖掘和融合不同数据模态内在的互补特性。如果已经有了较好的互补特性,下一步就需要更多地考虑如何更智能、更精细地融合这些信息。各类复杂的交互机制和融合策略在实际任务中需要细致的实验和调整,以确保性能提升和计算开销之间的平衡。
Assistant2024-11-13 08:21 UTC Copy response
在当前的双模态交互中,尤其是在处理不同模态的数据(如RGB图像与事件数据)时,存在若干常见的问题。这些问题可能会影响模型的性能、效率以及对真正有用信息的提取和整合。以下是一些常见的问题以及如何可能影响模型:
1. 模态不对齐
问题描述 :不同模态的数据可能在空间、时间或尺度上存在不对齐的情况。例如,RGB图像可能以帧率捕获,而事件数据以新鲜度变化捕获。
影响 :不对齐会导致在融合时无法充分利用两种模态的信息优势,可能包含误导性信息或模糊。
2. 信息冗余与噪声
问题描述 :两种模态的数据可能包含重复信息,或者某模态的特定信息在当前任务中可能是噪声。
影响 :信息冗余可能导致计算上的浪费和误导,噪声信息可能增加模型的挑战,加大错误决策的风险。
3. 融合策略单一
问题描述 :如果在模态融合中采用简单的连接或加权策略,可能无法捕捉模态间的复杂相互关系。
影响 :简单的融合可能错失模态之间的非线性关系和互补信息,影响性能的进一步提升。
4. 互动不充分
问题描述 :模态之间的信息互动可能缺乏足够的深度或灵活性。例如,简单的并行处理各模态后将结果整合,而非通过交互机制。
影响 :互动不充分可能导致模态之间的潜在协作关系未被展现,未能挖掘不同模态的内在补充作用。
5. 计算负担与效率
问题描述 :双模态网络可能较单模态复杂,从而在计算资源上有更高的需求。
影响 :计算负担会影响实时性应用及高效推理,尤其在资源受限的设备上。
6. 动态性挑战
问题描述 :在动态环境中,两种模态所获取信息的时效性和对应性可能存在动态变化。
影响 :动态适应性不足会导致模型在不同环境或变化条件下表现不稳定。
解决方案与改进思路
模态对齐 :引入机制或算法(如时间同步、特征匹配等)确保数据在处理前已对齐。
自适应融合 :开发更复杂或智能化的融合策略,如通过注意力机制或动态加权来平衡不同模态的信息。
信息选择 :加入噪声过滤或信息增益评估机制,在融合前对可用信息进行选择。
深度互动 :设计多层次的信息互动模型,允许不同模态在多层次上相互影响。
通过分析这些问题,可以更好地理解如何优化双模态系统的设计与实现,以便在融合多源数据时取得最佳结果。
分析一下# -----------------------------------------------------------------------------------
Swin Transformer
Copyright (c) 2021 Microsoft
-----------------------------------------------------------------------------------
VMamba: Visual State Space Model
Copyright (c) 2024 MzeroMiko
-----------------------------------------------------------------------------------
Spatial-Mamba: Effective Visual State Space Models via Structure-Aware State Fusion
Modified by Chaodong Xiao
-----------------------------------------------------------------------------------
import math
import copy
from functools import partial
from typing import Optional, Callable
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 fvcore.nn import flop_count, parameter_count
DropPath.repr = lambda self: f"timm.DropPath({self.drop_prob})"
try:
from .utils import selective_scan_state_flop_jit, selective_scan_fn, Stem, DownSampling
except:
from utils import selective_scan_state_flop_jit, selective_scan_fn, Stem, DownSampling
try:
from Dwconv.dwconv_layer import DepthwiseFunction
except:
DepthwiseFunction = None
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
code Copy code
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 StateFusion(nn.Module):
def init (self, dim):
super(StateFusion, self).init ()
Show full message · 593 lines Assistant2024-11-13 08:48 UTC Copy response
该代码实现了一种名为 Spatial-Mamba 的视觉模型,其灵感来源于 Transformer 架构,用于计算机视觉任务。模型结合了 Swin Transformer 的元素以及详细的状态空间建模技术,旨在通过空间感知和结构感知的状态融合来提高视觉变换模型的性能。以下是对其中主要组件的分析:
主要组件分析
StateFusion 模块
功能 :用于通过多尺度卷积核实现状态的多尺度融合。这种方法可以从不同的空间尺度提取特征,并通过学习的权重 (self.alpha) 来融合这些特征。
机制 :三种不同的卷积核,以及在非训练阶段中通过合并权重以提高计算效率。
StructureAwareSSM 模块
功能 :实现一种结构感知的状态空间模型,旨在通过一系列参数化的投影操作,对特征进行动态调整和融合。
机制 :包括卷积操作、非线性激活 SiLU、状态空间模型的参数化投影 (A_log, Dt, D) 以及后续通过 state_fusion 进行的特征融合。
MLP (Multi-Layer Perceptron)
功能 :用于实现特征转换和非线性映射,帮助提取更高维度的信息。
机制 :典型的前馈全连接层,使用 GELU 激活函数和 dropout 进行正则化。
SpatialMambaBlock
功能 :实现一个基本的 Transformer 块,包括卷积性位置编码 (CPE),自注意力模块以及 MLP 模块。
机制 :通过链式 Add + Norm + MLP 架构实现特征更新。
SpatialMambaLayer 和 Backbone_SpatialMamba
功能 :构造由多个 SpatialMambaBlock 组成的层,用于处理输入特征。
机制 :可以选择使用检查点技术来节省内存,支持下采样以及输出中间层的特征。
Patch Embedding 和 Absolute Position Embedding
功能 :将输入图像分块以及加入绝对位置编码以保留空间信息。
机制 :通过 stem 层进行图像块的生成,并可选择性地添加位置嵌入。
模型使用场景
该模型的设计特别适用于需要空间感知和结构特征捕获的场景,如图像分类、对象检测或分割等任务。
框架结合了 Transformer 的自注意力机制和卷积网络的局部特征提取能力,可以增强模型在处理复杂图像内容时的表达能力。
可能的问题与优化方向
计算开销 :由于结合了多种网络技术,模型可能在计算开销上比较大,尤其在处理高分辨率图像时。
优化建议 :研究减少不必要的特征层,或通过模型剪枝、量化等技术提升效率。
融合策略复杂 :多尺度、多层级的融合策略可能引入相关复杂性,影响训练稳定性。
优化建议 :细化各模块交互中的超参数,并进行充足的超参数搜索以找到更优的配置。
训练难度 :参数繁多,可能需要大量的数据和计算资源进行训练和调优。
优化建议 :结合迁移学习方案,预训练与微调策略协同应用以降低模型的训练成本。
综上所述,Spatial-Mamba 模型通过复杂的多阶段、多层级卷积与自注意力结合,旨在提供更强的性能,但在实施上需要统筹考虑计算效率和训练复杂度。
那么在# Copyright (c) 2015-present, Facebook, Inc.
All rights reserved.
import torch
import torch.nn as nn
from functools import partial
from torch import Tensor
from typing import Optional
from timm.models.vision_transformer import VisionTransformer, cfg
from timm.models.registry import register_model
from timm.models.layers import trunc_normal , lecun_normal_
from timm.models.layers import DropPath, to_2tuple
from timm.models.vision_transformer import _load_weights
import math
from collections import namedtuple
from mamba_ssm.modules.mamba_simple import Mamba
from mamba_ssm.utils.generation import GenerationMixin
from mamba_ssm.utils.hf import load_config_hf, load_state_dict_hf
from lib.models.mamba_fetrack.rope import *
import random
from lib.models.layers.head import build_box_head
import importlib
import lib.train.admin.settings as ws_settings
from .utils import combine_tokens, recover_tokens
try:
from mamba_ssm.ops.triton.layernorm import RMSNorm, layer_norm_fn, rms_norm_fn
except ImportError:
RMSNorm, layer_norm_fn, rms_norm_fn = None, None, None
all = [
'vim_tiny_patch16_224', 'vim_small_patch16_224', 'vim_base_patch16_224',
'vim_tiny_patch16_384', 'vim_small_patch16_384', 'vim_base_patch16_384',
]
class PatchEmbed(nn.Module):
""" 2D Image to Patch Embedding
"""
def init (self, img_size=224, patch_size=16, stride=16, in_chans=3, embed_dim=768, norm_layer=None, flatten=True):
super().init ()
img_size = to_2tuple(img_size)
patch_size = to_2tuple(patch_size)
self.img_size = img_size
self.patch_size = patch_size
self.grid_size = ((img_size[0] - patch_size[0]) // stride + 1, (img_size[1] - patch_size[1]) // stride + 1)
self.num_patches = self.grid_size[0] * self.grid_size[1]
self.flatten = flatten
code Copy code
self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=stride)
self.norm = norm_layer(embed_dim) if norm_layer else nn.Identity()
def forward(self, x):
B, C, H, W = x.shape
# assert H == self.img_size[0] and W == self.img_size[1], \
# f"Input image size ({H}*{W}) doesn't match model ({self.img_size[0]}*{self.img_size[1]})."
x = self.proj(x)
if self.flatten:
x = x.flatten(2).transpose(1, 2) # BCHW -> BNC
x = self.norm(x)
return x
class Block(nn.Module):
def (
self, dim, mixer_cls, norm_cls=nn.LayerNorm, fused_add_norm=False, residual_in_fp32=False,drop_path=0.,
):
"""
Simple block wrapping a mixer class with LayerNorm/RMSNorm and residual connection"
Show full message · 616 lines Assistant2024-11-13 08:50 UTC Copy response
在 VisionMamba 模型中应用来自 Spatial-Mamba 的设计思想可能带来一些有趣的增强,特别是在有效的特征学习和空间感知能力上。以下是一些可以从 Spatial-Mamba 模型借鉴的设计,并适用于 VisionMamba 的元素:
1. 结构感知与状态空间融合
建议借鉴 :Spatial-Mamba 中的 StateFusion 和 StructureAwareSSM 组件能够对输入特征进行多尺度、多层次的融合。这种特征融合有助于加强模型对局部和全局空间特征的捕获能力。
应用于 VisionMamba :
在特征提取或中间层中加入类似 StateFusion 或 StructureAwareSSM 模块,以增强特征的空间多样性和融合。
利用状态空间建模过渡以在不同层级的网络中提供深度特征交互和多层次的增强。
2. 多尺度卷积处理
建议借鉴 :Spatial-Mamba 使用多尺度卷积核进行特征提取,以便在不同尺寸的感受野上处理视觉信息。
应用于 VisionMamba :
在 VisionMamba 的特征抽取层,考虑引入大小不同的卷积核或模块进行多尺度卷积特征融合。
允许网络在同一数据流中从多个尺度提取信息,提高对各种大小目标的识别能力。
3. 模块化设计与逐层规范
建议借鉴 :Spatial-Mamba 中的模块化设计如 SpatialMambaBlock 提供了一种灵活结构来处理不同层面的特征。
应用于 VisionMamba :
通过模块化的方式构建 VisionMamba,使其具有更好的扩展性和可调试性。
引入对不同层的规范化与特定功能的处理(如新位置编码策略、改变激活函数等)能够增加模型的适应性与效率。
4. 优化参数管理
建议借鉴 :在 Spatial-Mamba 中,对全局参数(如缩放和初始化)进行了精细管理,以此提升训练效率。
应用于 VisionMamba :
细化模型中的参数初始化,借鉴如 A_log_init 和 dt_init 的细化处理逻辑,提高初始训练阶段的稳定性。
对参数缩放(如归一化层)进行再优化,可能提高模型的稳定性和性能表现。
总结
将 Spatial-Mamba 的一些设计思想引入 VisionMamba 中,可以在保障原模型核心功能的基础上,进一步提高其空间感知能力和上下文信息整合的表现。这种充分融合在设计和实现上需要注意到两种架构的不同需求和优化方向,但通过合理的合并与创新设计,可以在深度学习模型性能上带来新的突破。
那么在VisionMamba模型中,增加StateFusion 和 StructureAwareSSM 组件,可以先增加一个,给出代码
Assistant2024-11-13 08:53 UTC Copy response
在 VisionMamba 模型中引入 StateFusion 或 StructureAwareSSM 组件可以提高空间融合能力和结构感知能力。为了说明如何在模型中増加一个组件,我们将增加 StateFusion 作为一个示例。StateFusion 模块用于在多尺度上下提取和融合特征。
在 VisionMamba 中增加 StateFusion
代码实现
首先,我们需要定义 StateFusion 模块,然后将其集成到 VisionMamba 模型中合适的地方,如特征提取阶段。
Assistant2024-11-13 09:00 UTC Copy response
当然,为了完整地展示 forward_features 函数的实现,我们可以确保所有步骤都包括,并全面处理特征提取过程。在这里,我们将使用之前的 StateFusion 模块并说明如何在特征提取过程中应用它。
python Copy code
import torch
import torch.nn as nn
import torch.nn.functional as F
class PatchEmbed(nn.Module):
""" 2D Image to Patch Embedding """
def __init__(self, img_size=224, patch_size=16, stride=16, in_chans=3, embed_dim=768, norm_layer=None, flatten=True):
super().__init__()
self.img_size = img_size
self.patch_size = patch_size
self.grid_size = ((img_size - patch_size) // stride + 1, (img_size - patch_size) // stride + 1)
self.num_patches = self.grid_size[0] * self.grid_size[1]
self.flatten = flatten
self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=stride)
self.norm = norm_layer(embed_dim) if norm_layer else nn.Identity()
def forward(self, x):
B, C, H, W = x.shape
x = self.proj(x)
if self.flatten:
x = x.flatten(2).transpose(1, 2) # (B, C, H, W) -> (B, N, C)
x = self.norm(x)
return x
class VisionMambaWithStateFusion(nn.Module):
def __init__(self,
img_size=224,
patch_size=16,
stride=16,
depth=24,
embed_dim=192,
channels=3,
num_classes=1000,
drop_rate=0.,
norm_epsilon: float = 1e-5,
):
super().__init__()
self.embed_dim = embed_dim
self.patch_embed = PatchEmbed(
img_size=img_size, patch_size=patch_size, stride=stride, in_chans=channels, embed_dim=embed_dim
)
# Apply StateFusion after patch embedding
self.state_fusion = StateFusion(embed_dim)
self.layers = nn.ModuleList(
[
create_block(embed_dim) for _ in range(depth)
]
)
self.norm_f = nn.LayerNorm(embed_dim, eps=norm_epsilon)
self.head = nn.Linear(embed_dim, num_classes) if num_classes > 0 else nn.Identity()
def forward_features(self, x):
# Initial Patch Embedding
x = self.patch_embed(x)
# Reshape for StateFusion
x = x.permute(0, 2, 1).reshape(-1, self.embed_dim, int(self.patch_embed.grid_size[0]), int(self.patch_embed.grid_size[1]))
# Apply StateFusion
x = self.state_fusion(x)
# Flatten back to (B, N, C)
x = x.view(x.size(0), self.embed_dim, -1).permute(0, 2, 1)
# Apply Transformer Blocks
for layer in self.layers:
x, _ = layer(x)
# Normalize
x = self.norm_f(x)
# Pooling (mean over sequence dimension)
return x.mean(dim=1)
def forward(self, x):
x = self.forward_features(x)
x = self.head(x)
return x
这是原始的def forward_features(self, z, x, inference_params=None, if_random_cls_token_position=False, if_random_token_rank=False):
# taken from https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/vision_transformer.py
# with slight modifications to add the dist_token
x = self.patch_embed(x) #x.shape = torch.Size([B, 3, 256, 256]) -> torch.Size([2, 256, 384])
z = self.patch_embed(z) #z.shape = torch.Size([B, 3, 128, 128]) -> torch.Size([2, 64, 384])
B, M, _ = x.shape
Show full message · 154 lines Assistant2024-11-13 09:03 UTC Copy response
为了在原始的 forward_features 方法中集成 StateFusion 模块,我们可以在嵌入之后进行 StateFusion 的应用。这将允许我们利用 StateFusion 来增强特征的空间感知能力。下面是如何将 StateFusion 整合到 VisionMamba 模型中的代码:
当前在x = self.hin_block(x)
z = self.hin_block(z)
code Copy code
x = self.patch_embed(x) #x.shape = torch.Size([B, 3, 256, 256]) -> torch.Size([2, 256, 384])
z = self.patch_embed(z) #z.shape = torch.Size([B, 3, 128, 128]) -> torch.Size([2, 64, 384])
B, M, _ = x.shape中先用了 def forward(self, x):
scale_1 = self.conv_1x1(x)
scale_2 = self.conv_3x3(x)
scale_3 = self.conv_5x5(x)
resi = torch.cat([scale_1, scale_2, scale_3], dim=1)
resi = self.relu(resi)
resi = self.relu(self.conv_2(resi))
out_1, out_2 = torch.chunk(resi, 2, dim=1)
resi = torch.cat([self.norm(out_1), out_2], dim=1)
return x + resi
Assistant2024-11-13 09:05 UTC Copy response
在你的架构中,看起来你正在使用一个自定义的块 hin_block 来增强输入特征 x 和 z,该块可能是一个多尺度卷积模块,并在最终输出时进行了归一化和残差连接。下面将详细分析这个模块的理念,以及它为何可能对模型的特征捕获能力有益。
解释
hin_block 的实现
Multi-Scale Convolution :
对输入 x 使用了三种不同尺寸的卷积核:1x1、3x3 和 5x5。
这允许模型在不同的尺度上提取特征,从而更好地捕捉到局部和全局的信息。
残差连接 :
在卷积和归一化之后,结果和输入 x 相加。这样做可以帮助模型学习输入数据的增量变化,并解决深层网络中的梯度消失问题。
通过这种方式,可以保留某种程度的输入信息,再加上新提取的特征。
ReLU 激活函数 :
在卷积结果的连接和第二次卷积之后应用 ReLU 激活函数,确保非线性特征的增加,并在计算上通常能增强模型的表现。
Normalization :
在 torch.chunk 和第二次 torch.cat 之间的归一化处理,有助于提高模型的数值稳定性。
使用 hin_block 的优点
多尺度分析 : 多尺度卷积特征增强了模型捕捉不同尺寸对象和结构细节的能力。
特征融合与增强 : 残差连接和 ReLU 激活用于提取特征的同时保持信息流的连续性与丰富性。
归一化提高稳定性 : 在特定的维度上进行归一化,有助于获取平衡的输入,不因特征尺度导致训练不稳定。
整合在模型中的意义
在 VisionMamba 的特征提取过程中,首先对输入应用 hin_block 以增强特征质量,再进行 patch_embed 投影。这种做法可以确保嵌入层接收的特征已被充分处理,从而提高整体网络对原始图像数据的表达能力。
后续步骤
参数调优 : 可对卷积核的大小、数量,及归一化、激活函数的类型进行实验与调优,以找到最适合特定任务的数据增强手段。
组合其它特征处理模块 : 根据需要,考虑与 StateFusion 或其它空间特征提取模块结合使用,以求最优的特征表示。
这种设计显示出一种目标明确的特征预处理架构设计思路,能让主模型以更高效的方式分析和学得数据特征。
Assistant2024-11-13 09:06 UTC Copy response
在现有的模型中,引入 StateFusion 模块可以进一步提高模型的特征提取能力。StateFusion 能够通过多尺度卷积聚合特征,从而增强模型的空间感知和细节捕捉能力。下面介绍如何在模型的特征流处理中集成 StateFusion,特别是在前文所描述的 hin_block 后进行应用。
集成 StateFusion 的位置与作用
StateFusion 主要通过不同的卷积尺度来融合不同空间尺度的特征,适合在 patch_embed 之前进行,因为此时的特征图仍为二维形式,允许更好地进行空间建模。
以下是如何在 VisionMamba 模型的 forward_features 方法中集成 StateFusion:
这里存在的问题是 hin_block 和 stateFusion两个模块的作用是否重复了?
Assistant2024-11-13 09:07 UTC Copy response
您提出的疑问确实值得注意。在设计深度学习模型时,模块的作用尽量避免重复是至关重要的,以防增加不必要的计算复杂度和资源消耗。我们可以通过分析 hin_block 和 StateFusion 来了解它们之间可能的重叠,并考虑如何优化。
模块功能分析
HinBlock :
多尺度卷积 : HinBlock 使用三种不同尺寸的卷积核(1x1, 3x3, 5x5)以捕捉不同尺度的特征。
特征融合 : 通过串联卷积结果,然后进行 ReLU 激活和进一步的卷积操作。
残差连接 : 特征经过归一化和分割后,参与到残差连接中,以保留输入的某些原始信息。
StateFusion :
多尺度卷积 : 以多种膨胀率 (dilation rates) 进行卷积,从而捕获不同的空间上下文。
多尺度融合 : 使用学习参数(alpha)来聚合多尺度卷积的结果。
主要直接作用于二维特征图。
功能重叠部分
多尺度处理 :
两个模块均在不同尺度上进行卷积以增加特征的多样性。这种多尺度卷积策略在两个模块中同时存在,可能会导致特征处理中的冗余。
特征融合 :
HinBlock 和 StateFusion 使用不同的方法来融合多尺度特征。如果两者的目标和特征空间相似,可能会导致一些功能重叠。
优化建议
选择性使用 : 根据具体任务的特征和需求,选择一个模块以进行多尺度卷积。您可以根据任务需求的一致性和效率作出抉择。
功能整合 : 在一个模块中实现不同的多尺度策略,而不是分别应用它们。这种结合可以简化模型架构,减少计算开销。
模块重构 : 如果必须保留两个模块,则可以考虑对其中一个进行重构,使其在功能上与另一个模块互补,而非重复。
参数共享策略 : 探索在两个模块之间实施参数共享的可能性,这样可以减少冗余权重,也可能带来一定正则化效果。
在模型开发中实现正确的架构设计,既能提高模型性能,又能降低资源开销。在实验和调优阶段,经常需要依据数据集、问题领域和计算预算来优化设计。
那么stateFusion是否能集成在mambaBlock中?
Assistant2024-11-13 09:08 UTC Copy response
将 StateFusion 集成到 MambaBlock 中是一个合理的想法,它可以结合 MambaBlock 的特性并增强其空间感知能力。通过这种方式,StateFusion 不再是一个独立的模块,而是与其他特征变换操作结合在一起,从而可能提高 MambaBlock 的整体性能和效率。
下面是如何在 MambaBlock 中集成 StateFusion 的一个例子:
集成 StateFusion 到 MambaBlock
假设 MambaBlock 的定义如下:
python Copy code
class MambaBlock(nn.Module):
def __init__(self, dim, mixer_cls, norm_cls=nn.LayerNorm, drop_path=0.0, ...):
super().__init__()
self.mixer = mixer_cls(dim)
self.norm = norm_cls(dim)
self.drop_path = DropPath(drop_path)
# 初始化其他组件...
# 集成 StateFusion
self.state_fusion = StateFusion(dim)
def forward(self, hidden_states: Tensor, residual: Optional[Tensor] = None, ...):
# 使用 StateFusion 进行特征增强
h = hidden_states.permute(0, 2, 1).reshape(-1, hidden_states.size(-1), int(hidden_states.size(1)**0.5), int(hidden_states.size(1)**0.5))
h = self.state_fusion(h)
h = h.view(hidden_states.size(0), hidden_states.size(1), hidden_states.size(2)).permute(0, 2, 1)
# 继续原本 MambaBlock 的计算
if residual is None:
residual = h
else:
residual = residual + self.drop_path(h)
# normalization and mixer operations
h = self.norm(residual.to(dtype=self.norm.weight.dtype))
hidden_states = self.mixer(h)
return hidden_states, residual
整合思路
和现有逻辑结合 :
将 StateFusion 作为 MambaBlock 的一部分,这样可以在特征流的过程中进行空间特征增强。
在其它标准操作(如归一化、混合器)之前首先增强多尺度特征。
调整序列化 :
根据输入特征的形状,适当地进行 permute 和 view 操作,以使 StateFusion 能够处理二维特征图。
简化模型结构 :
这种集成可以避免多余的模块调用和冗余特征处理步骤,从而简化模型结构并可能降低计算复杂度。
优势
通过这种方式,模型能在保持模块化设计灵活性同时提升整体性能。不过,实施时需要根据任务和数据集特征对 StateFusion 的参数(如卷积核和学习率)进行适当调整和优化。
把 def forward(
self, hidden_states: Tensor, residual: Optional[Tensor] = None, inference_params=None
):
r"""Pass the input through the encoder layer.
code Copy code
Args:
hidden_states: the sequence to the encoder layer (required).
residual: hidden_states = Mixer(LN(residual))
"""
if not self.fused_add_norm:
if residual is None:
residual = hidden_states
else:
residual = residual + self.drop_path(hidden_states)
hidden_states = self.norm(residual.to(dtype=self.norm.weight.dtype))
if self.residual_in_fp32:
residual = residual.to(torch.float32)
else:
fused_add_norm_fn = rms_norm_fn if isinstance(self.norm, RMSNorm) else layer_norm_fn
if residual is None:
hidden_states, residual = fused_add_norm_fn(
hidden_states,
self.norm.weight,
self.norm.bias,
residual=residual,
prenorm=True,
residual_in_fp32=self.residual_in_fp32,
eps=self.norm.eps,
)
else:
hidden_states, residual = fused_add_norm_fn(
self.drop_path(hidden_states),
self.norm.weight,
self.norm.bias,
residual=residual,
prenorm=True,
residual_in_fp32=self.residual_in_fp32,
eps=self.norm.eps,
)
hidden_states = self.mixer(hidden_states, inference_params=inference_params)
# 增加门控机制, 消除冗余和不相关的特征,保留最具表现力的输出
if self.glu_adapter is not None:
hidden_states = self.glu_adapter(hidden_states)
# hidden_states = self.glu_adapter(hidden_states)
return hidden_states, residual写全
Show full message · 46 lines Assistant2024-11-13 09:10 UTC Copy response
要将这个函数补全,我们将展示如何在 MambaBlock 中实现特征处理的完整步骤,包括使用 StateFusion 和提供已注释的高级函数。这个函数是 MambaBlock 的核心,它描述了输入经过特征增强、规范化、混合和可能的门控机制的路径。我们将补全函数并集成 StateFusion。
完整代码示例
Assistant2024-11-13 09:12 UTC Copy response
对于这种形状的输入 (20, 320, 384),我们需要特别注意如何在三维格式下应用 StateFusion,因为它是在二维特征图上进行操作的。下面是一种方法:通过在应用 StateFusion 之前对形状进行适当的排列和变换,来确保特征在二维平面上进行卷积操作。
整合 StateFusion 的 MambaBlock 的代码示例
Assistant2024-11-13 09:14 UTC Copy response
你指出的问题是对的。在处理输入形状为 (B, N, C) 时,如果序列长度 N 不是一个完美平方,那么将其重塑为二维形态以适合 StateFusion 的操作可能会失败。在这种情况下,我们可以使用一种处理方式来适应非完美平方的序列长度。
一个解决方案是对输入进行批量处理,将每个序列分开并独立扩展为足够的宽高比。我们可以通过填充或裁剪来确保特征图最终的大小适合卷积的操作。以下是一个示例,展示了如何调整输入形状以应用 StateFusion:
代码示例
那么StructureAwareSSM模块呢,是否能集成进来,作用是什么?
Assistant2024-11-13 09:16 UTC Copy response
将 StructureAwareSSM 模块集成到现有模型中,特别是 MambaBlock 中,可以为模型增加结构感知的处理能力。StructureAwareSSM 模块通常用来在空间和结构层次上加强特征处理能力,通过对特征的动态调整和融合,可以有效地捕捉局部和全局的结构信息。
作用与优势
多尺度特征捕捉 :通过复杂的卷积和投影操作,StructureAwareSSM 能够在多尺度上对特征进行提取和融合。
结构感知能力 :该模块的设计基于对特征进行结构化的处理,帮助模型更准确地捕捉输入中的模式和变化。
动态调整 :StructureAwareSSM 能够根据输入动态调整特征,使模型获得更强的泛化性能和适应能力。
代码示例
假设 StructureAwareSSM 已被实现,我们可以在 MambaBlock 内集成它:
我们想在crossMamba处进行创新设计,对于双模态特征交互,还可以如何设计?
Assistant2024-11-13 09:23 UTC Copy response
在设计双模态特征交互机制时,我们可以借鉴现代深度学习的最新进展,并结合有效的特征融合策略。以下是一些可能的创新设计思路,可以在 CrossMamba 中实施以增强双模态特征交互:
1. 多头交叉注意力 (Multi-head Cross Attention)
概念 :将来自两个模态的特征通过交叉注意力机制连接,允许每个模态以自适应的方式关注另一个模态的相关特征。
实现 :
利用多头注意力,使得不同的头能够捕获不同的信息模式。
改进传统的自注意力机制,让每个模态从其他模态中汲取信息。
2. 特征级融合 (Feature-wise Fusion)
概念 :根据特征维度进行单独的融合操作,可以是加权平均、拼接之后的卷积、或者门控机制。
实现 :
使用可学习的权重对不同模态的特征进行加权。
引入门控机制以融合特征,比如使用 Sigmoid 或 Tanh 激活函数确定融合比重。
3. 可学习的特征门控 (Gated Feature Selection)
概念 :使用感知器层来动态地选择或衰减某些来自模态的特征,以达到更精确的融合。
实现 :
使用门控单元 (例如 Gated Linear Units, GLU) 控制哪一部分特征被保留或忽略。
引入以输入特征为条件的门控网络指导整个过程。
4. 模态转换层 (Modal Transformation Layer)
概念 :建立模态之间的映射关系,使得一种模态可以在另一个模态中表现出类似的特征。
实现 :
采用 Transformation Network 将一种模态投影到另一个模态的特征空间。
使用特定的变换(如基于残差的变换)以去捕捉模态间的隐含关系。
5. 协同注意力 (Co-Attention) 机制
概念 :通过双向注意力机制,确保每个模态都能有效参与到另外一个模态的信息交流和集中。
实现 :
创建两个独立的注意力通道,彼此更新和共享权重。
使用类似 Transformer 的两层交互模型以对两个模态分别进行注意力建模。
6. 层次式特征融合 (Hierarchical Feature Fusion)
概念 :在不同的网络层级上进行多次交互,不仅局限于初始特征或嵌入层。
实现 :
在不同深度的位置各自进行特征交互与融合。
在模型深度增加的情况下,逐步在更高层次上表现出合并效应。
7. 生成对抗学习 (Generative Adversarial Interaction)
概念 :利用生成对抗网络(GAN)中所用的竞争性学习方法,优化双模态特征的生成和匹配。
实现 :
建立生成器和判别器,分别来提升模态间交互产生特征的真实度。
利用GAN学习推助目标模态生成逼真的相对应直接对于另一个模态的特征。
通过这些方法,你可以设计一个更加灵活且强大的 CrossMamba 机制,旨在最优地结合和利用不同模态之间互补的信息。实施时需考虑到特定任务和数据集的需求,选取合适的策略进行融合与实现。
Assistant2024-11-13 09:24 UTC Copy response
为您提供多种双模态特征交互策略的代码示例。每个策略都是独立实现的,可以根据具体需求插入到 CrossMamba 或类似结构的模型中。
1. 多头交叉注意力 (Multi-head Cross Attention)
python Copy code
import torch
import torch.nn as nn
class MultiHeadCrossAttention(nn.Module):
def __init__(self, embed_dim, num_heads):
super().__init__()
self.cross_attention = nn.MultiheadAttention(embed_dim, num_heads)
def forward(self, query, key, value):
# query, key, value with shape (seq_len, batch, embed_dim)
attn_output, _ = self.cross_attention(query, key, value)
return attn_output
2. 特征级融合 (Feature-wise Fusion)
python Copy code
class FeatureWiseFusion(nn.Module):
def __init__(self, embed_dim):
super().__init__()
self.fc1 = nn.Linear(embed_dim, embed_dim)
self.sigmoid = nn.Sigmoid()
def forward(self, x1, x2):
# x1 and x2 are features from two different modalities
weights = self.sigmoid(self.fc1(x1))
return weights * x1 + (1 - weights) * x2
3. 可学习的特征门控 (Gated Feature Selection)
python Copy code
class GatedFeatureSelection(nn.Module):
def __init__(self, embed_dim):
super().__init__()
self.glu = nn.Linear(embed_dim, embed_dim * 2)
def forward(self, x1, x2):
# x1 and x2 could be from two different modalities
gate = self.glu(x1)
gate, value = gate.chunk(2, dim=-1)
gated_output = torch.sigmoid(gate) * value
return gated_output + x2
4. 模态转换层 (Modal Transformation Layer)
Assistant2024-11-13 09:25 UTC Copy response
层次式特征融合(Hierarchical Feature Fusion)是一种通过在模型的多个层级上整合特征的技术。其核心思想是在不同抽象级别上捕获和融合特征信息,以增强模型对输入数据的理解。层次式特征融合的原理可以从以下几个方面来理解:
原理
多层次特征表示 :
在一个深层神经网络中,不同的层可以学习到输入数据的不同特征表示。底层可能捕获较低级别的细节特征(如边缘、纹理),而高层可能更关注语义和上下文信息。
通过在多个层次上融合特征,可以整合来自不同抽象级别的丰富信息。
增强特征表示 :
层次式特征融合通常能涵盖多个尺度和上下文,有助于捕获复杂模式,例如在图像中不同对象的情况。
通过将不同层的特征线性组合或者非线性转换,可以提高特征的表示能力,使之更有效地贡献于之后的任务(如分类或回归)。
鲁棒性与一致性 :
在不同层次进行特征交互有助于增强模型的鲁棒性,防止对单个特征的不稳定依赖,从而实现更一致的决策。
多种策略与实施方式 :
最直接的层次式特征融合方式是通过跳跃连接(skip connections)或者特征拼接(concatenation)来结合不同网络层的输出。
在某些设计中,特征可能经过特定变换(如卷积、全连接、注意力机制)后再融合,以保证特征的可兼容性和可用性。
示例实现
在实现层次式特征融合时,你可能会想要一个模块,该模块可以接受来自不同层的输入并施加融合操作。
python Copy code
import torch
import torch.nn as nn
class HierarchicalFeatureFusion(nn.Module):
def __init__(self, embed_dim):
super().__init__()
# Fusion layers suppose to further process inputs before aggregation
self.fusion_layers = nn.ModuleList([
nn.Sequential(
nn.Linear(embed_dim, embed_dim),
nn.ReLU()
) for _ in range(3) # Suppose we want 3 layers of fusion
])
self.combine = nn.Linear(embed_dim * 3, embed_dim)
def forward(self, x1, x2):
# Process each input through a series of transformation layers
fusions = []
for layer in self.fusion_layers:
x1 = layer(x1)
x2 = layer(x2)
fusions.append((x1 + x2) / 2)
# Concatenate the fused outputs and compress back to original size
out = torch.cat(fusions, dim=-1)
out = self.combine(out)
return out
在网络结构中的作用
Sharing Across Hierarchies :
每一层融合都能在不同网络深度间传递信息,从而可以在模型计算时逐步丰富数据表示。
Gradient Flow :
从融合的不同层导出的梯度流可以更好地平衡各个层的学习压力,充分利用网络各个层的表示能力,得到更加充分和稳定的训练结果。
这种多层次的融合策略可以提高模型的特征表达能力,在视觉任务、自然语言处理等任务中已经被证明具有优良的性能优势。每个项目或者应用可能需要特定的实现和适应以满足对融合的需求。
那么将HierarchicalFeatureFusion集成到import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from einops import rearrange
import numbers
from lib.models.mamba_fetrack.mamba_cross_simple import Mamba
def to_3d(x):
return rearrange(x, 'b c h w -> b (h w) c')
def to_4d(x, h, w):
return rearrange(x, 'b (h w) c -> b c h w', h=h, w=w)
class BiasFree_LayerNorm(nn.Module):
def init (self, normalized_shape):
super(BiasFree_LayerNorm, self).init ()
if isinstance(normalized_shape, numbers.Integral):
normalized_shape = (normalized_shape,)
normalized_shape = torch.Size(normalized_shape)
code Copy code
assert len(normalized_shape) == 1
self.weight = nn.Parameter(torch.ones(normalized_shape))
self.normalized_shape = normalized_shape
def forward(self, x):
sigma = x.var(-1, keepdim=True, unbiased=False)
return x / torch.sqrt(sigma+1e-5) * self.weight
class WithBias_LayerNorm(nn.Module):
def init (self, normalized_shape):
super(WithBias_LayerNorm, self).init ()
if isinstance(normalized_shape, numbers.Integral):
normalized_shape = (normalized_shape,)
normalized_shape = torch.Size(normalized_shape)
code Copy code
assert len(normalized_shape) == 1
self.weight = nn.Parameter(torch.ones(normalized_shape))
self.bias = nn.Parameter(torch.zeros(normalized_shape))
self.normalized_shape = normalized_shape
def forward(self, x):
mu = x.mean(-1, keepdim=True)
sigma = x.var(-1, keepdim=True, unbiased=False)
return (x - mu) / torch.sqrt(sigma+1e-5) * self.weight + self.bias
class LayerNorm(nn.Module):
def init (self, dim, LayerNorm_type):
super(LayerNorm, self).init ()
if LayerNorm_type =='BiasFree':
self.body = BiasFree_LayerNorm(dim)
else:
self.body = WithBias_LayerNorm(dim)
code Copy code
def forward(self, x):
h, w = x.shape[-2:]
return to_4d(self.body(to_3d(x)), h, w)
class CrossMamba(nn.Module):
def init (self, dim):
super(CrossMamba, self).init ()
self.cross_mamba = Mamba(dim,bimamba_type="v3")
self.norm1 = LayerNorm(dim,'with_bias')
self.norm2 = LayerNorm(dim,'with_bias')
self.dwconv = nn.Conv2d(dim, dim, kernel_size=3, padding=1, groups=dim)
def forward(self,m1,m1_resi,m2):
m1_resi = m1+m1_resi
global_f = self.cross_mamba(m1, extra_emb=m2)
return global_f 中去。
Show full message · 73 lines Assistant2024-11-13 09:29 UTC Copy response
将 HierarchicalFeatureFusion 集成到 CrossMamba 中,我们希望通过层次特征融合来提升模态间特征的交互效果。在 CrossMamba 的设计中,通过 HierarchicalFeatureFusion 可以更深入地整合和处理来自两个模态的数据,为 CrossMamba 提供更加丰富的输入信息以进行处理。
以下是如何进行这一整合的代码示例:
在 CrossMamba 中集成 HierarchicalFeatureFusion
Not yet included in a published release.
Turns (29) 1 分析一下:class LinearAttention(nn.Module): def init(self, dim): super(LinearAttentio 2 分析一下当前的操作中,注意力机制引入的计算量。 3 那么就不要这个注意力 4 你知道PINN吗? 5 那么PINN在目标跟踪任务中能用吗?可以 解决什么问题? 6 PINN可以和vision Mamba或者CNN结合吗? 7 模型是:# Copyright (c) 2015-present, Facebook, Inc. All rights reserved. import tor 8 模型的Loss设计为:from . import BaseActor from lib.utils.misc import NestedTensor from 9 综上,分析一下PINN可以集成在什么位置?起到什么作用? 10 给出结合PINN的代码 11 分析一下当前双模态网络存在什么问题?在交互中,还可以增加什么操作?当前的双模态是互补的。 12 分析一下当前双模态交互中存在的问题是什么? 13 分析一下# -------------------------------------------------------------------------- 14 那么在# Copyright (c) 2015-present, Facebook, Inc. All rights reserved. import torc 15 那么在VisionMamba模型中,增加StateFusion 和 StructureAwareSSM 组件,可以先增加一个,给出代码 16 把forwardfeatures部分写全 17 这是原始的def forwardfeatures(self, z, x, inferenceparams=None, ifrandomclstokenposit 18 当前在x = self.hinblock(x) z = self.hinblock(z) x = self.patchembed(x) #x.shape = t 19 那么statefusion呢 20 这里存在的问题是 hinblock 和 stateFusion两个模块的作用是否重复了? 21 那么stateFusion是否能集成在mambaBlock中? 22 把 def forward( self, hiddenstates: Tensor, residual: Optional[Tensor] = None, in 23 但是当前shape是(20,320,384) 24 但是320开方不整 25 那么StructureAwareSSM模块呢,是否能集成进来,作用是什么? 26 我们想在crossMamba处进行创新设计,对于双模态特征交互,还可以如何设计? 27 那么分别给出上述建议对应的代码 28 这里的层次式特征融合是什么原理 29 那么将HierarchicalFeatureFusion集成到import math import torch import torch.nn as nn im init
code Copy code
This Block has a slightly different structure compared to a regular
prenorm Transformer block.
The standard block is: LN -> MHA/MLP -> Add.
[Ref: https://arxiv.org/abs/2002.04745]
Here we have: Add -> LN -> Mixer, returning both
the hidden_states (output of the mixer) and the residual.
This is purely for performance reasons, as we can fuse add and LayerNorm.
The residual needs to be provided (except for the very first block).
"""
super().__init__()
self.residual_in_fp32 = residual_in_fp32
self.fused_add_norm = fused_add_norm
self.mixer = mixer_cls(dim)
self.norm = norm_cls(dim)
self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
if self.fused_add_norm:
assert RMSNorm is not None, "RMSNorm import fails"
assert isinstance(
self.norm, (nn.LayerNorm, RMSNorm)
), "Only LayerNorm and RMSNorm are supported for fused_add_norm"
def forward(
self, hidden_states: Tensor, residual: Optional[Tensor] = None, inference_params=None
):
r"""Pass the input through the encoder layer.
Args:
hidden_states: the sequence to the encoder layer (required).
residual: hidden_states = Mixer(LN(residual))
"""
if not self.fused_add_norm:
if residual is None:
residual = hidden_states
else:
residual = residual + self.drop_path(hidden_states)
hidden_states = self.norm(residual.to(dtype=self.norm.weight.dtype))
if self.residual_in_fp32:
residual = residual.to(torch.float32)
else:
fused_add_norm_fn = rms_norm_fn if isinstance(self.norm, RMSNorm) else layer_norm_fn
if residual is None:
hidden_states, residual = fused_add_norm_fn(
hidden_states,
self.norm.weight,
self.norm.bias,
residual=residual,
prenorm=True,
residual_in_fp32=self.residual_in_fp32,
eps=self.norm.eps,
)
else:
hidden_states, residual = fused_add_norm_fn(
self.drop_path(hidden_states),
self.norm.weight,
self.norm.bias,
residual=residual,
prenorm=True,
residual_in_fp32=self.residual_in_fp32,
eps=self.norm.eps,
)
hidden_states = self.mixer(hidden_states, inference_params=inference_params)
return hidden_states, residual
def allocate_inference_cache(self, batch_size, max_seqlen, dtype=None, **kwargs):
return self.mixer.allocate_inference_cache(batch_size, max_seqlen, dtype=dtype, **kwargs)
def create_block(
d_model,
ssm_cfg=None,
norm_epsilon=1e-5,
drop_path=0.,
rms_norm=False,
residual_in_fp32=False,
fused_add_norm=False,
layer_idx=None,
device=None,
dtype=None,
if_bimamba=False,
bimamba_type="none",
if_devide_out=False,
init_layer_scale=None,
):
if if_bimamba:
bimamba_type = "v1"
if ssm_cfg is None:
ssm_cfg = {}
factory_kwargs = {"device": device, "dtype": dtype}
mixer_cls = partial(Mamba, layer_idx=layer_idx, bimamba_type=bimamba_type, if_devide_out=if_devide_out, init_layer_scale=init_layer_scale, **ssm_cfg, **factory_kwargs)
norm_cls = partial(
nn.LayerNorm if not rms_norm else RMSNorm, eps=norm_epsilon, **factory_kwargs
)
block = Block(
d_model,
mixer_cls,
norm_cls=norm_cls,
drop_path=drop_path,
fused_add_norm=fused_add_norm,
residual_in_fp32=residual_in_fp32,
)
block.layer_idx = layer_idx
return block
def init_weights(
module,
n_layer,
initializer_range=0.02, # Now only used for embedding layer.
rescale_prenorm_residual=True,
n_residuals_per_layer=1, # Change to 2 if we have MLP
):
if isinstance(module, nn.Linear):
if module.bias is not None:
if not getattr(module.bias, "no_reinit", False):
nn.init.zeros (module.bias)
elif isinstance(module, nn.Embedding):
nn.init.normal (module.weight, std=initializer_range)
code Copy code
if rescale_prenorm_residual:
# Reinitialize selected weights subject to the OpenAI GPT-2 Paper Scheme:
# > A modified initialization which accounts for the accumulation on the residual path with model depth. Scale
# > the weights of residual layers at initialization by a factor of 1/√N where N is the # of residual layers.
# > -- GPT-2 :: https://openai.com/blog/better-language-models/
#
# Reference (Megatron-LM): https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/model/gpt_model.py
for name, p in module.named_parameters():
if name in ["out_proj.weight", "fc2.weight"]:
# Special Scaled Initialization --> There are 2 Layer Norms per Transformer Block
# Following Pytorch init, except scale by 1/sqrt(2 * n_layer)
# We need to reinit p since this code could be called multiple times
# Having just p *= scale would repeatedly scale it down
nn.init.kaiming_uniform_(p, a=math.sqrt(5))
with torch.no_grad():
p /= math.sqrt(n_residuals_per_layer * n_layer)
def segm_init_weights(m):
if isinstance(m, nn.Linear):
trunc_normal_(m.weight, std=0.02)
if isinstance(m, nn.Linear) and m.bias is not None:
nn.init.constant_(m.bias, 0)
elif isinstance(m, nn.Conv2d):
# NOTE conv was left to pytorch default in my original init
lecun_normal_(m.weight)
if m.bias is not None:
nn.init.zeros_(m.bias)
elif isinstance(m, (nn.LayerNorm, nn.GroupNorm, nn.BatchNorm2d)):
nn.init.zeros_(m.bias)
nn.init.ones_(m.weight)
class VisionMamba(nn.Module):
def init (self,
img_size=224,
patch_size=16,
stride=16,
depth=24,
embed_dim=192,
channels=3,
num_classes=1000,
ssm_cfg=None,
drop_rate=0.,
drop_path_rate=0.1,
norm_epsilon: float = 1e-5,
rms_norm: bool = False,
initializer_cfg=None,
fused_add_norm=False,
residual_in_fp32=False,
device=None,
dtype=None,
ft_seq_len=None,
pt_hw_seq_len=14,
if_bidirectional=False,
final_pool_type='none',
if_abs_pos_embed=False,
if_rope=False,
if_rope_residual=False,
flip_img_sequences_ratio=-1.,
if_bimamba=False,
bimamba_type="none",
if_cls_token=False,
if_devide_out=False,
init_layer_scale=None,
use_double_cls_token=False,
use_middle_cls_token=False,
**kwargs):
factory_kwargs = {"device": device, "dtype": dtype}
# add factory_kwargs into kwargs
kwargs.update(factory_kwargs)
super().init ()
self.residual_in_fp32 = residual_in_fp32
self.fused_add_norm = fused_add_norm
self.if_bidirectional = if_bidirectional
self.final_pool_type = final_pool_type
self.if_abs_pos_embed = if_abs_pos_embed
self.if_rope = if_rope
self.if_rope_residual = if_rope_residual
self.flip_img_sequences_ratio = flip_img_sequences_ratio
# self.if_cls_token = if_cls_token
self.if_cls_token = False
self.use_double_cls_token = use_double_cls_token
self.use_middle_cls_token = use_middle_cls_token
self.num_tokens = 1 if if_cls_token else 0
code Copy code
# pretrain parameters
self.num_classes = num_classes
self.d_model = self.num_features = self.embed_dim = embed_dim # num_features for consistency with other models
self.patch_embed = PatchEmbed(
img_size=img_size, patch_size=patch_size, stride=stride, in_chans=channels, embed_dim=embed_dim)
num_patches = self.patch_embed.num_patches
if if_cls_token:
if use_double_cls_token:
self.cls_token_head = nn.Parameter(torch.zeros(1, 1, self.embed_dim))
self.cls_token_tail = nn.Parameter(torch.zeros(1, 1, self.embed_dim))
self.num_tokens = 2
else:
self.cls_token = nn.Parameter(torch.zeros(1, 1, self.embed_dim))
# self.num_tokens = 1
if if_abs_pos_embed:
# self.pos_embed = nn.Parameter(torch.zeros(1, num_patches + self.num_tokens, self.embed_dim))
self.pos_embed_x = nn.Parameter(torch.zeros(1, 256, self.embed_dim))
self.pos_embed_z = nn.Parameter(torch.zeros(1, 64, self.embed_dim))
self.pos_drop = nn.Dropout(p=drop_rate)
if if_rope:
half_head_dim = embed_dim // 2
hw_seq_len = img_size // patch_size
self.rope = VisionRotaryEmbeddingFast(
dim=half_head_dim,
pt_seq_len=pt_hw_seq_len,
ft_seq_len=hw_seq_len
)
# self.head = nn.Linear(self.num_features, num_classes) if num_classes > 0 else nn.Identity()
# settings = ws_settings.Settings()
# config_module = importlib.import_module("lib.config.%s.config" % settings.script_name)
# cfg = config_module.cfg
# self.head = build_box_head(cfg, embed_dim)
# TODO: release this comment
dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)] # stochastic depth decay rule
# import ipdb;ipdb.set_trace()
inter_dpr = [0.0] + dpr
self.drop_path = DropPath(drop_path_rate) if drop_path_rate > 0. else nn.Identity()
# transformer blocks
self.layers = nn.ModuleList(
[
create_block(
embed_dim,
ssm_cfg=ssm_cfg,
norm_epsilon=norm_epsilon,
rms_norm=rms_norm,
residual_in_fp32=residual_in_fp32,
fused_add_norm=fused_add_norm,
layer_idx=i,
if_bimamba=if_bimamba,
bimamba_type=bimamba_type,
drop_path=inter_dpr[i],
if_devide_out=if_devide_out,
init_layer_scale=init_layer_scale,
**factory_kwargs,
)
for i in range(depth)
]
)
# output head
self.norm_f = (nn.LayerNorm if not rms_norm else RMSNorm)(
embed_dim, eps=norm_epsilon, **factory_kwargs
)
# self.pre_logits = nn.Identity()
# original init
self.patch_embed.apply(segm_init_weights)
# self.head.apply(segm_init_weights)
if if_abs_pos_embed:
trunc_normal_(self.pos_embed_x, std=.02)
trunc_normal_(self.pos_embed_z, std=.02)
if if_cls_token:
if use_double_cls_token:
trunc_normal_(self.cls_token_head, std=.02)
trunc_normal_(self.cls_token_tail, std=.02)
else:
trunc_normal_(self.cls_token, std=.02)
# mamba init
self.apply(
partial(
_init_weights,
n_layer=depth,
**(initializer_cfg if initializer_cfg is not None else {}),
)
)
def allocate_inference_cache(self, batch_size, max_seqlen, dtype=None, **kwargs):
return {
i: layer.allocate_inference_cache(batch_size, max_seqlen, dtype=dtype, **kwargs)
for i, layer in enumerate(self.layers)
}
@torch.jit.ignore
def no_weight_decay(self):
return {"pos_embed", "cls_token", "dist_token", "cls_token_head", "cls_token_tail"}
@torch.jit.ignore()
def load_pretrained(self, checkpoint_path, prefix=""):
_load_weights(self, checkpoint_path, prefix)
def forward_features(self, z, x, inference_params=None, if_random_cls_token_position=False, if_random_token_rank=False):
# taken from https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/vision_transformer.py
# with slight modifications to add the dist_token
x = self.patch_embed(x) #x.shape = torch.Size([B, 3, 256, 256]) -> torch.Size([2, 256, 384])
z = self.patch_embed(z) #z.shape = torch.Size([B, 3, 128, 128]) -> torch.Size([2, 64, 384])
B, M, _ = x.shape
if self.if_cls_token: # False
if self.use_double_cls_token:
cls_token_head = self.cls_token_head.expand(B, -1, -1)
cls_token_tail = self.cls_token_tail.expand(B, -1, -1)
token_position = [0, M + 1]
x = torch.cat((cls_token_head, x, cls_token_tail), dim=1)
M = x.shape[1]
else:
if self.use_middle_cls_token:
cls_token = self.cls_token.expand(B, -1, -1)
token_position = M // 2
# add cls token in the middle
x = torch.cat((x[:, :token_position, :], cls_token, x[:, token_position:, :]), dim=1)
elif if_random_cls_token_position:
cls_token = self.cls_token.expand(B, -1, -1)
token_position = random.randint(0, M)
x = torch.cat((x[:, :token_position, :], cls_token, x[:, token_position:, :]), dim=1)
print("token_position: ", token_position)
else:
cls_token = self.cls_token.expand(B, -1, -1) # stole cls_tokens impl from Phil Wang, thanks
token_position = 0
x = torch.cat((cls_token, x), dim=1)
M = x.shape[1]
if self.if_abs_pos_embed: # True
x = x + self.pos_embed_x # x = x + positon_embemding =torch.Size([B, 256, 384]) + torch.Size([1, 256, 384]) = torch.Size([B, 256, 384])
z = z + self.pos_embed_z # z = z + positon_embemding =torch.Size([B, 64, 384]) + torch.Size([1, 64, 384]) = torch.Size([B, 64, 384])
x = torch.cat((z, x), dim=1) # torch.Size([B, 320, 384])
x = self.pos_drop(x) # x.shape = torch.Size([B, 320, 384])
if if_random_token_rank: #False
# 生成随机 shuffle 索引
shuffle_indices = torch.randperm(M)
if isinstance(token_position, list):
print("original value: ", x[0, token_position[0], 0], x[0, token_position[1], 0])
else:
print("original value: ", x[0, token_position, 0])
print("original token_position: ", token_position)
# 执行 shuffle
x = x[:, shuffle_indices, :]
if isinstance(token_position, list):
# 找到 cls token 在 shuffle 之后的新位置
new_token_position = [torch.where(shuffle_indices == token_position[i])[0].item() for i in range(len(token_position))]
token_position = new_token_position
else:
# 找到 cls token 在 shuffle 之后的新位置
token_position = torch.where(shuffle_indices == token_position)[0].item()
if isinstance(token_position, list):
print("new value: ", x[0, token_position[0], 0], x[0, token_position[1], 0])
else:
print("new value: ", x[0, token_position, 0])
print("new token_position: ", token_position)
if_flip_img_sequences = False
if self.flip_img_sequences_ratio > 0 and (self.flip_img_sequences_ratio - random.random()) > 1e-5: # False
x = x.flip([1])
if_flip_img_sequences = True
# mamba impl
residual = None
hidden_states = x
if not self.if_bidirectional: # True
for layer in self.layers:
if if_flip_img_sequences and self.if_rope: # False
hidden_states = hidden_states.flip([1])
if residual is not None:
residual = residual.flip([1])
# rope about
if self.if_rope: # False
hidden_states = self.rope(hidden_states)
if residual is not None and self.if_rope_residual:
residual = self.rope(residual)
if if_flip_img_sequences and self.if_rope: # False
hidden_states = hidden_states.flip([1])
if residual is not None:
residual = residual.flip([1])
hidden_states, residual = layer(
hidden_states, residual, inference_params=inference_params
)
else: # False
# get two layers in a single for-loop
for i in range(len(self.layers) // 2):
if self.if_rope:
hidden_states = self.rope(hidden_states)
if residual is not None and self.if_rope_residual:
residual = self.rope(residual)
hidden_states_f, residual_f = self.layers[i * 2](
hidden_states, residual, inference_params=inference_params
)
hidden_states_b, residual_b = self.layers[i * 2 + 1](
hidden_states.flip([1]), None if residual == None else residual.flip([1]), inference_params=inference_params
)
hidden_states = hidden_states_f + hidden_states_b.flip([1])
residual = residual_f + residual_b.flip([1])
if not self.fused_add_norm: #False
if residual is None:
residual = hidden_states
else:
residual = residual + self.drop_path(hidden_states)
hidden_states = self.norm_f(residual.to(dtype=self.norm_f.weight.dtype))
else: #True
# Set prenorm=False here since we don't need the residual
fused_add_norm_fn = rms_norm_fn if isinstance(self.norm_f, RMSNorm) else layer_norm_fn
hidden_states = fused_add_norm_fn( # hidden_states.shape = torch.Size([B, 320, 384])
self.drop_path(hidden_states),
self.norm_f.weight,
self.norm_f.bias,
eps=self.norm_f.eps,
residual=residual,
prenorm=False,
residual_in_fp32=self.residual_in_fp32,
)
# return only cls token if it exists
if self.if_cls_token: #False
if self.use_double_cls_token:
return (hidden_states[:, token_position[0], :] + hidden_states[:, token_position[1], :]) / 2
else:
if self.use_middle_cls_token:
return hidden_states[:, token_position, :]
elif if_random_cls_token_position:
return hidden_states[:, token_position, :]
else:
return hidden_states[:, token_position, :]
if self.final_pool_type == 'none':
return hidden_states[:, -1, :]
elif self.final_pool_type == 'mean': #True
return hidden_states.mean(dim=1) #hidden_states.shape = torch.Size([2, 384])
elif self.final_pool_type == 'max':
return hidden_states
elif self.final_pool_type == 'all':
return hidden_states
else:
raise NotImplementedError
def forward(self, x, return_features=False, inference_params=None, if_random_cls_token_position=False, if_random_token_rank=False):
x = self.forward_features(x, inference_params, if_random_cls_token_position=if_random_cls_token_position, if_random_token_rank=if_random_token_rank)
if return_features:
return x
x = self.head(x)
if self.final_pool_type == 'max':
x = x.max(dim=1)[0]
return x
@register_model
def vim_tiny_patch16_224_bimambav2_final_pool_mean_abs_pos_embed_with_midclstok_div2(pretrained=False, **kwargs):
model = VisionMamba(
patch_size=16, embed_dim=192, depth=24, rms_norm=True, residual_in_fp32=True, fused_add_norm=True, final_pool_type='mean', if_abs_pos_embed=True, if_rope=False, if_rope_residual=False, bimamba_type="v2", if_cls_token=True, if_devide_out=True, use_middle_cls_token=True, **kwargs)
model.default_cfg = _cfg()
if pretrained:
checkpoint = torch.hub.load_state_dict_from_url(
url="to.do",
map_location="cpu", check_hash=True
)
model.load_state_dict(checkpoint["model"])
return model
@register_model
def vim_tiny_patch16_stride8_224_bimambav2_final_pool_mean_abs_pos_embed_with_midclstok_div2(pretrained=False, **kwargs):
model = VisionMamba(
patch_size=16, stride=8, embed_dim=192, depth=24, rms_norm=True, residual_in_fp32=True, fused_add_norm=True, final_pool_type='mean', if_abs_pos_embed=True, if_rope=False, if_rope_residual=False, bimamba_type="v2", if_cls_token=True, if_devide_out=True, use_middle_cls_token=True, **kwargs)
model.default_cfg = _cfg()
if pretrained:
checkpoint = torch.hub.load_state_dict_from_url(
url="to.do",
map_location="cpu", check_hash=True
)
model.load_state_dict(checkpoint["model"])
return model
@register_model
def vim_small_patch16_224_bimambav2_final_pool_mean_abs_pos_embed_with_midclstok_div2(pretrained=False, **kwargs):
model = VisionMamba(
patch_size=16, embed_dim=384, depth=24, rms_norm=True, residual_in_fp32=True, fused_add_norm=True, final_pool_type='all', if_abs_pos_embed=True, if_rope=False, if_rope_residual=False, bimamba_type="v2", if_cls_token=True, if_devide_out=True, use_middle_cls_token=True, **kwargs)
model.default_cfg = _cfg()
code Copy code
if pretrained:
# checkpoint = torch.hub.load_state_dict_from_url(
# url="to.do",
# map_location="cpu", check_hash=True
# )
# model.load_state_dict(checkpoint["model"])
checkpoint = torch.load(pretrained, map_location="cpu")
missing_keys, unexpected_keys = model.load_state_dict(checkpoint["model"], strict=False)
print('Load pretrained model from: ' + pretrained)
return model
@register_model
def vim_small_patch16_stride8_224_bimambav2_final_pool_mean_abs_pos_embed_with_midclstok_div2(pretrained=False, **kwargs):
model = VisionMamba(
patch_size=16, stride=8, embed_dim=384, depth=24, rms_norm=True, residual_in_fp32=True, fused_add_norm=True, final_pool_type='mean', if_abs_pos_embed=True, if_rope=False, if_rope_residual=False, bimamba_type="v2", if_cls_token=True, if_devide_out=True, use_middle_cls_token=True, **kwargs)
model.default_cfg = _cfg()
if pretrained:
checkpoint = torch.hub.load_state_dict_from_url(
url="to.do",
map_location="cpu", check_hash=True
)
model.load_state_dict(checkpoint["model"])
return model
和 """
Basic mamda_fetrack model.
"""
import math
import os
from typing import List
import torch
from torch import nn
from torch.nn.modules.transformer import _get_clones
from lib.models.layers.head import build_box_head
from lib.utils.box_ops import box_xyxy_to_cxcywh
from lib.models.mamba_fetrack.models_mamba import create_block
from timm.models import create_model
import torch.nn.functional as F
from lib.models.mamba_fetrack.mamba_cross import CrossMamba
from thop import profile
class Mamba_FEtrack(nn.Module):
""" This is the base class for mamda_fetrack """
code Copy code
def __init__(self, visionmamba, cross_mamba, box_head, aux_loss=False, head_type="CORNER"):
""" Initializes the model.
Parameters:
transformer: torch module of the transformer architecture.
aux_loss: True if auxiliary decoding losses (loss at each decoder layer) are to be used.
"""
super().__init__()
self.backbone = visionmamba
self.cross_mamba= cross_mamba
self.box_head = box_head
self.aux_loss = aux_loss
self.head_type = head_type
if head_type == "CORNER" or head_type == "CENTER":
self.feat_sz_s = int(box_head.feat_sz)
self.feat_len_s = int(box_head.feat_sz ** 2)
if self.aux_loss:
self.box_head = _get_clones(self.box_head, 6)
def forward(self, template: torch.Tensor,
search: torch.Tensor,
event_template: torch.Tensor,
event_search: torch.Tensor,
ce_template_mask=None,
ce_keep_rate=None,
return_last_attn=False,
):
rgb_feature = self.backbone.forward_features( z=template, x=search, #[B, 320, 384]
inference_params=None, if_random_cls_token_position=False, if_random_token_rank=False)
event_feature = self.backbone.forward_features(z=event_template, x=event_search, #[B, 320, 384]
inference_params=None, if_random_cls_token_position=False, if_random_token_rank=False)
residual_event_f = 0
residual_rgb_f = 0
event_f = self.cross_mamba(event_feature,residual_event_f,rgb_feature) + event_feature
rgb_f = self.cross_mamba(rgb_feature,residual_rgb_f,event_feature) + rgb_feature
event_searh = event_f[:, -self.feat_len_s:]
rgb_search = rgb_f[:, -self.feat_len_s:]
x = torch.cat((event_searh,rgb_search),dim=-1)
# Forward head
feat_last = x
if isinstance(x, list):
feat_last = x[-1]
out = self.forward_head(feat_last, None)
out['backbone_feat'] = x
return out
def forward_head(self, cat_feature, gt_score_map=None):
"""
cat_feature: output embeddings of the backbone, it can be (HW1+HW2, B, C) or (HW2, B, C)
"""
search_feature = cat_feature
opt = (search_feature.unsqueeze(-1)).permute((0, 3, 2, 1)).contiguous() # opt.shape = torch.Size([B, 1, 384, 256])
bs, Nq, C, HW = opt.size()
opt_feat = opt.view(-1, C, self.feat_sz_s, self.feat_sz_s) # opt_feat.shape = torch.Size([B, 384, 16, 16])
if self.head_type == "CORNER":
# run the corner head
pred_box, score_map = self.box_head(opt_feat, True)
outputs_coord = box_xyxy_to_cxcywh(pred_box)
outputs_coord_new = outputs_coord.view(bs, Nq, 4)
out = {'pred_boxes': outputs_coord_new,
'score_map': score_map,
}
return out
elif self.head_type == "CENTER":
# run the center head
score_map_ctr, bbox, size_map, offset_map = self.box_head(opt_feat, gt_score_map)
outputs_coord = bbox
outputs_coord_new = outputs_coord.view(bs, Nq, 4)
out = {'pred_boxes': outputs_coord_new,
'score_map': score_map_ctr,
'size_map': size_map,
'offset_map': offset_map}
return out
else:
raise NotImplementedError
def build_mamba_fetrack(cfg, training=True):
current_dir = os.path.dirname(os.path.abspath(file )) # This is your Project Root
pretrained_path = os.path.join(current_dir, '../../../pretrained_models')
if cfg.MODEL.PRETRAIN_FILE and ('Mamba_FETrack' not in cfg.MODEL.PRETRAIN_FILE) and training:
pretrained = os.path.join(pretrained_path, cfg.MODEL.PRETRAIN_FILE)
else:
pretrained = ''
code Copy code
backbone = create_model( model_name= cfg.MODEL.BACKBONE.TYPE, pretrained= pretrained, num_classes=1000,
drop_rate=0.0, drop_path_rate=cfg.TRAIN.DROP_PATH_RATE, drop_block_rate=None, img_size=256
)
hidden_dim = 384
cross_mamba = CrossMamba(hidden_dim)
box_head = build_box_head(cfg, hidden_dim*2)
model = Mamba_FEtrack(
backbone,
cross_mamba,
box_head,
aux_loss=False,
head_type=cfg.MODEL.HEAD.TYPE,
)
if 'Mamba_FETrack' in cfg.MODEL.PRETRAIN_FILE and training:
checkpoint = torch.load(cfg.MODEL.PRETRAIN_FILE, map_location="cpu")
missing_keys, unexpected_keys = model.load_state_dict(checkpoint["net"], strict=False)
print('Load pretrained model from: ' + cfg.MODEL.PRETRAIN_FILE)
return model
def __init__(self, net, objective, loss_weight, settings, cfg=None):
super().__init__(net, objective)
self.loss_weight = loss_weight
self.settings = settings
self.bs = self.settings.batchsize # batch size
self.cfg = cfg
def __call__(self, data):
"""
args:
data - The input data, should contain the fields 'template', 'search', 'gt_bbox'.
template_images: (N_t, batch, 3, H, W)
search_images: (N_s, batch, 3, H, W)
returns:
loss - the training loss
status - dict containing detailed losses
"""
# forward pass
out_dict = self.forward_pass(data)
# compute losses
loss, status = self.compute_losses(out_dict, data)
return loss, status
def forward_pass(self, data):
# currently only support 1 template and 1 search region
assert len(data['template_images']) == 1
assert len(data['search_images']) == 1
assert len(data['template_event']) == 1
assert len(data['search_event']) == 1
template_list = []
for i in range(self.settings.num_template):
template_img_i = data['template_images'][i].view(-1,
*data['template_images'].shape[2:]) # (batch, 3, 128, 128)
# template_att_i = data['template_att'][i].view(-1, *data['template_att'].shape[2:]) # (batch, 128, 128)
template_list.append(template_img_i)
search_img = data['search_images'][0].view(-1, *data['search_images'].shape[2:]) # (batch, 3, 320, 320)
# search_att = data['search_att'][0].view(-1, *data['search_att'].shape[2:]) # (batch, 320, 320)
template_event = data['template_event'][0].view(-1, *data['template_event'].shape[2:])
search_event = data['search_event'][0].view(-1, *data['search_event'].shape[2:])
box_mask_z = None
ce_keep_rate = None
if self.cfg.MODEL.BACKBONE.CE_LOC:
box_mask_z = generate_mask_cond(self.cfg, template_list[0].shape[0], template_list[0].device,
data['template_anno'][0])
ce_start_epoch = self.cfg.TRAIN.CE_START_EPOCH
ce_warm_epoch = self.cfg.TRAIN.CE_WARM_EPOCH
ce_keep_rate = adjust_keep_rate(data['epoch'], warmup_epochs=ce_start_epoch,
total_epochs=ce_start_epoch + ce_warm_epoch,
ITERS_PER_EPOCH=1,
base_keep_rate=self.cfg.MODEL.BACKBONE.CE_KEEP_RATIO[0])
if len(template_list) == 1:
template_list = template_list[0]
out_dict = self.net(template=template_list,
search=search_img,
event_template=template_event,
event_search=search_event,
ce_template_mask=box_mask_z,
ce_keep_rate=ce_keep_rate,
return_last_attn=False)
return out_dict
def compute_losses(self, pred_dict, gt_dict, return_status=True):
# gt gaussian map
gt_bbox = gt_dict['search_anno'][-1] # (Ns, batch, 4) (x1,y1,w,h) -> (batch, 4)
gt_gaussian_maps = generate_heatmap(gt_dict['search_anno'], self.cfg.DATA.SEARCH.SIZE, self.cfg.MODEL.BACKBONE.STRIDE)
gt_gaussian_maps = gt_gaussian_maps[-1].unsqueeze(1)
# Get boxes
pred_boxes = pred_dict['pred_boxes']
if torch.isnan(pred_boxes).any():
raise ValueError("Network outputs is NAN! Stop Training")
num_queries = pred_boxes.size(1)
pred_boxes_vec = box_cxcywh_to_xyxy(pred_boxes).view(-1, 4) # (B,N,4) --> (BN,4) (x1,y1,x2,y2)
gt_boxes_vec = box_xywh_to_xyxy(gt_bbox)[:, None, :].repeat((1, num_queries, 1)).view(-1, 4).clamp(min=0.0,
max=1.0) # (B,4) --> (B,1,4) --> (B,N,4)
# compute giou and iou
try:
giou_loss, iou = self.objective['giou'](pred_boxes_vec, gt_boxes_vec) # (BN,4) (BN,4)
except:
giou_loss, iou = torch.tensor(0.0).cuda(), torch.tensor(0.0).cuda()
# compute l1 loss
l1_loss = self.objective['l1'](pred_boxes_vec, gt_boxes_vec) # (BN,4) (BN,4)
# compute location loss
if 'score_map' in pred_dict:
location_loss = self.objective['focal'](pred_dict['score_map'], gt_gaussian_maps)
else:
location_loss = torch.tensor(0.0, device=l1_loss.device)
# weighted sum
loss = self.loss_weight['giou'] * giou_loss + self.loss_weight['l1'] * l1_loss + self.loss_weight['focal'] * location_loss
if return_status:
# status for log
mean_iou = iou.detach().mean()
status = {"Loss/total": loss.item(),
"Loss/giou": giou_loss.item(),
"Loss/l1": l1_loss.item(),
"Loss/location": location_loss.item(),
"IoU": mean_iou.item()}
return loss, status
else:
return loss
解释
PINN模块 :
我们创建了一个简单的全连接网络作为PINN的示例。它可以根据物理约束和输入进行调整。
Mamba_FETrack_with_PINN类 :
修改了Mamba_FEtrack类,在视觉特征提取后添加了PINN处理步骤,确保特征在物理意义上有一定约束性。
与PINN结合 :
特征在进入CrossMamba前被传递给PINN模块进行进一步处理,确保特征流的物理一致性。
注意:实际实施时,PINN的网络结构及其训练策略可能会更加复杂,需要根据具体物理模型和任务需求进行设计和调整。这只是一个起始示例,展示如何集成和使用PINN。
self.dim = dim
self.kernel_3 = nn.Parameter(torch.ones(dim, 1, 3, 3))
self.kernel_3_1 = nn.Parameter(torch.ones(dim, 1, 3, 3))
self.kernel_3_2 = nn.Parameter(torch.ones(dim, 1, 3, 3))
self.alpha = nn.Parameter(torch.ones(3), requires_grad=True)
@staticmethod
def padding(input_tensor, padding):
return torch.nn.functional.pad(input_tensor, padding, mode='replicate')
def forward(self, h):
if self.training:
h1 = F.conv2d(self.padding(h, (1,1,1,1)), self.kernel_3, padding=0, dilation=1, groups=self.dim)
h2 = F.conv2d(self.padding(h, (3,3,3,3)), self.kernel_3_1, padding=0, dilation=3, groups=self.dim)
h3 = F.conv2d(self.padding(h, (5,5,5,5)), self.kernel_3_2, padding=0, dilation=5, groups=self.dim)
out = self.alpha[0]*h1 + self.alpha[1]*h2 + self.alpha[2]*h3
return out
else:
if not hasattr(self, "_merge_weight"):
self._merge_weight = torch.zeros((self.dim, 1, 11, 11), device=h.device)
self._merge_weight[:, :, 4:7, 4:7] = self.alpha[0]*self.kernel_3
self._merge_weight[:, :, 2:3, 2:3] = self.alpha[1]*self.kernel_3_1[:,:,0:1,0:1]
self._merge_weight[:, :, 2:3, 5:6] = self.alpha[1]*self.kernel_3_1[:,:,0:1,1:2]
self._merge_weight[:, :, 2:3, 8:9] = self.alpha[1]*self.kernel_3_1[:,:,0:1,2:3]
self._merge_weight[:, :, 5:6, 2:3] = self.alpha[1]*self.kernel_3_1[:,:,1:2,0:1]
self._merge_weight[:, :, 5:6, 5:6] += self.alpha[1]*self.kernel_3_1[:,:,1:2,1:2]
self._merge_weight[:, :, 5:6, 8:9] = self.alpha[1]*self.kernel_3_1[:,:,1:2,2:3]
self._merge_weight[:, :, 8:9, 2:3] = self.alpha[1]*self.kernel_3_1[:,:,2:3,0:1]
self._merge_weight[:, :, 8:9, 5:6] = self.alpha[1]*self.kernel_3_1[:,:,2:3,1:2]
self._merge_weight[:, :, 8:9, 8:9] = self.alpha[1]*self.kernel_3_1[:,:,2:3,2:3]
self._merge_weight[:, :, 0:1, 0:1] = self.alpha[2]*self.kernel_3_2[:,:,0:1,0:1]
self._merge_weight[:, :, 0:1, 5:6] = self.alpha[2]*self.kernel_3_2[:,:,0:1,1:2]
self._merge_weight[:, :, 0:1, 10:11] = self.alpha[2]*self.kernel_3_2[:,:,0:1,2:3]
self._merge_weight[:, :, 5:6, 0:1] = self.alpha[2]*self.kernel_3_2[:,:,1:2,0:1]
self._merge_weight[:, :, 5:6, 5:6] += self.alpha[2]*self.kernel_3_2[:,:,1:2,1:2]
self._merge_weight[:, :, 5:6, 10:11] = self.alpha[2]*self.kernel_3_2[:,:,1:2,2:3]
self._merge_weight[:, :, 10:11, 0:1] = self.alpha[2]*self.kernel_3_2[:,:,2:3,0:1]
self._merge_weight[:, :, 10:11, 5:6] = self.alpha[2]*self.kernel_3_2[:,:,2:3,1:2]
self._merge_weight[:, :, 10:11, 10:11] = self.alpha[2]*self.kernel_3_2[:,:,2:3,2:3]
out = DepthwiseFunction.apply(h, self._merge_weight, None, 11//2, 11//2, False)
return out
class StructureAwareSSM(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.dt_rank = math.ceil(self.d_model / 16) if dt_rank == "auto" else dt_rank
code Copy code
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)
self.x_proj_weight = nn.Parameter(self.x_proj.weight)
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_projs_weight = nn.Parameter(self.dt_projs.weight)
self.dt_projs_bias = nn.Parameter(self.dt_projs.bias)
del self.dt_projs
self.A_logs = self.A_log_init(self.d_state, self.d_inner, dt_init)
self.Ds = self.D_init(self.d_inner, dt_init)
self.selective_scan = selective_scan_fn
self.state_fusion = StateFusion(self.d_inner)
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, bias=True,**factory_kwargs):
dt_proj = nn.Linear(dt_rank, d_inner, bias=bias, **factory_kwargs)
if bias:
# 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
# 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)
elif dt_init == "simple":
with torch.no_grad():
dt_proj.weight.copy_(0.1 * torch.randn((d_inner, dt_rank)))
dt_proj.bias.copy_(0.1 * torch.randn((d_inner)))
dt_proj.bias._no_reinit = True
elif dt_init == "zero":
with torch.no_grad():
dt_proj.weight.copy_(0.1 * torch.rand((d_inner, dt_rank)))
dt_proj.bias.copy_(0.1 * torch.rand((d_inner)))
dt_proj.bias._no_reinit = True
else:
raise NotImplementedError
return dt_proj
@staticmethod
def A_log_init(d_state, d_inner, init, device=None):
if init=="random" or "constant":
# 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)
A_log = nn.Parameter(A_log)
A_log._no_weight_decay = True
elif init=="simple":
A_log = nn.Parameter(torch.randn((d_inner, d_state)))
elif init=="zero":
A_log = nn.Parameter(torch.zeros((d_inner, d_state)))
else:
raise NotImplementedError
return A_log
@staticmethod
def D_init(d_inner, init="random", device=None):
if init=="random" or "constant":
# D "skip" parameter
D = torch.ones(d_inner, device=device)
D = nn.Parameter(D)
D._no_weight_decay = True
elif init == "simple" or "zero":
D = nn.Parameter(torch.ones(d_inner))
else:
raise NotImplementedError
return D
def ssm(self, x: torch.Tensor):
B, C, H, W = x.shape
L = H * W
xs = x.view(B, -1, L)
x_dbl = torch.matmul(self.x_proj_weight.view(1, -1, C), xs)
dts, Bs, Cs = torch.split(x_dbl, [self.dt_rank, self.d_state, self.d_state], dim=1)
dts = torch.matmul(self.dt_projs_weight.view(1, C, -1), dts)
As = -torch.exp(self.A_logs)
Ds = self.Ds
dts = dts.contiguous()
dt_projs_bias = self.dt_projs_bias
h = self.selective_scan(
xs, dts,
As, Bs, None,
z=None,
delta_bias=dt_projs_bias,
delta_softplus=True,
return_last_state=False,
)
h = rearrange(h, "b d 1 (h w) -> b (d 1) h w", h=H, w=W)
h = self.state_fusion(h)
h = rearrange(h, "b d h w -> b d (h w)")
y = h * Cs
y = y + xs * Ds.view(-1, 1)
return 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 = rearrange(x, 'b h w d -> b d h w').contiguous()
x = self.act(self.conv2d(x))
y = self.ssm(x)
y = rearrange(y, 'b d (h w)-> b h w d', h=H, w=W)
y = self.out_norm(y)
y = y * F.silu(z)
y = self.out_proj(y)
if self.dropout is not None:
y = self.dropout(y)
return y
class SpatialMambaBlock(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,
dt_init: str = "random",
num_heads: int = 8,
mlp_ratio = 4.0,
mlp_act_layer=nn.GELU,
mlp_drop_rate=0.0,
**kwargs,
):
super().init ()
code Copy code
self.cpe1 = nn.Conv2d(hidden_dim, hidden_dim, 3, padding=1, groups=hidden_dim)
self.ln_1 = norm_layer(hidden_dim)
self.self_attention = StructureAwareSSM(d_model=hidden_dim, dropout=attn_drop_rate, d_state=d_state, dt_init=dt_init, **kwargs)
self.drop_path = DropPath(drop_path)
self.cpe2 = nn.Conv2d(hidden_dim, hidden_dim, 3, padding=1, groups=hidden_dim)
self.ln_2 = norm_layer(hidden_dim)
self.mlp = MLP(in_features=hidden_dim, hidden_features=int(hidden_dim*mlp_ratio), act_layer=mlp_act_layer, drop=mlp_drop_rate, channels_first=False)
def forward(self, x: torch.Tensor):
x = x + self.cpe1(x.permute(0, 3, 1, 2).contiguous()).permute(0, 2, 3, 1)
x = x + self.drop_path(self.self_attention(self.ln_1(x)))
x = x + self.cpe2(x.permute(0, 3, 1, 2).contiguous()).permute(0, 2, 3, 1)
x = x + self.drop_path(self.mlp(self.ln_2(x)))
return x
class SpatialMambaLayer(nn.Module):
""" A basic Swin Transformer layer for one stage.
Args:
dim (int): Number of input channels.
depth (int): Number of blocks.
drop (float, optional): Dropout rate. Default: 0.0
attn_drop (float, optional): Attention dropout rate. Default: 0.0
drop_path (float | tuple[float], optional): Stochastic depth rate. Default: 0.0
norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
downsample (nn.Module | None, optional): Downsample layer at the end of the layer. Default: None
use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False.
"""
code Copy code
def __init__(
self,
dim,
depth,
attn_drop=0.,
drop_path=0.,
norm_layer=nn.LayerNorm,
downsample=None,
use_checkpoint=False,
d_state=16,
dt_init="random",
mlp_ratio=4.0,
**kwargs,
):
super().__init__()
self.dim = dim
self.use_checkpoint = use_checkpoint
self.blocks = nn.ModuleList([
SpatialMambaBlock(
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,
dt_init=dt_init,
mlp_ratio=mlp_ratio,
)
for i in range(depth)])
if True:
def _init_weights(module: nn.Module):
for name, p in module.named_parameters():
if name in ["out_proj.weight"]:
p = p.clone().detach_()
nn.init.kaiming_uniform_(p, a=math.sqrt(5))
self.apply(_init_weights)
if downsample is not None:
self.downsample = downsample(dim=dim)
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 SpatialMamba(nn.Module):
def init (self,
img_size=224,
patch_size=4,
in_chans=3,
num_classes=1000,
depths=[2, 2, 9, 2],
dims=[96, 192, 384, 768],
d_state=1,
dt_init="random",
mlp_ratio=4.0,
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
code Copy code
self.patch_embed = Stem(img_size=img_size, patch_size=patch_size, in_chans=in_chans, embed_dim=self.embed_dim )
self.ape = False
if self.ape:
self.patches_resolution = self.patch_embed.patches_resolution
self.absolute_pos_embed = 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
self.layers = nn.ModuleList()
for i_layer in range(self.num_layers):
layer = SpatialMambaLayer(
dim=dims[i_layer],
depth=depths[i_layer],
d_state=math.ceil(dims[0] / 6) if d_state is None else d_state, # 20240109
dt_init=dt_init,
mlp_ratio=mlp_ratio,
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=DownSampling if (i_layer < self.num_layers - 1) else None,
use_checkpoint=use_checkpoint,
)
self.layers.append(layer)
self.norm = norm_layer(self.num_features)
self.avgpool = nn.AdaptiveAvgPool1d(1)
self.head = nn.Linear(self.num_features, num_classes) if num_classes > 0 else nn.Identity()
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 flops(self, shape=(3, 224, 224), verbose=True):
# shape = self.__input_shape__[1:]
supported_ops={
"aten::silu": None, # as relu is in _IGNORED_OPS
"aten::neg": None, # as relu is in _IGNORED_OPS
"aten::exp": None, # as relu is in _IGNORED_OPS
"aten::flip": None, # as permute is in _IGNORED_OPS
"prim::PythonOp.SelectiveScanStateFn": selective_scan_state_flop_jit,
}
model = copy.deepcopy(self)
model.cuda()#.eval()
input = torch.randn((1, *shape), device=next(model.parameters()).device)
params = parameter_count(model)[""]
Gflops, unsupported = flop_count(model=model, inputs=(input,), supported_ops=supported_ops)
del model, input
return sum(Gflops.values()) * 1e9
return f"params {params} GFLOPs {sum(Gflops.values())}"
def forward_features(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)
x = torch.flatten(x, 1, 2)
x = self.norm(x)
x = self.avgpool(x.transpose(1, 2))
x = torch.flatten(x, 1)
return x
def forward(self, x):
x = self.forward_features(x)
x = self.head(x)
return x
class Backbone_SpatialMamba(SpatialMamba):
def init (self, out_indices=(0, 1, 2, 3), pretrained=None, norm_layer="ln", **kwargs):
code Copy code
super().__init__(**kwargs)
self.channel_first = (norm_layer.lower() in ["bn", "ln2d"])
_NORMLAYERS = dict(
ln=nn.LayerNorm,
bn=nn.BatchNorm2d,
)
norm_layer: nn.Module = _NORMLAYERS.get(norm_layer.lower(), None)
kwargs.update(norm_layer=norm_layer)
# add norm ========================
self.out_indices = out_indices
for i in out_indices:
layer = norm_layer(self.dims[i])
layer_name = f'outnorm{i}'
self.add_module(layer_name, layer)
# modify layer ========================
def layer_forward(self: SpatialMambaLayer, x):
for blk in self.blocks:
if self.use_checkpoint:
x = checkpoint.checkpoint(blk, x)
else:
x = blk(x)
y = None
if self.downsample is not None:
y = self.downsample(x)
return x, y
for l in self.layers:
l.forward = partial(layer_forward, l)
# del self.classifier ===================
del self.head
del self.avgpool
del self.norm
self.load_pretrained(pretrained, key=kwargs.get('key','model'))
def load_pretrained(self, ckpt=None, key="model"):
if ckpt is None:
return
try:
_ckpt = torch.load(open(ckpt, "rb"), map_location=torch.device("cpu"))
print(f"Successfully load ckpt {ckpt}")
incompatibleKeys = self.load_state_dict(_ckpt[key], strict=False)
print(incompatibleKeys)
except Exception as e:
print(f"Failed loading checkpoint form {ckpt}: {e}")
def forward(self, x):
x = self.patch_embed(x)
outs = []
for i, layer in enumerate(self.layers):
o, x = layer(x)
if i in self.out_indices:
norm_layer = getattr(self, f'outnorm{i}')
out = norm_layer(o)
if not self.channel_first:
out = out.permute(0, 3, 1, 2).contiguous()
outs.append(out)
if len(self.out_indices) == 0:
return x
return outs
init
code Copy code
This Block has a slightly different structure compared to a regular
prenorm Transformer block.
The standard block is: LN -> MHA/MLP -> Add.
[Ref: https://arxiv.org/abs/2002.04745]
Here we have: Add -> LN -> Mixer, returning both
the hidden_states (output of the mixer) and the residual.
This is purely for performance reasons, as we can fuse add and LayerNorm.
The residual needs to be provided (except for the very first block).
"""
super().__init__()
self.residual_in_fp32 = residual_in_fp32
self.fused_add_norm = fused_add_norm
self.mixer = mixer_cls(dim)
self.norm = norm_cls(dim)
self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
if self.fused_add_norm:
assert RMSNorm is not None, "RMSNorm import fails"
assert isinstance(
self.norm, (nn.LayerNorm, RMSNorm)
), "Only LayerNorm and RMSNorm are supported for fused_add_norm"
def forward(
self, hidden_states: Tensor, residual: Optional[Tensor] = None, inference_params=None
):
r"""Pass the input through the encoder layer.
Args:
hidden_states: the sequence to the encoder layer (required).
residual: hidden_states = Mixer(LN(residual))
"""
if not self.fused_add_norm:
if residual is None:
residual = hidden_states
else:
residual = residual + self.drop_path(hidden_states)
hidden_states = self.norm(residual.to(dtype=self.norm.weight.dtype))
if self.residual_in_fp32:
residual = residual.to(torch.float32)
else:
fused_add_norm_fn = rms_norm_fn if isinstance(self.norm, RMSNorm) else layer_norm_fn
if residual is None:
hidden_states, residual = fused_add_norm_fn(
hidden_states,
self.norm.weight,
self.norm.bias,
residual=residual,
prenorm=True,
residual_in_fp32=self.residual_in_fp32,
eps=self.norm.eps,
)
else:
hidden_states, residual = fused_add_norm_fn(
self.drop_path(hidden_states),
self.norm.weight,
self.norm.bias,
residual=residual,
prenorm=True,
residual_in_fp32=self.residual_in_fp32,
eps=self.norm.eps,
)
hidden_states = self.mixer(hidden_states, inference_params=inference_params)
return hidden_states, residual
def allocate_inference_cache(self, batch_size, max_seqlen, dtype=None, **kwargs):
return self.mixer.allocate_inference_cache(batch_size, max_seqlen, dtype=dtype, **kwargs)
def create_block(
d_model,
ssm_cfg=None,
norm_epsilon=1e-5,
drop_path=0.,
rms_norm=False,
residual_in_fp32=False,
fused_add_norm=False,
layer_idx=None,
device=None,
dtype=None,
if_bimamba=False,
bimamba_type="none",
if_devide_out=False,
init_layer_scale=None,
):
if if_bimamba:
bimamba_type = "v1"
if ssm_cfg is None:
ssm_cfg = {}
factory_kwargs = {"device": device, "dtype": dtype}
mixer_cls = partial(Mamba, layer_idx=layer_idx, bimamba_type=bimamba_type, if_devide_out=if_devide_out, init_layer_scale=init_layer_scale, **ssm_cfg, **factory_kwargs)
norm_cls = partial(
nn.LayerNorm if not rms_norm else RMSNorm, eps=norm_epsilon, **factory_kwargs
)
block = Block(
d_model,
mixer_cls,
norm_cls=norm_cls,
drop_path=drop_path,
fused_add_norm=fused_add_norm,
residual_in_fp32=residual_in_fp32,
)
block.layer_idx = layer_idx
return block
def init_weights(
module,
n_layer,
initializer_range=0.02, # Now only used for embedding layer.
rescale_prenorm_residual=True,
n_residuals_per_layer=1, # Change to 2 if we have MLP
):
if isinstance(module, nn.Linear):
if module.bias is not None:
if not getattr(module.bias, "no_reinit", False):
nn.init.zeros (module.bias)
elif isinstance(module, nn.Embedding):
nn.init.normal (module.weight, std=initializer_range)
code Copy code
if rescale_prenorm_residual:
# Reinitialize selected weights subject to the OpenAI GPT-2 Paper Scheme:
# > A modified initialization which accounts for the accumulation on the residual path with model depth. Scale
# > the weights of residual layers at initialization by a factor of 1/√N where N is the # of residual layers.
# > -- GPT-2 :: https://openai.com/blog/better-language-models/
#
# Reference (Megatron-LM): https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/model/gpt_model.py
for name, p in module.named_parameters():
if name in ["out_proj.weight", "fc2.weight"]:
# Special Scaled Initialization --> There are 2 Layer Norms per Transformer Block
# Following Pytorch init, except scale by 1/sqrt(2 * n_layer)
# We need to reinit p since this code could be called multiple times
# Having just p *= scale would repeatedly scale it down
nn.init.kaiming_uniform_(p, a=math.sqrt(5))
with torch.no_grad():
p /= math.sqrt(n_residuals_per_layer * n_layer)
def segm_init_weights(m):
if isinstance(m, nn.Linear):
trunc_normal_(m.weight, std=0.02)
if isinstance(m, nn.Linear) and m.bias is not None:
nn.init.constant_(m.bias, 0)
elif isinstance(m, nn.Conv2d):
# NOTE conv was left to pytorch default in my original init
lecun_normal_(m.weight)
if m.bias is not None:
nn.init.zeros_(m.bias)
elif isinstance(m, (nn.LayerNorm, nn.GroupNorm, nn.BatchNorm2d)):
nn.init.zeros_(m.bias)
nn.init.ones_(m.weight)
class VisionMamba(nn.Module):
def init (self,
img_size=224,
patch_size=16,
stride=16,
depth=24,
embed_dim=192,
channels=3,
num_classes=1000,
ssm_cfg=None,
drop_rate=0.,
drop_path_rate=0.1,
norm_epsilon: float = 1e-5,
rms_norm: bool = False,
initializer_cfg=None,
fused_add_norm=False,
residual_in_fp32=False,
device=None,
dtype=None,
ft_seq_len=None,
pt_hw_seq_len=14,
if_bidirectional=False,
final_pool_type='none',
if_abs_pos_embed=False,
if_rope=False,
if_rope_residual=False,
flip_img_sequences_ratio=-1.,
if_bimamba=False,
bimamba_type="none",
if_cls_token=False,
if_devide_out=False,
init_layer_scale=None,
use_double_cls_token=False,
use_middle_cls_token=False,
**kwargs):
factory_kwargs = {"device": device, "dtype": dtype}
# add factory_kwargs into kwargs
kwargs.update(factory_kwargs)
super().init ()
self.residual_in_fp32 = residual_in_fp32
self.fused_add_norm = fused_add_norm
self.if_bidirectional = if_bidirectional
self.final_pool_type = final_pool_type
self.if_abs_pos_embed = if_abs_pos_embed
self.if_rope = if_rope
self.if_rope_residual = if_rope_residual
self.flip_img_sequences_ratio = flip_img_sequences_ratio
# self.if_cls_token = if_cls_token
self.if_cls_token = False
self.use_double_cls_token = use_double_cls_token
self.use_middle_cls_token = use_middle_cls_token
self.num_tokens = 1 if if_cls_token else 0
code Copy code
# pretrain parameters
self.num_classes = num_classes
self.d_model = self.num_features = self.embed_dim = embed_dim # num_features for consistency with other models
self.patch_embed = PatchEmbed(
img_size=img_size, patch_size=patch_size, stride=stride, in_chans=channels, embed_dim=embed_dim)
num_patches = self.patch_embed.num_patches
if if_cls_token:
if use_double_cls_token:
self.cls_token_head = nn.Parameter(torch.zeros(1, 1, self.embed_dim))
self.cls_token_tail = nn.Parameter(torch.zeros(1, 1, self.embed_dim))
self.num_tokens = 2
else:
self.cls_token = nn.Parameter(torch.zeros(1, 1, self.embed_dim))
# self.num_tokens = 1
if if_abs_pos_embed:
# self.pos_embed = nn.Parameter(torch.zeros(1, num_patches + self.num_tokens, self.embed_dim))
self.pos_embed_x = nn.Parameter(torch.zeros(1, 256, self.embed_dim))
self.pos_embed_z = nn.Parameter(torch.zeros(1, 64, self.embed_dim))
self.pos_drop = nn.Dropout(p=drop_rate)
if if_rope:
half_head_dim = embed_dim // 2
hw_seq_len = img_size // patch_size
self.rope = VisionRotaryEmbeddingFast(
dim=half_head_dim,
pt_seq_len=pt_hw_seq_len,
ft_seq_len=hw_seq_len
)
# self.head = nn.Linear(self.num_features, num_classes) if num_classes > 0 else nn.Identity()
# settings = ws_settings.Settings()
# config_module = importlib.import_module("lib.config.%s.config" % settings.script_name)
# cfg = config_module.cfg
# self.head = build_box_head(cfg, embed_dim)
# TODO: release this comment
dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)] # stochastic depth decay rule
# import ipdb;ipdb.set_trace()
inter_dpr = [0.0] + dpr
self.drop_path = DropPath(drop_path_rate) if drop_path_rate > 0. else nn.Identity()
# transformer blocks
self.layers = nn.ModuleList(
[
create_block(
embed_dim,
ssm_cfg=ssm_cfg,
norm_epsilon=norm_epsilon,
rms_norm=rms_norm,
residual_in_fp32=residual_in_fp32,
fused_add_norm=fused_add_norm,
layer_idx=i,
if_bimamba=if_bimamba,
bimamba_type=bimamba_type,
drop_path=inter_dpr[i],
if_devide_out=if_devide_out,
init_layer_scale=init_layer_scale,
**factory_kwargs,
)
for i in range(depth)
]
)
# output head
self.norm_f = (nn.LayerNorm if not rms_norm else RMSNorm)(
embed_dim, eps=norm_epsilon, **factory_kwargs
)
# self.pre_logits = nn.Identity()
# original init
self.patch_embed.apply(segm_init_weights)
# self.head.apply(segm_init_weights)
if if_abs_pos_embed:
trunc_normal_(self.pos_embed_x, std=.02)
trunc_normal_(self.pos_embed_z, std=.02)
if if_cls_token:
if use_double_cls_token:
trunc_normal_(self.cls_token_head, std=.02)
trunc_normal_(self.cls_token_tail, std=.02)
else:
trunc_normal_(self.cls_token, std=.02)
# mamba init
self.apply(
partial(
_init_weights,
n_layer=depth,
**(initializer_cfg if initializer_cfg is not None else {}),
)
)
def allocate_inference_cache(self, batch_size, max_seqlen, dtype=None, **kwargs):
return {
i: layer.allocate_inference_cache(batch_size, max_seqlen, dtype=dtype, **kwargs)
for i, layer in enumerate(self.layers)
}
@torch.jit.ignore
def no_weight_decay(self):
return {"pos_embed", "cls_token", "dist_token", "cls_token_head", "cls_token_tail"}
@torch.jit.ignore()
def load_pretrained(self, checkpoint_path, prefix=""):
_load_weights(self, checkpoint_path, prefix)
def forward_features(self, z, x, inference_params=None, if_random_cls_token_position=False, if_random_token_rank=False):
# taken from https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/vision_transformer.py
# with slight modifications to add the dist_token
x = self.patch_embed(x) #x.shape = torch.Size([B, 3, 256, 256]) -> torch.Size([2, 256, 384])
z = self.patch_embed(z) #z.shape = torch.Size([B, 3, 128, 128]) -> torch.Size([2, 64, 384])
B, M, _ = x.shape
if self.if_cls_token: # False
if self.use_double_cls_token:
cls_token_head = self.cls_token_head.expand(B, -1, -1)
cls_token_tail = self.cls_token_tail.expand(B, -1, -1)
token_position = [0, M + 1]
x = torch.cat((cls_token_head, x, cls_token_tail), dim=1)
M = x.shape[1]
else:
if self.use_middle_cls_token:
cls_token = self.cls_token.expand(B, -1, -1)
token_position = M // 2
# add cls token in the middle
x = torch.cat((x[:, :token_position, :], cls_token, x[:, token_position:, :]), dim=1)
elif if_random_cls_token_position:
cls_token = self.cls_token.expand(B, -1, -1)
token_position = random.randint(0, M)
x = torch.cat((x[:, :token_position, :], cls_token, x[:, token_position:, :]), dim=1)
print("token_position: ", token_position)
else:
cls_token = self.cls_token.expand(B, -1, -1) # stole cls_tokens impl from Phil Wang, thanks
token_position = 0
x = torch.cat((cls_token, x), dim=1)
M = x.shape[1]
if self.if_abs_pos_embed: # True
x = x + self.pos_embed_x # x = x + positon_embemding =torch.Size([B, 256, 384]) + torch.Size([1, 256, 384]) = torch.Size([B, 256, 384])
z = z + self.pos_embed_z # z = z + positon_embemding =torch.Size([B, 64, 384]) + torch.Size([1, 64, 384]) = torch.Size([B, 64, 384])
x = torch.cat((z, x), dim=1) # torch.Size([B, 320, 384])
x = self.pos_drop(x) # x.shape = torch.Size([B, 320, 384])
if if_random_token_rank: #False
# 生成随机 shuffle 索引
shuffle_indices = torch.randperm(M)
if isinstance(token_position, list):
print("original value: ", x[0, token_position[0], 0], x[0, token_position[1], 0])
else:
print("original value: ", x[0, token_position, 0])
print("original token_position: ", token_position)
# 执行 shuffle
x = x[:, shuffle_indices, :]
if isinstance(token_position, list):
# 找到 cls token 在 shuffle 之后的新位置
new_token_position = [torch.where(shuffle_indices == token_position[i])[0].item() for i in range(len(token_position))]
token_position = new_token_position
else:
# 找到 cls token 在 shuffle 之后的新位置
token_position = torch.where(shuffle_indices == token_position)[0].item()
if isinstance(token_position, list):
print("new value: ", x[0, token_position[0], 0], x[0, token_position[1], 0])
else:
print("new value: ", x[0, token_position, 0])
print("new token_position: ", token_position)
if_flip_img_sequences = False
if self.flip_img_sequences_ratio > 0 and (self.flip_img_sequences_ratio - random.random()) > 1e-5: # False
x = x.flip([1])
if_flip_img_sequences = True
# mamba impl
residual = None
hidden_states = x
if not self.if_bidirectional: # True
for layer in self.layers:
if if_flip_img_sequences and self.if_rope: # False
hidden_states = hidden_states.flip([1])
if residual is not None:
residual = residual.flip([1])
# rope about
if self.if_rope: # False
hidden_states = self.rope(hidden_states)
if residual is not None and self.if_rope_residual:
residual = self.rope(residual)
if if_flip_img_sequences and self.if_rope: # False
hidden_states = hidden_states.flip([1])
if residual is not None:
residual = residual.flip([1])
hidden_states, residual = layer(
hidden_states, residual, inference_params=inference_params
)
else: # False
# get two layers in a single for-loop
for i in range(len(self.layers) // 2):
if self.if_rope:
hidden_states = self.rope(hidden_states)
if residual is not None and self.if_rope_residual:
residual = self.rope(residual)
hidden_states_f, residual_f = self.layers[i * 2](
hidden_states, residual, inference_params=inference_params
)
hidden_states_b, residual_b = self.layers[i * 2 + 1](
hidden_states.flip([1]), None if residual == None else residual.flip([1]), inference_params=inference_params
)
hidden_states = hidden_states_f + hidden_states_b.flip([1])
residual = residual_f + residual_b.flip([1])
if not self.fused_add_norm: #False
if residual is None:
residual = hidden_states
else:
residual = residual + self.drop_path(hidden_states)
hidden_states = self.norm_f(residual.to(dtype=self.norm_f.weight.dtype))
else: #True
# Set prenorm=False here since we don't need the residual
fused_add_norm_fn = rms_norm_fn if isinstance(self.norm_f, RMSNorm) else layer_norm_fn
hidden_states = fused_add_norm_fn( # hidden_states.shape = torch.Size([B, 320, 384])
self.drop_path(hidden_states),
self.norm_f.weight,
self.norm_f.bias,
eps=self.norm_f.eps,
residual=residual,
prenorm=False,
residual_in_fp32=self.residual_in_fp32,
)
# return only cls token if it exists
if self.if_cls_token: #False
if self.use_double_cls_token:
return (hidden_states[:, token_position[0], :] + hidden_states[:, token_position[1], :]) / 2
else:
if self.use_middle_cls_token:
return hidden_states[:, token_position, :]
elif if_random_cls_token_position:
return hidden_states[:, token_position, :]
else:
return hidden_states[:, token_position, :]
if self.final_pool_type == 'none':
return hidden_states[:, -1, :]
elif self.final_pool_type == 'mean': #True
return hidden_states.mean(dim=1) #hidden_states.shape = torch.Size([2, 384])
elif self.final_pool_type == 'max':
return hidden_states
elif self.final_pool_type == 'all':
return hidden_states
else:
raise NotImplementedError
def forward(self, x, return_features=False, inference_params=None, if_random_cls_token_position=False, if_random_token_rank=False):
x = self.forward_features(x, inference_params, if_random_cls_token_position=if_random_cls_token_position, if_random_token_rank=if_random_token_rank)
if return_features:
return x
x = self.head(x)
if self.final_pool_type == 'max':
x = x.max(dim=1)[0]
return x
@register_model
def vim_tiny_patch16_224_bimambav2_final_pool_mean_abs_pos_embed_with_midclstok_div2(pretrained=False, **kwargs):
model = VisionMamba(
patch_size=16, embed_dim=192, depth=24, rms_norm=True, residual_in_fp32=True, fused_add_norm=True, final_pool_type='mean', if_abs_pos_embed=True, if_rope=False, if_rope_residual=False, bimamba_type="v2", if_cls_token=True, if_devide_out=True, use_middle_cls_token=True, **kwargs)
model.default_cfg = _cfg()
if pretrained:
checkpoint = torch.hub.load_state_dict_from_url(
url="to.do",
map_location="cpu", check_hash=True
)
model.load_state_dict(checkpoint["model"])
return model
@register_model
def vim_tiny_patch16_stride8_224_bimambav2_final_pool_mean_abs_pos_embed_with_midclstok_div2(pretrained=False, **kwargs):
model = VisionMamba(
patch_size=16, stride=8, embed_dim=192, depth=24, rms_norm=True, residual_in_fp32=True, fused_add_norm=True, final_pool_type='mean', if_abs_pos_embed=True, if_rope=False, if_rope_residual=False, bimamba_type="v2", if_cls_token=True, if_devide_out=True, use_middle_cls_token=True, **kwargs)
model.default_cfg = _cfg()
if pretrained:
checkpoint = torch.hub.load_state_dict_from_url(
url="to.do",
map_location="cpu", check_hash=True
)
model.load_state_dict(checkpoint["model"])
return model
@register_model
def vim_small_patch16_224_bimambav2_final_pool_mean_abs_pos_embed_with_midclstok_div2(pretrained=False, **kwargs):
model = VisionMamba(
patch_size=16, embed_dim=384, depth=24, rms_norm=True, residual_in_fp32=True, fused_add_norm=True, final_pool_type='all', if_abs_pos_embed=True, if_rope=False, if_rope_residual=False, bimamba_type="v2", if_cls_token=True, if_devide_out=True, use_middle_cls_token=True, **kwargs)
model.default_cfg = _cfg()
code Copy code
if pretrained:
# checkpoint = torch.hub.load_state_dict_from_url(
# url="to.do",
# map_location="cpu", check_hash=True
# )
# model.load_state_dict(checkpoint["model"])
checkpoint = torch.load(pretrained, map_location="cpu")
missing_keys, unexpected_keys = model.load_state_dict(checkpoint["model"], strict=False)
print('Load pretrained model from: ' + pretrained)
return model
@register_model
def vim_small_patch16_stride8_224_bimambav2_final_pool_mean_abs_pos_embed_with_midclstok_div2(pretrained=False, **kwargs):
model = VisionMamba(
patch_size=16, stride=8, embed_dim=384, depth=24, rms_norm=True, residual_in_fp32=True, fused_add_norm=True, final_pool_type='mean', if_abs_pos_embed=True, if_rope=False, if_rope_residual=False, bimamba_type="v2", if_cls_token=True, if_devide_out=True, use_middle_cls_token=True, **kwargs)
model.default_cfg = _cfg()
if pretrained:
checkpoint = torch.hub.load_state_dict_from_url(
url="to.do",
map_location="cpu", check_hash=True
)
model.load_state_dict(checkpoint["model"])
return model
中,是否可以借鉴Spatial-Mamba模型中的设计?
import torch
import torch.nn as nn
import torch.nn.functional as F
class StateFusion(nn.Module):
def __init__(self, dim):
super(StateFusion, self).__init__()
self.dim = dim
self.kernel_3 = nn.Parameter(torch.ones(dim, 1, 3, 3))
self.kernel_3_1 = nn.Parameter(torch.ones(dim, 1, 3, 3))
self.kernel_3_2 = nn.Parameter(torch.ones(dim, 1, 3, 3))
self.alpha = nn.Parameter(torch.ones(3), requires_grad=True)
@staticmethod
def padding(input_tensor, padding):
return F.pad(input_tensor, padding, mode='replicate')
def forward(self, h):
h1 = F.conv2d(self.padding(h, (1,1,1,1)), self.kernel_3, padding=0, dilation=1, groups=self.dim)
h2 = F.conv2d(self.padding(h, (3,3,3,3)), self.kernel_3_1, padding=0, dilation=3, groups=self.dim)
h3 = F.conv2d(self.padding(h, (5,5,5,5)), self.kernel_3_2, padding=0, dilation=5, groups=self.dim)
out = self.alpha[0]*h1 + self.alpha[1]*h2 + self.alpha[2]*h3
return out
# Integrating StateFusion into VisionMamba
class VisionMambaWithStateFusion(nn.Module):
def __init__(self,
img_size=224,
patch_size=16,
stride=16,
depth=24,
embed_dim=192,
channels=3,
num_classes=1000,
ssm_cfg=None,
drop_rate=0.,
drop_path_rate=0.1,
norm_epsilon: float = 1e-5,
rms_norm: bool = False,
initializer_cfg=None,
fused_add_norm=False,
residual_in_fp32=False,
device=None,
dtype=None,
**kwargs
):
super().__init__()
self.embed_dim = embed_dim
self.patch_embed = PatchEmbed(
img_size=img_size, patch_size=patch_size, stride=stride, in_chans=channels, embed_dim=embed_dim
)
# Apply StateFusion after patch embedding
self.state_fusion = StateFusion(embed_dim)
self.layers = nn.ModuleList(
[
create_block(embed_dim) for _ in range(depth)
]
)
self.norm_f = nn.LayerNorm(embed_dim, eps=norm_epsilon)
self.head = nn.Linear(embed_dim, num_classes) if num_classes > 0 else nn.Identity()
def forward_features(self, x):
x = self.patch_embed(x)
# Apply state fusion
x = self.state_fusion(x.permute(0, 2, 1).reshape(-1, self.embed_dim, int(x.size(1)**0.5), int(x.size(1)**0.5)))
x = x.view(x.size(0), self.embed_dim, -1).permute(0, 2, 1)
for layer in self.layers:
x, _ = layer(x)
x = self.norm_f(x)
return x.mean(dim=1)
def forward(self, x):
x = self.forward_features(x)
x = self.head(x)
return x
解释
StateFusion Module :
定义了一个多尺度卷积模块,可处理输入特征,同时应用不同的卷积核和尺度。
alpha 是可学习的权重,可以调整各尺度特征在总输出中的贡献。
Integration :
StateFusion 被集成到 VisionMamba 中的特征抽取阶段。
在进行 patch_embed 后,立即应用 StateFusion 以在低层次融合多种空间特征。
通过这样的集成,VisionMamba 在特征嵌入阶段能够更好地处理多尺度信息,提高模型对输入图像复杂性的敏感度。可以按需调试以适应特定任务和数据。
解释
Patch Embedding : 将输入图像分块并通过卷积投影到嵌入空间。
StateFusion : 在 patch embedding 之后,StateFusion 被应用于其特征图上,通过多尺度卷积增强空域特征。
Reshaping : StateFusion 需要输入具有 (B, C, H, W) 格式,应用完成后我们将它转换回 (B, N, C) 格式。
Transformer Blocks : 执行以序列为基础的转换块;这些块负责进一步提取和处理全局特征。
Normalization and Pooling : 使用图层归一化调整特征,再通过均值池化将序列维度减少到单个向量(代表全图特征)。
这个设计对于 VisionMamba 模型增加 Spatial-Awareness 处理能力可能有显著的提升,加强模型对多尺度与空间特征的处理。
if self.if_cls_token: # False
if self.use_double_cls_token:
cls_token_head = self.cls_token_head.expand(B, -1, -1)
cls_token_tail = self.cls_token_tail.expand(B, -1, -1)
token_position = [0, M + 1]
x = torch.cat((cls_token_head, x, cls_token_tail), dim=1)
M = x.shape[1]
else:
if self.use_middle_cls_token:
cls_token = self.cls_token.expand(B, -1, -1)
token_position = M // 2
# add cls token in the middle
x = torch.cat((x[:, :token_position, :], cls_token, x[:, token_position:, :]), dim=1)
elif if_random_cls_token_position:
cls_token = self.cls_token.expand(B, -1, -1)
token_position = random.randint(0, M)
x = torch.cat((x[:, :token_position, :], cls_token, x[:, token_position:, :]), dim=1)
print("token_position: ", token_position)
else:
cls_token = self.cls_token.expand(B, -1, -1) # stole cls_tokens impl from Phil Wang, thanks
token_position = 0
x = torch.cat((cls_token, x), dim=1)
M = x.shape[1]
if self.if_abs_pos_embed: # True
x = x + self.pos_embed_x # x = x + positon_embemding =torch.Size([B, 256, 384]) + torch.Size([1, 256, 384]) = torch.Size([B, 256, 384])
z = z + self.pos_embed_z # z = z + positon_embemding =torch.Size([B, 64, 384]) + torch.Size([1, 64, 384]) = torch.Size([B, 64, 384])
x = torch.cat((z, x), dim=1) # torch.Size([B, 320, 384])
x = self.pos_drop(x) # x.shape = torch.Size([B, 320, 384])
if if_random_token_rank: #False
# 生成随机 shuffle 索引
shuffle_indices = torch.randperm(M)
if isinstance(token_position, list):
print("original value: ", x[0, token_position[0], 0], x[0, token_position[1], 0])
else:
print("original value: ", x[0, token_position, 0])
print("original token_position: ", token_position)
# 执行 shuffle
x = x[:, shuffle_indices, :]
if isinstance(token_position, list):
# 找到 cls token 在 shuffle 之后的新位置
new_token_position = [torch.where(shuffle_indices == token_position[i])[0].item() for i in range(len(token_position))]
token_position = new_token_position
else:
# 找到 cls token 在 shuffle 之后的新位置
token_position = torch.where(shuffle_indices == token_position)[0].item()
if isinstance(token_position, list):
print("new value: ", x[0, token_position[0], 0], x[0, token_position[1], 0])
else:
print("new value: ", x[0, token_position, 0])
print("new token_position: ", token_position)
if_flip_img_sequences = False
if self.flip_img_sequences_ratio > 0 and (self.flip_img_sequences_ratio - random.random()) > 1e-5: # False
x = x.flip([1])
if_flip_img_sequences = True
# mamba impl
residual = None
hidden_states = x
if not self.if_bidirectional: # True
for layer in self.layers:
if if_flip_img_sequences and self.if_rope: # False
hidden_states = hidden_states.flip([1])
if residual is not None:
residual = residual.flip([1])
# rope about
if self.if_rope: # False
hidden_states = self.rope(hidden_states)
if residual is not None and self.if_rope_residual:
residual = self.rope(residual)
if if_flip_img_sequences and self.if_rope: # False
hidden_states = hidden_states.flip([1])
if residual is not None:
residual = residual.flip([1])
hidden_states, residual = layer(
hidden_states, residual, inference_params=inference_params
)
else: # False
# get two layers in a single for-loop
for i in range(len(self.layers) // 2):
if self.if_rope:
hidden_states = self.rope(hidden_states)
if residual is not None and self.if_rope_residual:
residual = self.rope(residual)
hidden_states_f, residual_f = self.layers[i * 2](
hidden_states, residual, inference_params=inference_params
)
hidden_states_b, residual_b = self.layers[i * 2 + 1](
hidden_states.flip([1]), None if residual == None else residual.flip([1]), inference_params=inference_params
)
hidden_states = hidden_states_f + hidden_states_b.flip([1])
residual = residual_f + residual_b.flip([1])
if not self.fused_add_norm: #False
if residual is None:
residual = hidden_states
else:
residual = residual + self.drop_path(hidden_states)
hidden_states = self.norm_f(residual.to(dtype=self.norm_f.weight.dtype))
else: #True
# Set prenorm=False here since we don't need the residual
fused_add_norm_fn = rms_norm_fn if isinstance(self.norm_f, RMSNorm) else layer_norm_fn
hidden_states = fused_add_norm_fn( # hidden_states.shape = torch.Size([B, 320, 384])
self.drop_path(hidden_states),
self.norm_f.weight,
self.norm_f.bias,
eps=self.norm_f.eps,
residual=residual,
prenorm=False,
residual_in_fp32=self.residual_in_fp32,
)
# return only cls token if it exists
if self.if_cls_token: #False
if self.use_double_cls_token:
return (hidden_states[:, token_position[0], :] + hidden_states[:, token_position[1], :]) / 2
else:
if self.use_middle_cls_token:
return hidden_states[:, token_position, :]
elif if_random_cls_token_position:
return hidden_states[:, token_position, :]
else:
return hidden_states[:, token_position, :]
if self.final_pool_type == 'none':
return hidden_states[:, -1, :]
elif self.final_pool_type == 'mean': #True
return hidden_states.mean(dim=1) #hidden_states.shape = torch.Size([2, 384])
elif self.final_pool_type == 'max':
return hidden_states
elif self.final_pool_type == 'all':
return hidden_states
else:
raise NotImplementedError
,现在把self.state_fusion加进去。
import torch
import torch.nn as nn
import torch.nn.functional as F
# 定义 StateFusion 模块
class StateFusion(nn.Module):
def __init__(self, dim):
super(StateFusion, self).__init__()
self.dim = dim
self.kernel_3 = nn.Parameter(torch.ones(dim, 1, 3, 3))
self.kernel_3_1 = nn.Parameter(torch.ones(dim, 1, 3, 3))
self.kernel_3_2 = nn.Parameter(torch.ones(dim, 1, 3, 3))
self.alpha = nn.Parameter(torch.ones(3), requires_grad=True)
@staticmethod
def padding(input_tensor, padding):
return F.pad(input_tensor, padding, mode='replicate')
def forward(self, h):
h1 = F.conv2d(self.padding(h, (1,1,1,1)), self.kernel_3, padding=0, dilation=1, groups=self.dim)
h2 = F.conv2d(self.padding(h, (3,3,3,3)), self.kernel_3_1, padding=0, dilation=3, groups=self.dim)
h3 = F.conv2d(self.padding(h, (5,5,5,5)), self.kernel_3_2, padding=0, dilation=5, groups=self.dim)
out = self.alpha[0]*h1 + self.alpha[1]*h2 + self.alpha[2]*h3
return out
class VisionMambaWithStateFusion(nn.Module):
# 初始化 ...
def __init__(self,
img_size=224,
patch_size=16,
stride=16,
depth=24,
embed_dim=192,
channels=3,
num_classes=1000,
drop_rate=0.,
norm_epsilon: float = 1e-5,
# 其他参数 ...
):
super().__init__()
self.embed_dim = embed_dim
self.patch_embed = PatchEmbed(img_size=img_size, patch_size=patch_size, stride=stride, in_chans=channels, embed_dim=embed_dim)
self.state_fusion = StateFusion(embed_dim) # 增加 StateFusion
# 其他初始化...
self.layers = nn.ModuleList([
create_block(embed_dim) for _ in range(depth)
])
self.norm_f = nn.LayerNorm(embed_dim, eps=norm_epsilon)
def forward_features(self, z, x, inference_params=None, if_random_cls_token_position=False, if_random_token_rank=False):
x = self.patch_embed(x)
z = self.patch_embed(z)
# 使用 StateFusion 增强特征
x = x.permute(0, 2, 1).reshape(-1, self.embed_dim, int(self.patch_embed.grid_size[0]), int(self.patch_embed.grid_size[1]))
z = z.permute(0, 2, 1).reshape(-1, self.embed_dim, int(self.patch_embed.grid_size[0] // 2), int(self.patch_embed.grid_size[1] // 2))
x = self.state_fusion(x).view(x.size(0), self.embed_dim, -1).permute(0, 2, 1)
z = self.state_fusion(z).view(z.size(0), self.embed_dim, -1).permute(0, 2, 1)
B, M, _ = x.shape
# 下方保持原样...
if self.if_abs_pos_embed:
x = x + self.pos_embed_x
z = z + self.pos_embed_z
x = torch.cat((z, x), dim=1)
x = self.pos_drop(x)
residual = None
hidden_states = x
if not self.if_bidirectional:
for layer in self.layers:
hidden_states, residual = layer(
hidden_states, residual, inference_params=inference_params
)
if not self.fused_add_norm:
if residual is None:
residual = hidden_states
else:
residual = residual + self.drop_path(hidden_states)
hidden_states = self.norm_f(residual.to(dtype=self.norm_f.weight.dtype))
else:
fused_add_norm_fn = rms_norm_fn if isinstance(self.norm_f, RMSNorm) else layer_norm_fn
hidden_states = fused_add_norm_fn(
self.drop_path(hidden_states),
self.norm_f.weight,
self.norm_f.bias,
eps=self.norm_f.eps,
residual=residual,
prenorm=False,
residual_in_fp32=self.residual_in_fp32,
)
if self.final_pool_type == 'none':
return hidden_states[:, -1, :]
elif self.final_pool_type == 'mean':
return hidden_states.mean(dim=1)
elif self.final_pool_type == 'max':
return hidden_states
elif self.final_pool_type == 'all':
return hidden_states
else:
raise NotImplementedError
# forward 函数...
解释
StateFusion Integration :
在特征嵌入之后,应用 StateFusion 来强化输入特征,增强空间感知能力。
通过不同尺寸卷积核提升特征的多层次处理。
修改特征流 :
在 patch_embed 之后,对 x 和 z 应用 StateFusion。
StateFusion 采用不同尺度展开特征,并返回至网络中以继续处理。
这种集成设计利用 StateFusion 来进一步强化特征的空间信息处理,确保模型能够更好地捕捉复杂图像中的细节特征。请根据实际需求进一步调试模型的参数与细节。
import torch
import torch.nn as nn
import torch.nn.functional as F
# 假设 StateFusion 模块已被定义
class StateFusion(nn.Module):
def __init__(self, dim):
super(StateFusion, self).__init__()
self.dim = dim
self.kernel_3 = nn.Parameter(torch.ones(dim, 1, 3, 3))
self.kernel_3_1 = nn.Parameter(torch.ones(dim, 1, 3, 3))
self.kernel_3_2 = nn.Parameter(torch.ones(dim, 1, 3, 3))
self.alpha = nn.Parameter(torch.ones(3), requires_grad=True)
@staticmethod
def padding(input_tensor, padding):
return F.pad(input_tensor, padding, mode='replicate')
def forward(self, h):
h1 = F.conv2d(self.padding(h, (1,1,1,1)), self.kernel_3, padding=0, dilation=1, groups=self.dim)
h2 = F.conv2d(self.padding(h, (3,3,3,3)), self.kernel_3_1, padding=0, dilation=3, groups=self.dim)
h3 = F.conv2d(self.padding(h, (5,5,5,5)), self.kernel_3_2, padding=0, dilation=5, groups=self.dim)
out = self.alpha[0]*h1 + self.alpha[1]*h2 + self.alpha[2]*h3
return out
class VisionMamba(nn.Module):
def __init__(self, img_size=224, patch_size=16, stride=16,
embed_dim=192, depth=24, num_classes=1000, **kwargs):
super().__init__()
self.embed_dim = embed_dim
self.patch_embed = PatchEmbed(img_size=img_size, patch_size=patch_size, stride=stride, embed_dim=embed_dim)
self.hin_block = HinBlock(embed_dim) # 假设 HinBlock 已被定义
self.state_fusion = StateFusion(embed_dim) # 增加 StateFusion
self.layers = nn.ModuleList([
create_block(embed_dim) for _ in range(depth)
])
self.norm_f = nn.LayerNorm(embed_dim)
self.head = nn.Linear(embed_dim, num_classes)
def forward_features(self, z, x):
# 应用 hin_block,以增强特征输入
x = self.hin_block(x)
z = self.hin_block(z)
# 应用 patch_embed
x = self.patch_embed(x)
z = self.patch_embed(z)
# 状态融合
x = x.permute(0, 2, 1).reshape(-1, self.embed_dim, int(self.patch_embed.grid_size[0]), int(self.patch_embed.grid_size[1]))
z = z.permute(0, 2, 1).reshape(-1, self.embed_dim, int(self.patch_embed.grid_size[0] // 2), int(self.patch_embed.grid_size[1] // 2))
x = self.state_fusion(x).view(x.size(0), self.embed_dim, -1).permute(0, 2, 1)
z = self.state_fusion(z).view(z.size(0), self.embed_dim, -1).permute(0, 2, 1)
x = torch.cat((z, x), dim=1)
# 进入 transformer 层
for layer in self.layers:
x, _ = layer(x)
x = self.norm_f(x)
return x.mean(dim=1)
def forward(self, z, x):
x = self.forward_features(z, x)
x = self.head(x)
return x
# 假设 HinBlock 已被定义
class HinBlock(nn.Module):
def __init__(self, embed_dim):
super(HinBlock, self).__init__()
self.conv_1x1 = nn.Conv2d(embed_dim, embed_dim, kernel_size=1)
self.conv_3x3 = nn.Conv2d(embed_dim, embed_dim, kernel_size=3, padding=1)
self.conv_5x5 = nn.Conv2d(embed_dim, embed_dim, kernel_size=5, padding=2)
self.conv_2 = nn.Conv2d(embed_dim * 3, embed_dim * 2, kernel_size=1)
self.norm = nn.BatchNorm2d(embed_dim)
self.relu = nn.ReLU()
def forward(self, x):
scale_1 = self.conv_1x1(x)
scale_2 = self.conv_3x3(x)
scale_3 = self.conv_5x5(x)
resi = torch.cat([scale_1, scale_2, scale_3], dim=1)
resi = self.relu(resi)
resi = self.relu(self.conv_2(resi))
out_1, out_2 = torch.chunk(resi, 2, dim=1)
resi = torch.cat([self.norm(out_1), out_2], dim=1)
return x + resi
解释
Spatial Enhancement :
StateFusion 被插入到 patch_embed 之后,用于增强特征的空间信息。
原有的 hin_block 继续用来进行多尺度特征提取,然后按照上面的步骤对特征进行空间增强。
Combination of Features :
使用 z 和 x 作为输入,这两种输入会受到 hin_block 和 StateFusion 的空间增强。
这种整合可以提高模型在不同尺度信息下的空间特征提取能力,从而提升模型整体的性能。进一步调整模块参数或排布可以帮助优化模型表现。
import torch
import torch.nn as nn
from torch import Tensor
from typing import Optional
class MambaBlock(nn.Module):
def __init__(self, dim, mixer_cls, norm_cls=nn.LayerNorm, drop_path=0., fused_add_norm=False, residual_in_fp32=False, glu_adapter=None):
super().__init__()
self.residual_in_fp32 = residual_in_fp32
self.fused_add_norm = fused_add_norm
self.mixer = mixer_cls(dim)
self.norm = norm_cls(dim)
self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
# Adding StateFusion
self.state_fusion = StateFusion(dim)
# Optional GLU Adapter
self.glu_adapter = glu_adapter
def forward(
self, hidden_states: Tensor, residual: Optional[Tensor] = None, inference_params=None
):
r"""Pass the input through the encoder layer.
Args:
hidden_states: the sequence to the encoder layer (required).
residual: residual tensor from previous layer (optional).
"""
# Apply StateFusion for spatial feature enhancement
batch_size, seq_length, dim = hidden_states.shape
sqrt_seq_length = int(seq_length**0.5)
hidden_states_2d = hidden_states.view(batch_size, dim, sqrt_seq_length, sqrt_seq_length)
enhanced_features = self.state_fusion(hidden_states_2d)
enhanced_features = enhanced_features.view(batch_size, seq_length, dim)
# Replace hidden_states with enhanced features
hidden_states = enhanced_features
if not self.fused_add_norm:
if residual is None:
residual = hidden_states
else:
# Apply DropPath and add residual
residual = residual + self.drop_path(hidden_states)
# Apply normalization
hidden_states = self.norm(residual.to(dtype=self.norm.weight.dtype))
if self.residual_in_fp32:
residual = residual.to(torch.float32)
else:
fused_add_norm_fn = rms_norm_fn if isinstance(self.norm, RMSNorm) else layer_norm_fn
if residual is None:
# Apply fused normalization
hidden_states, residual = fused_add_norm_fn(
hidden_states,
self.norm.weight,
self.norm.bias,
residual=residual,
prenorm=True,
residual_in_fp32=self.residual_in_fp32,
eps=self.norm.eps,
)
else:
hidden_states, residual = fused_add_norm_fn(
self.drop_path(hidden_states),
self.norm.weight,
self.norm.bias,
residual=residual,
prenorm=True,
residual_in_fp32=self.residual_in_fp32,
eps=self.norm.eps,
)
# Apply the mixer layer
hidden_states = self.mixer(hidden_states, inference_params=inference_params)
# Apply GLU Adapter if available
if self.glu_adapter is not None:
hidden_states = self.glu_adapter(hidden_states)
return hidden_states, residual
解释
StateFusion :
在接受输入后立即应用 StateFusion 增强空间特征。
将隐藏状态 hidden_states 转换为适当的 2D 形态以便处理,然后将增强后的特征替入。
DropPath and Residual :
使用残差连接来保留必要的模型特征。
结合 DropPath 来实现训练的随机化和正则化效果。
Normalization :
使用特定的规范化方法 (LayerNorm 或 RMSNorm),视插入方式而定。
Mixer and Adapter :
特征通过混合器(可能为 MLP 或其他自定义类)。
如有必要,应用 GLU(门控线性单元)来进一步优化特征。
通过这种集成,特征在层内经历了一个增强的处理路径,包括多尺度卷积、正则化和先进的激活策略。这能实现对输入特征进行更丰富的分析和处理,并可能提升模型的整体表现。
import torch
import torch.nn as nn
from torch import Tensor
from typing import Optional
class StateFusion(nn.Module):
def __init__(self, dim):
super(StateFusion, self).__init__()
self.dim = dim
self.kernel_3 = nn.Parameter(torch.ones(dim, 1, 3, 3))
self.kernel_3_1 = nn.Parameter(torch.ones(dim, 1, 3, 3))
self.kernel_3_2 = nn.Parameter(torch.ones(dim, 1, 3, 3))
self.alpha = nn.Parameter(torch.ones(3), requires_grad=True)
@staticmethod
def padding(input_tensor, padding):
return F.pad(input_tensor, padding, mode='replicate')
def forward(self, h):
h1 = F.conv2d(self.padding(h, (1, 1, 1, 1)), self.kernel_3, padding=0, dilation=1, groups=self.dim)
h2 = F.conv2d(self.padding(h, (3, 3, 3, 3)), self.kernel_3_1, padding=0, dilation=3, groups=self.dim)
h3 = F.conv2d(self.padding(h, (5, 5, 5, 5)), self.kernel_3_2, padding=0, dilation=5, groups=self.dim)
out = self.alpha[0]*h1 + self.alpha[1]*h2 + self.alpha[2]*h3
return out
class MambaBlock(nn.Module):
def __init__(self, dim, mixer_cls, norm_cls=nn.LayerNorm, drop_path=0., fused_add_norm=False, residual_in_fp32=False, glu_adapter=None):
super().__init__()
self.residual_in_fp32 = residual_in_fp32
self.fused_add_norm = fused_add_norm
self.mixer = mixer_cls(dim) # mixer should be a callable that returns a nn.Module
self.norm = norm_cls(dim)
self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
# Adding StateFusion
self.state_fusion = StateFusion(dim)
# Optional GLU Adapter
self.glu_adapter = glu_adapter
def forward(
self, hidden_states: Tensor, residual: Optional[Tensor] = None, inference_params=None
):
r"""Pass the input through the encoder layer.
Args:
hidden_states: the sequence to the encoder layer (required).
residual: residual tensor from previous layer (optional).
"""
# Assume input shape is (B, N, C)
B, N, C = hidden_states.shape
# Assume sequence length N can be squared into dimensions
seq_len_sqrt = int(N**0.5)
if seq_len_sqrt * seq_len_sqrt != N:
raise ValueError("The sequence length N should be a perfect square for reshaping to 2D.")
# Reshape to (B, C, H, W) for 2D convolutions
hidden_states_2d = hidden_states.view(B, seq_len_sqrt, seq_len_sqrt, C).permute(0, 3, 1, 2)
# Apply StateFusion
enhanced_features = self.state_fusion(hidden_states_2d)
# Reshape back to (B, N, C)
enhanced_features = enhanced_features.view(B, C, N).permute(0, 2, 1)
# If drop path or fused_add_norm logic is needed
if not self.fused_add_norm:
if residual is None:
residual = enhanced_features
else:
residual = residual + self.drop_path(enhanced_features)
hidden_states = self.norm(residual.to(dtype=self.norm.weight.dtype))
else:
fused_add_norm_fn = rms_norm_fn if isinstance(self.norm, RMSNorm) else layer_norm_fn
if residual is None:
hidden_states, residual = fused_add_norm_fn(
enhanced_features,
self.norm.weight,
self.norm.bias,
residual=residual,
prenorm=True,
residual_in_fp32=self.residual_in_fp32,
eps=self.norm.eps,
)
else:
hidden_states, residual = fused_add_norm_fn(
self.drop_path(enhanced_features),
self.norm.weight,
self.norm.bias,
residual=residual,
prenorm=True,
residual_in_fp32=self.residual_in_fp32,
eps=self.norm.eps,
)
# Apply the mixer layer
hidden_states = self.mixer(hidden_states, inference_params=inference_params)
# Apply GLU Adapter if available
if self.glu_adapter is not None:
hidden_states = self.glu_adapter(hidden_states)
return hidden_states, residual
解释
二维转换 :
假设输入形状为 (B, N, C),我们需要将序列维度 N 转换为 (H, W),这要求 N 为完美平方以适合重新排列。对于给定的形状 (20, 320, 384),这假设 320 可拆成 16 x 20 等价的 (H, W),用前置条件去确保。
特征增强 :
使用 StateFusion 进行多尺度增强,确保提高特征表达。
归一化与连接 :
使用 LayerNorm 或 RMSNorm 和选择性 DropPath。
保持残差连接以进一步增强特征。
确保这些步骤在集成和运用时符合特定问题上下文中的数据特征和要求。如果特征数据不适合正方形转换,可以考虑通过填充或不同的分块方法来处理基础数据。
import torch
import torch.nn as nn
import torch.functional as F
class StateFusion(nn.Module):
def __init__(self, dim):
super(StateFusion, self).__init__()
self.dim = dim
self.kernel_3 = nn.Parameter(torch.ones(dim, 1, 3, 3))
self.kernel_3_1 = nn.Parameter(torch.ones(dim, 1, 3, 3))
self.kernel_3_2 = nn.Parameter(torch.ones(dim, 1, 3, 3))
self.alpha = nn.Parameter(torch.ones(3), requires_grad=True)
@staticmethod
def padding(input_tensor, padding):
return F.pad(input_tensor, padding, mode='replicate')
def forward(self, h):
h1 = F.conv2d(self.padding(h, (1, 1, 1, 1)), self.kernel_3, padding=0, dilation=1, groups=self.dim)
h2 = F.conv2d(self.padding(h, (3, 3, 3, 3)), self.kernel_3_1, padding=0, dilation=3, groups=self.dim)
h3 = F.conv2d(self.padding(h, (5, 5, 5, 5)), self.kernel_3_2, padding=0, dilation=5, groups=self.dim)
out = self.alpha[0]*h1 + self.alpha[1]*h2 + self.alpha[2]*h3
return out
class MambaBlock(nn.Module):
def __init__(self, dim, mixer_cls, norm_cls=nn.LayerNorm, drop_path=0., fused_add_norm=False, residual_in_fp32=False, glu_adapter=None):
super().__init__()
self.residual_in_fp32 = residual_in_fp32
self.fused_add_norm = fused_add_norm
self.mixer = mixer_cls(dim)
self.norm = norm_cls(dim)
self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
# Adding StateFusion
self.state_fusion = StateFusion(dim)
# Optional GLU Adapter
self.glu_adapter = glu_adapter
def forward(
self, hidden_states: Tensor, residual: Optional[Tensor] = None, inference_params=None
):
r"""Pass the input through the encoder layer.
Args:
hidden_states: the sequence to the encoder layer (required).
residual: residual tensor from previous layer (optional).
"""
# Assume input shape is (B, N, C)
B, N, C = hidden_states.shape
# Try to resolve to a 2D shape close to a square for the StateFusion layer
# Let's just reshape it into a closest k such that k*k is close to N or N' with padding
# Find a rectangle that's close to a square
H = int(N**0.5)
W = N // H
if H * W < N: # If N isn't perfectly divisible by H
W += 1
# Pad the input for the reshaping into 2D if necessary
pad_amount = (H * W) - N
if pad_amount > 0:
padded_hidden_states = F.pad(hidden_states, (0, 0, 0, pad_amount))
else:
padded_hidden_states = hidden_states
# Reshape to (B, C, H, W)
enhanced_2d_input = padded_hidden_states.view(B, H, W, C).permute(0, 3, 1, 2)
# Apply StateFusion
enhanced_features = self.state_fusion(enhanced_2d_input)
# Trim the enhanced feature map to the original sequence length
enhanced_features = enhanced_features[:, :, :H, :W].contiguous().view(B, H * W, C)[:, :N]
# Original processing steps
if not self.fused_add_norm:
if residual is None:
residual = enhanced_features
else:
residual = residual + self.drop_path(enhanced_features)
hidden_states = self.norm(residual.to(dtype=self.norm.weight.dtype))
else:
fused_add_norm_fn = rms_norm_fn if isinstance(self.norm, RMSNorm) else layer_norm_fn
if residual is None:
hidden_states, residual = fused_add_norm_fn(
enhanced_features,
self.norm.weight,
self.norm.bias,
residual=residual,
prenorm=True,
residual_in_fp32=self.residual_in_fp32,
eps=self.norm.eps,
)
else:
hidden_states, residual = fused_add_norm_fn(
self.drop_path(enhanced_features),
self.norm.weight,
self.norm.bias,
residual=residual,
prenorm=True,
residual_in_fp32=self.residual_in_fp32,
eps=self.norm.eps,
)
# Apply the mixer layer
hidden_states = self.mixer(hidden_states, inference_params=inference_params)
if self.glu_adapter is not None:
hidden_states = self.glu_adapter(hidden_states)
return hidden_states, residual
解释
形状调整 :
我们首先设法将 N 转换为一个接近正方形的矩形 (H, W)。
如果 H * W 较小,则会增加 W,并在必要时填充 hidden_states 以适应这种转换。这允许在应用 state_fusion 前将特征转换为二维。
填充和修剪 :
首先应用填充,以便将所有输入都统一为适合卷积的形状。
在卷积操作后(state_fusion 操作结束后),修剪特征图至原始序列长度。
这种方法给我们提供了一种灵活的方法来处理不规则形状,并且保证在预处理和后处理中对维度进行适当的处理,不改变数据的实际信息内容。
class StructureAwareSSM(nn.Module):
# Hypothetical implementation of StructureAwareSSM
def __init__(self, d_model):
super(StructureAwareSSM, self).__init__()
self.conv = nn.Conv2d(d_model, d_model, kernel_size=3, padding=1, groups=d_model)
def forward(self, x):
# Assume input x is in shape of (B, C, H, W)
return self.conv(x)
class MambaBlock(nn.Module):
def __init__(self, dim, mixer_cls, norm_cls=nn.LayerNorm, drop_path=0., fused_add_norm=False, residual_in_fp32=False, glu_adapter=None):
super().__init__()
self.residual_in_fp32 = residual_in_fp32
self.fused_add_norm = fused_add_norm
self.mixer = mixer_cls(dim)
self.norm = norm_cls(dim)
self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
# Adding StateFusion
self.state_fusion = StateFusion(dim)
# Adding StructureAwareSSM
self.structure_aware_ssm = StructureAwareSSM(dim)
# Optional GLU Adapter
self.glu_adapter = glu_adapter
def forward(
self, hidden_states: Tensor, residual: Optional[Tensor] = None, inference_params=None
):
r"""Pass the input through the encoder layer.
Args:
hidden_states: the sequence to the encoder layer (required).
residual: residual tensor from previous layer (optional).
"""
# Assume input shape is (B, N, C)
B, N, C = hidden_states.shape
H = int(N**0.5) # Assuming N is a perfect square or can be padded to be one
W = N // H
if H * W < N:
W += 1
# Pad the input if necessary
pad_amount = (H * W) - N
if pad_amount > 0:
padded_hidden_states = F.pad(hidden_states, (0, 0, 0, pad_amount))
else:
padded_hidden_states = hidden_states
# Reshape to (B, C, H, W)
enhanced_2d_input = padded_hidden_states.view(B, H, W, C).permute(0, 3, 1, 2)
# Apply StateFusion
enhanced_features = self.state_fusion(enhanced_2d_input)
# Apply StructureAwareSSM
enhanced_features = self.structure_aware_ssm(enhanced_features)
# Reshape back to (B, N, C)
enhanced_features = enhanced_features.view(B, C, N).permute(0, 2, 1)[:, :N]
# Original processing steps...
if not self.fused_add_norm:
if residual is None:
residual = enhanced_features
else:
residual = residual + self.drop_path(enhanced_features)
hidden_states = self.norm(residual.to(dtype=self.norm.weight.dtype))
else:
fused_add_norm_fn = rms_norm_fn if isinstance(self.norm, RMSNorm) else layer_norm_fn
if residual is None:
hidden_states, residual = fused_add_norm_fn(
enhanced_features,
self.norm.weight,
self.norm.bias,
residual=residual,
prenorm=True,
residual_in_fp32=self.residual_in_fp32,
eps=self.norm.eps,
)
else:
hidden_states, residual = fused_add_norm_fn(
self.drop_path(enhanced_features),
self.norm.weight,
self.norm.bias,
residual=residual,
prenorm=True,
residual_in_fp32=self.residual_in_fp32,
eps=self.norm.eps,
)
# Apply the mixer layer
hidden_states = self.mixer(hidden_states, inference_params=inference_params)
if self.glu_adapter is not None:
hidden_states = self.glu_adapter(hidden_states)
return hidden_states, residual
解释
模块整合 :
StructureAwareSSM 被添加到 MambaBlock 中,紧随 StateFusion 之后,以便充分利用空间增强特征,并进一步进行结构化处理。
特征处理 :
StateFusion 初步增强特征以捕获多尺度的空间信息。
StructureAwareSSM 通过卷积操作感知局部和全局的结构模式。
形状调整 :
输入特征先重塑为 (B, C, H, W) 格式,以便应用卷积操作。
之后特征被重构回原始格式 (B, N, C)。
这样集成后,MambaBlock 可以更好地处理输入特征,通过多层次的结构感知和空间增强来提升模型的整体性能。具体实施时,根据任务和数据的特点,可能需要对模块的参数进行调试和优化。
class ModalTransformation(nn.Module):
def __init__(self, embed_dim):
super().__init__()
self.transform = nn.Linear(embed_dim, embed_dim)
def forward(self, x1, x2):
# Transform x2 into x1's feature space
transformed_x2 = self.transform(x2)
return x1 + transformed_x2
5. 协同注意力 (Co-Attention) 机制 python Copy code
class CoAttention(nn.Module):
def __init__(self, embed_dim, num_heads):
super().__init__()
self.attn1 = nn.MultiheadAttention(embed_dim, num_heads)
self.attn2 = nn.MultiheadAttention(embed_dim, num_heads)
def forward(self, x1, x2):
# Cross attention between two modalities
x1_attn, _ = self.attn1(x1, x2, x2)
x2_attn, _ = self.attn2(x2, x1, x1)
return x1_attn, x2_attn
6. 层次式特征融合 (Hierarchical Feature Fusion) python Copy code
class HierarchicalFeatureFusion(nn.Module):
def __init__(self, embed_dim):
super().__init__()
self.fusion_layers = nn.ModuleList([nn.Linear(embed_dim, embed_dim) for _ in range(3)])
def forward(self, x1, x2):
# Multi-level feature fusion
for layer in self.fusion_layers:
x1 = layer(x1)
x2 = layer(x2)
return x1, x2
7. 生成对抗学习 (Generative Adversarial Interaction) python Copy code
class GANInteraction(nn.Module):
def __init__(self, embed_dim):
super().__init__()
self.generator = nn.Sequential(
nn.Linear(embed_dim, embed_dim),
nn.ReLU(),
nn.Linear(embed_dim, embed_dim)
)
self.discriminator = nn.Sequential(
nn.Linear(embed_dim * 2, embed_dim),
nn.ReLU(),
nn.Linear(embed_dim, 1),
nn.Sigmoid()
)
def forward(self, x1, x2):
# Generate interaction features
generated = self.generator(x1)
real_fake = self.discriminator(torch.cat([generated, x2], dim=-1))
return generated, real_fake
总结 通过这些代码示例,您可以在跨模态交互机制上尝试多种策略。这些模块可以根据具体的任务需求调整参数,比如特征维度、注意力头的数量、融合层的数量等。在选择合适方案时,需考虑数据集特性、目标特征间的关系以及计算复杂度。分析和实验这些不同策略的特点可以帮助您在目标性能和计算资源之间取得平衡。
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from einops import rearrange
import numbers
from lib.models.mamba_fetrack.mamba_cross_simple import Mamba
def to_3d(x):
return rearrange(x, 'b c h w -> b (h w) c')
def to_4d(x, h, w):
return rearrange(x, 'b (h w) c -> b c h w', h=h, w=w)
class BiasFree_LayerNorm(nn.Module):
def __init__(self, normalized_shape):
super(BiasFree_LayerNorm, self).__init__()
if isinstance(normalized_shape, numbers.Integral):
normalized_shape = (normalized_shape,)
normalized_shape = torch.Size(normalized_shape)
assert len(normalized_shape) == 1
self.weight = nn.Parameter(torch.ones(normalized_shape))
self.normalized_shape = normalized_shape
def forward(self, x):
sigma = x.var(-1, keepdim=True, unbiased=False)
return x / torch.sqrt(sigma + 1e-5) * self.weight
class WithBias_LayerNorm(nn.Module):
def __init__(self, normalized_shape):
super(WithBias_LayerNorm, self).__init__()
if isinstance(normalized_shape, numbers.Integral):
normalized_shape = (normalized_shape,)
normalized_shape = torch.Size(normalized_shape)
assert len(normalized_shape) == 1
self.weight = nn.Parameter(torch.ones(normalized_shape))
self.bias = nn.Parameter(torch.zeros(normalized_shape))
self.normalized_shape = normalized_shape
def forward(self, x):
mu = x.mean(-1, keepdim=True)
sigma = x.var(-1, keepdim=True, unbiased=False)
return (x - mu) / torch.sqrt(sigma + 1e-5) * self.weight + self.bias
class LayerNorm(nn.Module):
def __init__(self, dim, LayerNorm_type):
super(LayerNorm, self).__init__()
if LayerNorm_type == 'BiasFree':
self.body = BiasFree_LayerNorm(dim)
else:
self.body = WithBias_LayerNorm(dim)
def forward(self, x):
h, w = x.shape[-2:]
return to_4d(self.body(to_3d(x)), h, w)
# 定义 HierarchicalFeatureFusion
class HierarchicalFeatureFusion(nn.Module):
def __init__(self, embed_dim):
super(HierarchicalFeatureFusion, self).__init__()
# 假设有三个不同的阶段进行特征变换
self.fusion_layers = nn.ModuleList([
nn.Sequential(
nn.Linear(embed_dim, embed_dim),
nn.ReLU()
) for _ in range(3)
])
self.combine = nn.Linear(embed_dim * 3, embed_dim)
def forward(self, x1, x2):
fusions = []
for layer in self.fusion_layers:
x1 = layer(x1)
x2 = layer(x2)
fusions.append((x1 + x2) / 2)
# 将融合后的输出进行连接
out = torch.cat(fusions, dim=-1)
# 将连接后的输出压缩回原始大小
out = self.combine(out)
return out
class CrossMamba(nn.Module):
def __init__(self, dim):
super(CrossMamba, self).__init__()
self.cross_mamba = Mamba(dim, bimamba_type="v3")
self.norm1 = LayerNorm(dim, 'with_bias')
self.norm2 = LayerNorm(dim, 'with_bias')
self.dwconv = nn.Conv2d(dim, dim, kernel_size=3, padding=1, groups=dim)
# Integrate HierarchicalFeatureFusion
self.feature_fusion = HierarchicalFeatureFusion(dim)
def forward(self, m1, m1_resi, m2):
m1_resi = m1 + m1_resi
# Apply HierarchicalFeatureFusion on inputs
fused_features = self.feature_fusion(m1_resi, m2)
# Integrate with cross mamba
global_f = self.cross_mamba(fused_features, extra_emb=m2)
return global_f
代码解释
定义 HierarchicalFeatureFusion :
设计了多层的特征融合通路,以便对来自两种模态的特征在不同的层级上进行融合。
在每个融合层中,分别处理 m1_resi 和 m2,将它们融合在一起。
结合 CrossMamba :
在 CrossMamba 中实例化 HierarchicalFeatureFusion。
使用 HierarchicalFeatureFusion 对输入模态进行特征融合,然后将融合后的特征送入 cross_mamba 进行进一步处理。
优势
层次化特征捕捉 : 利用层次结构对特征进行多次融合,能有效整合多模态信息。
灵活性 : 融合模块可根据需要进一步扩展或修改以适应不同维度与需求。
鲁棒性 : 通过结构化处理改善双模态交互表现,提高潜在建模能力。
通过这种融合设计,CrossMamba 可以在更加灵活、精细的特征交互基础上,提升对多模态输入的整体综合性能。