在# Copyright (c) OpenMMLab. All rights reserved. import torch import torch.nn as nn…
- User
在# Copyright (c) OpenMMLab. All rights reserved. import torch import torch.nn as nn import math from torch.nn.init import constant_ from .hardutils import conv_s, conv, deconv
import matplotlib.pyplot as plt
import torch.nn.functional as F import numpy as np import cv2 import pdb
from mmcv.ops import DeformConv2dPack as DCN
from collections import OrderedDictimport matplotlib.pyplot as plt
from mmaction.registry import MODELS
from mmengine.utils.dl_utils.parrots_wrapper import BatchNorm from mmengine.model.weight_init import constant_init, kaiming_init, normal_init from timm.models.layers import PatchEmbed, Mlp, DropPath, trunc_normal, lecun_normal_
import snntorch as snn
from timm.models.layers import to_2tuple from mmaction.models.backbones import torchvision_resnet
@MODELS.register_module() class SSTFormer(nn.Module): expansion = 1 # default_hyper_params = dict(pretrain_model_path="", crop_pad=4, pruned=True,) def init(self, pretrained=None, batchNorm=True, output_layers=None, init_std=0.05,num_heads=8,clip_n =3, dim=972, clip_len=8, tau: float = 2.,threshold=0.75, init_values=None,to_device="cuda:0",batch_size=5):
super(SSTFormer, self).init() self.batchNorm = batchNorm # self.conv1 = conv_s(self.batchNorm, 8, 64, kernel_size=3, stride=1) self.conv1 = conv_s(self.batchNorm, 12, 64, kernel_size=3, stride=1) self.conv2 = conv_s(self.batchNorm, 64, 64, kernel_size=3, stride=1) self.conv3 = conv_s(self.batchNorm, 64, 128, kernel_size=3, stride=1) self.conv4 = conv_s(self.batchNorm, 128, 128, kernel_size=3, stride=1) self.conv5 = conv_s(self.batchNorm, 128, 256, kernel_size=3, stride=1) self.conv6 = conv_s(self.batchNorm, 256, 256, kernel_size=3, stride=1) self.conv7 = conv_s(self.batchNorm, 256, 512, kernel_size=3, stride=1) self.conv8 = conv_s(self.batchNorm, 512, 512, kernel_size=3, stride=1)self.deconv3 = deconv(self.batchNorm, 512, 256) self.deconv2 = deconv(self.batchNorm, 512, 128) self.deconv1 = deconv(self.batchNorm, 960, 960) for m in self.modules(): if isinstance(m, nn.Conv2d): n = m.kernel_size[0] * m.kernel_size[1] * m.in_channels variance1 = math.sqrt(3.0 / n) # use 3 for dt1 and 2 for dt4 m.weight.data.normal_(0, variance1) if m.bias is not None: constant_(m.bias, 0) elif isinstance(m, nn.ConvTranspose2d): n = m.kernel_size[0] * m.kernel_size[1] * m.in_channels variance1 = math.sqrt(3.0 / n) # use 3 for dt1 and 2 for dt4 m.weight.data.normal_(0, variance1) if m.bias is not None: constant_(m.bias, 0) self.fusion_feature_map = nn.Parameter(torch.randn(1, 16, 60, 60)) kaiming_init(self.fusion_feature_map, mode='fan_out') self.fu_concat_1 = conv_s(self.batchNorm, 256, 16, kernel_size=3, stride=1) self.fu_concat_2 = nn.Conv2d(in_channels=16,out_channels=256, kernel_size=5, stride=3,padding=1) ## DCN-v2: dynamic convolutional network module self.dcnfeat_layers = nn.Sequential(OrderedDict([ ('conv1', nn.Sequential(nn.Conv2d(32, 32, kernel_size=3, padding=1), nn.ReLU(inplace=True), nn.GroupNorm(32, 32), nn.MaxPool2d(kernel_size=3, stride=2))), ('dcn_conv2', nn.Sequential(DCN(32, 32, kernel_size=3, stride=1, padding=1, dilation=1, deformable_groups=1), nn.ReLU(inplace=True), nn.GroupNorm(32, 32), nn.MaxPool2d(kernel_size=3, stride=2) )), ('dcn_conv3', nn.Sequential(DCN(32, 32, kernel_size=3, stride=1, padding=1, dilation=1, deformable_groups=1), nn.ReLU(inplace=True), nn.GroupNorm(32, 32), )), ('dcn_conv4', nn.Sequential(DCN(32, 32, kernel_size=3, stride=1, padding=1, dilation=1, deformable_groups=1), nn.ReLU(inplace=True), nn.GroupNorm(32, 32))), ('dcn_conv5', nn.Sequential(DCN(32, 32, kernel_size=3, stride=1, padding=1, dilation=1, deformable_groups=1), nn.ReLU(inplace=True))) ])) self.former_out = nn.Sequential( # nn.Linear(768, 32), nn.Linear(512, 32), nn.ReLU(inplace=True), ) self.snn_former_fc = nn.Sequential( nn.Linear(7232, 4096), nn.ReLU(inplace=True), nn.Dropout3d(0.5) ) self.init_values =init_values self.batch_size = batch_size self.clip_len =clip_len self.GRU_Transformer = GRU_Transformer(clip_n =clip_n, dim=dim,num_heads=num_heads,qkv_bias=False,drop_rate=0.0,init_values=self.init_values) self.pretrained = pretrained self.init_std = init_std self.pool= nn.MaxPool2d(2, 2) self.batchNorm1 = nn.BatchNorm2d(64) self.batchNorm2 = nn.BatchNorm2d(128) self.batchNorm3 = nn.BatchNorm2d(256) self.batchNorm4 = nn.BatchNorm2d(512) beta1 = 0.5 self.snn_lif1 = snn.Lapicque(beta=beta1,threshold=threshold) self.snn_lif2 = snn.Lapicque(beta=beta1, threshold=threshold) self.snn_lif3 = snn.Lapicque(beta=beta1, threshold=threshold) self.snn_lif4 = snn.Lapicque(beta=beta1, threshold=threshold) self.snn_lif5 = snn.Lapicque(beta=beta1, threshold=threshold) self.snn_lif6 = snn.Lapicque(beta=beta1, threshold=threshold) self.snn_lif7 = snn.Lapicque(beta=beta1, threshold=threshold) self.snn_lif8 = snn.Lapicque(beta=beta1, threshold=threshold) self.resnet18_feature_extractor = torchvision_resnet.resnet18(pretrained = True) self.conv2d_query = nn.Conv2d(in_channels=512,out_channels=4096, kernel_size=1, stride=1,padding=0) self.conv2d_support = nn.Conv2d(in_channels=512,out_channels=64, kernel_size=1, stride=1,padding=0) def init_weights(self): """Initiate the parameters either from existing checkpoint or from scratch.""" if isinstance(self.pretrained, str): logger = MMLogger.get_current_instance() logger.info(f'load model from: {self.pretrained}') load_checkpoint(self, self.pretrained, strict=False, logger=logger) elif self.pretrained is None: for m in self.modules(): if isinstance(m, nn.Conv3d): kaiming_init(m) elif isinstance(m, nn.Linear): normal_init(m, std=self.init_std) elif isinstance(m, _BatchNorm): constant_init(m, 1) else: raise TypeError('pretrained must be a str or None') def _add_output_and_check(self, name, x, outputs, output_layers): if name in output_layers: outputs[name] = x return len(output_layers) == len(outputs) def forward(self, input_, output_layers=None, image_resize=240, sp_threshold=0.75): rgb_input = input_[0] input = input_[1] threshold = sp_threshold mem_11 = torch.zeros(input.size(0), 64, int(math.ceil(image_resize)), int(math.ceil(image_resize))).cuda() mem_12 = torch.zeros(input.size(0), 64, int(math.ceil(image_resize/2)), int(math.ceil(image_resize/2))).cuda() mem_21 = torch.zeros(input.size(0), 128, int(math.ceil(image_resize/2)), int(math.ceil(image_resize/2))).cuda() mem_22 = torch.zeros(input.size(0), 128, int(math.ceil(image_resize/4)), int(math.ceil(image_resize/4))).cuda() mem_31 = torch.zeros(input.size(0), 256, int(math.ceil(image_resize/4)), int(math.ceil(image_resize/4))).cuda() mem_32 = torch.zeros(input.size(0), 256, int(math.ceil(image_resize/8)), int(math.ceil(image_resize/8))).cuda() mem_41 = torch.zeros(input.size(0), 512, int(math.ceil(image_resize/8)), int(math.ceil(image_resize/8))).cuda() mem_42 = torch.zeros(input.size(0), 512, int(math.ceil(image_resize/16)), int(math.ceil(image_resize/16))).cuda() mem_1_total = torch.zeros(input.size(0), 64, int(math.ceil(image_resize/2)), int(math.ceil(image_resize/2))).cuda() mem_2_total = torch.zeros(input.size(0), 128, int(math.ceil(image_resize/4)), int(math.ceil(image_resize/4))).cuda() mem_3_total = torch.zeros(input.size(0), 256, int(math.ceil(image_resize/8)), int(math.ceil(image_resize/8))).cuda() mem_4_total = torch.zeros(input.size(0), 512, int(math.ceil(image_resize/16)), int(math.ceil(image_resize/16))).cuda() input = input.permute(0,1,4,2,3) for i in range(input.shape[1]): ## from 1 to 16 current_input = input[:, i, :, :, :] current_input = F.interpolate(current_input, [image_resize, image_resize]) #---------------------------------------------------------------------------- current_11 = self.conv1(current_input) mem_11 = mem_11 + current_11 mem_11,current_1 =self.snn_lif1(current_11,mem_11) current_1 = self.conv2(current_1) current_1 = self.pool(current_1) current_12 = self.batchNorm1(current_1) mem_12 = mem_12 + current_12 mem_1_total = mem_1_total + current_12 mem_12,out_conv1 =self.snn_lif2(current_12,mem_12) #---------------------------------------------------------------------------- current_21 = self.conv3(out_conv1) mem_21 = mem_21 + current_21 mem_21,current_2 =self.snn_lif3(current_21,mem_21) current_2 = self.conv4(current_2) current_2 = self.pool(current_2) current_22 = self.batchNorm2(current_2) mem_22 = mem_22 + current_22 mem_2_total = mem_2_total + current_22 mem_22,out_conv2 =self.snn_lif4(current_22,mem_22) #---------------------------------------------------------------------------- current_31 = self.conv5(out_conv2) mem_31 = mem_31 + current_31 mem_31,current_3 =self.snn_lif5(current_31, mem_31) current_3 = self.conv6(current_3) current_3 = self.pool(current_3) current_32 = self.batchNorm3(current_3) mem_32 = mem_32 + current_32 mem_3_total = mem_3_total + current_32 mem_32,out_conv3 =self.snn_lif6(current_32, mem_32) #---------------------------------------------------------------------------- current_41 = self.conv7(out_conv3) mem_41 = mem_41 + current_41 mem_41, current_4 =self.snn_lif7(current_41,mem_41) current_4 = self.conv8(current_4) current_4 = self.pool(current_4) current_42 = self.batchNorm4(current_4) mem_42 = mem_42 + current_42 mem_4_total = mem_4_total + current_42 mem_42, out_conv4 =self.snn_lif8(current_42, mem_42) #---------------------------------------------------------------------------- out_conv4 = mem_4_total out_conv3 = mem_3_total out_conv2 = mem_2_total out_deconv3 = self.deconv3(out_conv4) concat3 = torch.cat((out_conv3, out_deconv3),1) out_deconv2 = self.deconv2(concat3) concat2 = torch.cat((out_conv2, out_deconv2),1) ############################################################################################################ concat_fu = self.fu_concat_1(concat2) fusion_feature_map = self.fusion_feature_map.expand_as(concat_fu) fusion_feature_map_agg = torch.cat((fusion_feature_map,concat_fu),1) ############################################################################################################ fu_eventFeats = self.dcnfeat_layers(fusion_feature_map_agg) fu_fea_map = fu_eventFeats[:,0:16,:,:] #torch.Size([6, 16, 14, 14]) scnn_out = fu_eventFeats[:,16:32,:,:] #torch.Size([6, 16, 14, 14]) scnn_out_Feats = torch.flatten(scnn_out, start_dim=1, end_dim=3) bottleneck_fea = self.fu_concat_2(fu_fea_map).reshape(fu_fea_map.shape[0],-1) ################################################################################################ B,C,N,H,W =rgb_input.shape rgb_input_res = rgb_input.reshape(B*N,C,H,W) rgb_res_out = self.resnet18_feature_extractor(rgb_input_res).reshape( B,N,512,8,8) # rgb_res_out = self.resnet50_feature_extractor(rgb_input_res).reshape( B,N,2048,8,8) if self.clip_len==16: res_query = torch.cat((rgb_res_out[:,3:4,:,:,:],rgb_res_out[:,7:8,:,:,:],rgb_res_out[:,11:12,:,:,:],rgb_res_out[:,15:16,:,:,:]),1).reshape(B*4,512,8,8) res_support = torch.cat((rgb_res_out[:,0:3,:,:,:],rgb_res_out[:,4:7,:,:,:],rgb_res_out[:,8:11,:,:,:],rgb_res_out[:,12:15,:,:,:]),1).reshape(B*(N-4),512,8,8) former_query = self.conv2d_query(res_query).reshape(B,4,64,4096) former_support = self.conv2d_support(res_support).reshape(B,N-4,-1) former_out = self.GRU_Transformer(former_support, former_query, bottleneck_fea) ################################################################################################ out_ = torch.cat((former_out,scnn_out_Feats),1) predict = self.snn_former_fc(out_) # print('self.proj : ',self.snn_former_fc[0].weight) return predict def weight_parameters(self): return [param for name, param in self.named_parameters() if 'weight' in name] def bias_parameters(self): return [param for name, param in self.named_parameters() if 'bias' in name] - Assistant
在您提供的代码中,
SSTFormer类是一个相对复杂的神经网络模型,其中包括多种类型的层和操作。然而,关于事件(event)数据的直接处理并没有明显提及或特别处理。事件数据通常源于事件摄像机,它输出的是像素级的亮度变化事件,而不是传统摄像机的每个像素的亮度值。事件数据的特点是非常稀疏并且时间分辨率高。在您的代码中,模型似乎被设计来处理传统的视频或图像输入,通过使用卷积层(
conv_s和conv),池化层,以及其他典型处理图像数据的模块。事件模态数据的转换(如事件到图像的转换)可能在输入模型之前就已经完成了,或者框架可能暗中处理这一步骤而未在代码中明确表达。如果您的目标是直接处理原始的事件数据,可能需要对模型进行适当的修改或使用专门为处理事件数据设计的层和网络结构。例如,直接处理事件数据(而不是转换为图像帧或其他形式)需要考虑数据的时空稀疏性和异构性。
针对处理原始事件数据的建议:
- 使用专门的层:可以开发或使用特定设计来处理事件数据的层,例如针对事件有选择性的发射或更新机制的特殊卷积层。
- 时空处理:由于事件数据具有高时间分辨率的特性,考虑使用像循环神经网络(RNN)或长短时记忆网络(LSTM)这种可以处理时序数据的网络结构。
- 数据预处理:在输入到网络之前,可能需要一个数据处理步骤将事件数据转换为适合网络处理的格式,例如创建时间窗口内的事件聚合或构建特定的数据表示。
总的来说,处理事件数据通常需要较为特别的处理或网络设计来充分利用其时空特性,您所提供的代码似乎并不直接支持这种特殊数据格式。如果您有进一步的需求或者想继续在事件数据上工作,可能需要更具体地探索或研发适应该类型数据的模型架构。
- User
- Assistant
在您提供的代码片段中,SNN3类似乎是设计为处理从事件摄像机捕获的数据。不过具体事件数据的格式没有直接说明。事件摄像机通常输出的是一系列事件,每个事件由时刻、像素位置和极性(比如亮变暗或暗变亮)组成。这些数据与传统的视频帧数据不同,因为它们非常稀疏并且时间分辨率极高。
理想中,处理这种类型的数据的模型应该能够接收以事件列表形式组织的数据,或者一种预先处理的格式,如时间表面(time surface)或事件帧(event frame)。但从您的代码中看,模型似乎在处理更传统的张量格式。
期望的事件数据格式:
-
事件列表形式:
- 一个事件由三个基本属性定义:x位置,y位置,和时间戳 (和可能的额外极性标记)。
- 数据输入可能是一个结构化数组或者一个Tensor,例如:[N, 3] 的尺寸,其中N是事件的数量。
-
时间表面(Time Surface):
- 时间表面是一种在给定时刻,通过考虑过去一段时间内在每个像素位置发生的最后一个事件的时间戳来构建的数据表达方式。
- 这可能会有额外的维度或通道来表示不同的极性(如正事件和负事件分开)。
- 数据输入可能是一个2D或3D张量,例如,[H, W, C],其中H, W是图像的高度和宽度,C是通道数(通常是1或2表示极性)。
代码使用的数据格式:
从方法签名
forward(self, input_pos, input_neg, trans_snn, transformer_sig, transformer_fea, first_seq)来看:input_pos和input_neg可能代表正事件和负事件的某种聚合或处理后的数据。trans_snn可能代表网络中传播的状态(如膜电位和尖峰活动)。transformer_sig和transformer_fea可能表示由一些前置网络层(如transformer层)处理生成的特征或信号。
这说明,虽然底层数据源可能是事件数据,但在进入模型之前,数据可能已经经过了一定的预处理,如分离成正负事件、转换成某种图像或地图格式等。
-
- User
- Assistant
对比这两个类
ST_Transformer_block和CEBlock,我们可以从几个方面来分析它们的设计和功能:架构和设计模式
-
标准化和层归一化(Layer Normalization):
- 两个类都使用了
nn.LayerNorm来规范化输入数据,有助于加速训练和提高模型的稳定性。
- 两个类都使用了
-
注意力机制(Attention):
- 两者使用了
Attention模块进行特征处理。这有助于模型在处理序列或时间数据时关注到重要的信息。
- 两者使用了
-
多层感知器(MLP):
Mlp模块在两个类中都用于在注意力模块后进一步处理特征,增强模型的表达能力。
-
DropPath(随机深度):
- 两个类都可能应用
DropPath,它是一种正则化技术,用于训练过程中随机“丢掉”一些路径,以避免过拟合。这在大规模网络中尤其有用。
- 两个类都可能应用
特定功能和差异
-
CEBlock 的候选区域消除:
CEBlock特有的功能是探索keep_ratio_search参数,与ST_Transformer_block相比,这使得CEBlock在模型输入处理上更为动态和灵活。具体来说, 可以根据注意力权重来动态减少搜索范围或关注的区域。
-
- User
那么再对比一下:class Block(nn.Module):
def __init__(self, dim, num_heads, mlp_ratio=4., qkv_bias=False, drop=0., attn_drop=0., drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm): super().__init__() self.norm1 = norm_layer(dim) self.attn = Attention(dim, num_heads=num_heads, qkv_bias=qkv_bias, attn_drop=attn_drop, proj_drop=drop) # NOTE: drop path for stochastic depth, we shall see if this is better than dropout here self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity() self.norm2 = norm_layer(dim) mlp_hidden_dim = int(dim * mlp_ratio) self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop) def forward(self, x, mask=None): x = x + self.drop_path(self.attn(self.norm1(x), mask)) x = x + self.drop_path(self.mlp(self.norm2(x))) return x - Assistant
在比较
Block类与前面提及的ST_Transformer_block和CEBlock类时,我们可以从以下方面进行分析:架构和设计
-
层规范化(Layer Normalization):
- 所有类都使用了
norm_layer参数指定的层规范化,通常是nn.LayerNorm。这有利于模型在训练中的稳定性和收敛速度。
- 所有类都使用了
-
注意力机制(Attention):
- 三个类都集成了一个
Attention模块。这是 Transformer 框架的核心部分,且参数配置num_heads(多头),qkv_bias(查询键值偏置),attn_drop和proj_drop在它们中均有出现。
- 三个类都集成了一个
-
多层感知器(MLP):
- 三个类都包含由
mlp_ratio参数决定的隐藏层大小的 MLP。这有助于在注意力机制后进一步处理和变换特征。
- 三个类都包含由
-
DropPath(随机深度):
- 三个类均使用
DropPath来提供随机深度功能,有助于防止过拟合,尤其在训练大型网络时。
- 三个类均使用
-