import torch.nn as nn
import torch.nn.functional as F
from mmcv.cnn import build_conv_layer, build_norm_layer
from mmengine.model import BaseModule
from mmengine.utils import to_3tuple
class AdaptivePadding(nn.Module):
"""Applies padding adaptively to the input.
code
This module can make input get fully covered by filter
you specified. It support two modes "same" and "corner". The
"same" mode is same with "SAME" padding mode in TensorFlow, pad
zero around input. The "corner" mode would pad zero
to bottom right.
Args:
kernel_size (int | tuple): Size of the kernel. Default: 1.
stride (int | tuple): Stride of the filter. Default: 1.
dilation (int | tuple): Spacing between kernel elements.
Default: 1.
padding (str): Support "same" and "corner", "corner" mode
would pad zero to bottom right, and "same" mode would
pad zero around input. Default: "corner".
Example:
>>> kernel_size = 16
>>> stride = 16
>>> dilation = 1
>>> input = torch.rand(1, 1, 15, 17)
>>> adap_pad = AdaptivePadding(
>>> kernel_size=kernel_size,
>>> stride=stride,
>>> dilation=dilation,
>>> padding="corner")
>>> out = adap_pad(input)
>>> assert (out.shape[2], out.shape[3]) == (16, 32)
>>> input = torch.rand(1, 1, 16, 17)
>>> out = adap_pad(input)
>>> assert (out.shape[2], out.shape[3]) == (16, 32)
"""
def __init__(self, kernel_size=1, stride=1, dilation=1, padding='corner'):
super().__init__()
assert padding in ('same', 'corner')
kernel_size = to_3tuple(kernel_size)
stride = to_3tuple(stride)
dilation = to_3tuple(dilation)
self.padding = padding
self.kernel_size = kernel_size
self.stride = stride
self.dilation = dilation
def get_pad_shape(self, input_shape):
"""Calculate the padding size of input.
Args:
input_shape (:obj:`torch.Size`): arrange as (H, W).
Returns:
Tuple[int]: The padding size along the
original H and W directions
"""
input_t, input_h, input_w = input_shape
kernel_d, kernel_h, kernel_w = self.kernel_size
stride_d, stride_h, stride_w = self.stride
output_d = math.ceil(input_t / stride_d)
output_h = math.ceil(input_h / stride_h)
output_w = math.ceil(input_w / stride_w)
pad_d = max((output_d - 1) * stride_d +
(kernel_d - 1) * self.dilation[0] + 1 - input_t, 0)
pad_h = max((output_h - 1) * stride_h +
(kernel_h - 1) * self.dilation[1] + 1 - input_h, 0)
pad_w = max((output_w - 1) * stride_w +
(kernel_w - 1) * self.dilation[2] + 1 - input_w, 0)
return pad_d, pad_h, pad_w
def forward(self, x):
"""Add padding to `x`
Args:
x (Tensor): Input tensor has shape (B, C, H, W).
Returns:
Tensor: The tensor with adaptive padding
"""
pad_d, pad_h, pad_w = self.get_pad_shape(x.size()[-2:])
if pad_d > 0 or pad_h > 0 or pad_w > 0:
if self.padding == 'corner':
x = F.pad(x, [0, pad_w, 0, pad_h, 0, pad_d])
elif self.padding == 'same':
x = F.pad(x, [
pad_w // 2,
pad_w - pad_w // 2,
pad_h // 2,
pad_h - pad_h // 2,
pad_d // 2,
pad_d - pad_d // 2,
])
return x
class PatchEmbed3D(BaseModule):
"""Video to Patch Embedding.
code
Assistant
The PatchEmbed3D class in the given code is designed to transform a 3D tensor input (commonly representing a video or volumetric data) into a patch embedding. This process involves several steps involving padding, convolution, potential normalization, and reshaping. Let's break down each step of the forward method to understand how the data dimensions are being transformed:
1. Adaptive Padding
The first step in the forward method involves adaptive padding, which is optional based on whether it has been initialized:
python
if self.adaptivePadding:
x = self.adaptive_padding(x)
Purpose: Adaptive padding is meant to adjust the input tensor so that the convolution operation can cover the input tensor fully based on the specified kernel size, stride, and padding type ("same" or "corner").
Input & Output Shape: If self.adaptive_padding is set, it modifies the dimensions of the tensor x from (B, C, T, H, W) to (B, C, T', H', W') where T', H', and W' might be larger depending on the padding applied to ensure that the convolution can be properly performed.
2. Convolution
After padding, the tensor is fed into a convolution layer:
python
x = self.projection(x)
Purpose: The convolution layer (self.projection) transforms the input channels to a specified number of output channels (embedding dimensions) and reduces the spatial and temporal dimensions based on kernel size, stride, and padding.
Kernel, Stride, & Padding: These parameters control how the convolution operation is performed. For example, a larger stride will produce a smaller output dimension.
Input & Output Shape: Input is (B, C, T', H', W') and output is (B, embed_dims, out_t, out_h, out_w) where embed_dims is the number of output channels.
3. Flattening and Permutation
Next, the output from the convolution is reshaped and permuted:
python
x = x.flatten(2).transpose(1, 2)
Purpose: Before this operation, the tensor has shape (B, embed_dims, out_t, out_h, out_w). combines the dimensions , , and into a single dimension, resulting in shape . The then swaps the last two dimensions to prepare for potential normalization and to make the embedding dimension the last dimension.
with AedatFile(aedat_file_path) as f:
events = np.hstack([packet for packet in f['events'].numpy()])
t, x, y, p = events['timestamp'], events['x'], events['y'], events['polarity']
with AedatFile(aedat_file_path) as f:
for frame in f['frames']:
frame_all.append(frame.image)
frame_exposure_time.append([frame.timestamp_start_of_exposure, frame.timestamp_end_of_exposure])
输出变量:
frame_all: 捕获的所有帧的列表。
frame_exposure_time: 各帧曝光时间的开始和结束时间戳列表。
图片保存:
遍历所有帧,并使用cv2.imwrite函数将其保存为PNG格式的图像文件。
python
for frame_no in range(0, int(frame_num)-1):
this_frame = frame_all[frame_no]
cv2.imwrite(os.path.join(rgb_save_path_img_dvs, '{:04d}'.format(frame_no) + '.png'), this_time)
在# 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 OrderedDict
import 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
We use a conv layer to implement PatchEmbed.
Args:
in_channels (int): The num of input channels. Default: 3
embed_dims (int): The dimensions of embedding. Default: 768
conv_type (str): The type of convolution
to generate patch embedding. Default: "Conv3d".
kernel_size (int): The kernel_size of embedding conv.
Default: (2, 4, 4).
stride (int): The slide stride of embedding conv.
Default: (2, 4, 4).
padding (int | tuple | string): The padding length of
embedding conv. When it is a string, it means the mode
of adaptive padding, support "same" and "corner" now.
Default: "corner".
dilation (int): The dilation rate of embedding conv. Default: 1.
bias (bool): Bias of embed conv. Default: True.
norm_cfg (dict, optional): Config dict for normalization layer.
Default: None.
input_size (int | tuple | None): The size of input, which will be
used to calculate the out size. Only works when `dynamic_size`
is False. Default: None.
init_cfg (`mmcv.ConfigDict`, optional): The Config for initialization.
Default: None.
"""
def __init__(self,
in_channels=3,
embed_dims=768,
conv_type='Conv3d',
kernel_size=(2, 4, 4),
stride=(2, 4, 4),
padding='corner',
dilation=1,
bias=True,
norm_cfg=None,
input_size=None,
init_cfg=None):
super().__init__(init_cfg=init_cfg)
self.embed_dims = embed_dims
if stride is None:
stride = kernel_size
kernel_size = to_3tuple(kernel_size)
stride = to_3tuple(stride)
dilation = to_3tuple(dilation)
if isinstance(padding, str):
self.adaptive_padding = AdaptivePadding(
kernel_size=kernel_size,
stride=stride,
dilation=dilation,
padding=padding)
# disable the padding of conv
padding = 0
else:
self.adaptive_padding = None
padding = to_3tuple(padding)
self.projection = build_conv_layer(
dict(type=conv_type),
in_channels=in_channels,
out_channels=embed_dims,
kernel_size=kernel_size,
stride=stride,
padding=padding,
dilation=dilation,
bias=bias)
if norm_cfg is not None:
self.norm = build_norm_layer(norm_cfg, embed_dims)[1]
else:
self.norm = None
if input_size:
input_size = to_3tuple(input_size)
# `init_out_size` would be used outside to
# calculate the num_patches
# e.g. when `use_abs_pos_embed` outside
self.init_input_size = input_size
if self.adaptive_padding:
pad_d, pad_h, pad_w = self.adaptive_padding.get_pad_shape(
input_size)
input_t, input_h, input_w = input_size
input_t = input_t + pad_d
input_h = input_h + pad_h
input_w = input_w + pad_w
input_size = (input_t, input_h, input_w)
# https://pytorch.org/docs/stable/generated/torch.nn.Conv3d.html
t_out = (input_size[0] + 2 * padding[0] - dilation[0] *
(kernel_size[0] - 1) - 1) // stride[0] + 1
h_out = (input_size[1] + 2 * padding[1] - dilation[1] *
(kernel_size[1] - 1) - 1) // stride[1] + 1
w_out = (input_size[2] + 2 * padding[2] - dilation[2] *
(kernel_size[2] - 1) - 1) // stride[2] + 1
self.init_out_size = (t_out, h_out, w_out)
else:
self.init_input_size = None
self.init_out_size = None
def forward(self, x):
"""
Args:
x (Tensor): Has shape (B, C, T, H, W). In most case, C is 3.
Returns:
tuple: Contains merged results and its spatial shape.
- x (Tensor): Has shape (B, out_t * out_h * out_w, embed_dims)
- out_size (tuple[int]): Spatial shape of x, arrange as
(out_t, out_h, out_w).
"""
if self.adaptive_padding:
x = self.adaptive_padding(x)
x = self.projection(x)
out_size = (x.shape[2], x.shape[3], x.shape[4])
x = x.flatten(2).transpose(1, 2)
if self.norm is not None:
x = self.norm(x)
return x, out_size中如何进行处理的?维度是如何进行变化的?
flatten(2)
out_t
out_h
out_w
(B, embed_dims, out_t * out_h * out_w)
transpose(1, 2)
Input & Output Shape: Changes from (B, embed_dims, out_t, out_h, out_w) to (B, out_t * out_h * out_w, embed_dims).
4. Normalization (optional)
If a normalization configuration is provided, this step will apply a normalization over the embedding dimension:
python
if self.norm is not None:
x = self.norm(x)
Purpose: Normalization (like BatchNorm, LayerNorm, etc.) is often used to help stabilize and speed up neural network training.
Input & Mrsorw:' Normalization does not change the shape of the tensor but might change its values by applying scale and shift transformations.
Output
Finally, the method returns the tensor x along with its spatial dimensions as (out_t, out_ht for clarity and consistency in architecturW) to facilitate further processing or to conform to expected input sizes for subsequent layers.
This structured transformation from original video/volumetric input into a compact embedded form makes it suitable for further processing by other network components, such as attention mechanisms or classifiers in transformer-based architectures.
Args:
mean (Sequence[float or int], optional): The pixel mean of channels
of images or stacked optical flow. Defaults to None.
std (Sequence[float or int], optional): The pixel standard deviation
of channels of images or stacked optical flow. Defaults to None.
to_rgb (bool): Whether to convert image from BGR to RGB.
Defaults to False.
blending (dict, optional): Config for batch blending.
Defaults to None.
format_shape (str): Format shape of input data.
Defaults to ``'NCHW'``.
"""
def __init__(self,
mean: Optional[Sequence[Union[float, int]]] = None,
std: Optional[Sequence[Union[float, int]]] = None,
to_rgb: bool = False,
blending: Optional[dict] = None,
format_shape: str = 'NCHW') -> None:
super().__init__()
self.to_rgb = to_rgb
self.format_shape = format_shape
if mean is not None:
assert std is not None, 'To enable the normalization in ' \
'preprocessing, please specify both ' \
'`mean` and `std`.'
# Enable the normalization in preprocessing.
self._enable_normalize = True
if self.format_shape == 'NCHW':
normalizer_shape = (-1, 1, 1)
elif self.format_shape in ['NCTHW', 'MIX2d3d']:
normalizer_shape = (-1, 1, 1, 1)
else:
raise ValueError(f'Invalid format shape: {format_shape}')
self.register_buffer(
'mean',
torch.tensor(mean, dtype=torch.float32).view(normalizer_shape),
False)
self.register_buffer(
'std',
torch.tensor(std, dtype=torch.float32).view(normalizer_shape),
False)
else:
self._enable_normalize = False
if blending is not None:
self.blending = MODELS.build(blending)
else:
self.blending = None
def forward(self,
data: Union[dict, Tuple[dict]],
training: bool = False) -> Union[dict, Tuple[dict]]:
"""Perform normalization, padding, bgr2rgb conversion and batch
augmentation based on ``BaseDataPreprocessor``.
Args:
data (dict or Tuple[dict]): data sampled from dataloader.
training (bool): Whether to enable training time augmentation.
Returns:
dict or Tuple[dict]: Data in the same format as the model input.
"""
data = self.cast_data(data)
if isinstance(data, dict):
return self.forward_onesample(data, training=training)
elif isinstance(data, tuple):
outputs = []
for data_sample in data:
output = self.forward_onesample(data_sample, training=training)
outputs.append(output)
return tuple(outputs)
else:
raise TypeError(f'Unsupported data type: {type(data)}!')
def forward_onesample(self, data, training: bool = False) -> dict:
"""Perform normalization, padding, bgr2rgb conversion and batch
augmentation on one data sample.
Args:
data (dict): data sampled from dataloader.
training (bool): Whether to enable training time augmentation.
Returns:
dict: Data in the same format as the model
input.
"""
inputs, data_samples = data['inputs'], data['data_samples']
inputs, data_samples = self.preprocess(inputs, data_samples, training)
data['inputs'] = inputs
data['data_samples'] = data_samples
return data
def preprocess(self,
inputs: List[torch.Tensor],
data_samples: SampleList,
training: bool = False) -> Tuple:
# --- Pad and stack --
batch_inputs = stack_batch(inputs)
if self.format_shape == 'MIX2d3d':
if batch_inputs.ndim == 4:
format_shape, view_shape = 'NCHW', (-1, 1, 1)
else:
format_shape, view_shape = 'NCTHW', None
else:
format_shape, view_shape = self.format_shape, None
# ------ To RGB ------
if self.to_rgb:
if format_shape == 'NCHW':
batch_inputs = batch_inputs[..., [2, 1, 0], :, :]
elif format_shape == 'NCTHW':
batch_inputs = batch_inputs[..., [2, 1, 0], :, :, :]
else:
raise ValueError(f'Invalid format shape: {format_shape}')
# -- Normalization ---
if self._enable_normalize:
if view_shape is None:
batch_inputs = (batch_inputs - self.mean) / self.std
else:
mean = self.mean.view(view_shape)
std = self.std.view(view_shape)
batch_inputs = (batch_inputs - mean) / std
else:
batch_inputs = batch_inputs.to(torch.float32)
# ----- Blending -----
if training and self.blending is not None:
batch_inputs, data_samples = self.blending(batch_inputs,
data_samples)
return batch_inputs, data_samples中数据时如何及逆行转换的?输入维度和输出维度时什么?
def snncnn(output_layers=None, pretrained=False, dilation_factor=1):
"""Constructs a SNN-CNN model.
"""
code
if output_layers is None:
output_layers = ['default']
else:
for l in output_layers:
if l not in ['conv1', 'layer1', 'layer2', 'layer3', 'layer4', 'fc']:
raise ValueError('Unknown layer: {}'.format(l))
snn_model = SCNN_TRANSFORMER(batchNorm=False)
return snn_model
class SpikingNN(torch.autograd.Function):
@staticmethod
def forward(self, input):
self.save_for_backward(input)
return input.gt(1e-5).type(torch.cuda.FloatTensor)
def forward(self, x):
return x.mul_(self.gamma) if self.inplace else x * self.gamma中输入维度是多少?
处理之后,是否可以直接传入# 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 OrderedDict
import 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
def snncnn(output_layers=None, pretrained=False, dilation_factor=1):
"""Constructs a SNN-CNN model.
"""
code
if output_layers is None:
output_layers = ['default']
else:
for l in output_layers:
if l not in ['conv1', 'layer1', 'layer2', 'layer3', 'layer4', 'fc']:
raise ValueError('Unknown layer: {}'.format(l))
snn_model = SCNN_TRANSFORMER(batchNorm=False)
return snn_model
class SpikingNN(torch.autograd.Function):
@staticmethod
def forward(self, input):
self.save_for_backward(input)
return input.gt(1e-5).type(torch.cuda.FloatTensor)