import time
import math
import copy
from functools import partial
from typing import Optional, Callable
import timm
import numpy as np
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 FlopCountAnalysis, flop_count_str, flop_count, parameter_count
DropPath.repr = lambda self: f"timm.DropPath({self.drop_prob})"
import mamba_ssm.selective_scan_fn (in which causal_conv1d is needed)
try:
from mamba_ssm.ops.selective_scan_interface import selective_scan_fn, selective_scan_ref
except:
pass
an alternative for mamba_ssm
try:
from selective_scan import selective_scan_fn as selective_scan_fn_v1
from selective_scan import selective_scan_ref as selective_scan_ref_v1
except:
pass
def flops_selective_scan_ref(B=1, L=256, D=768, N=16, with_D=True, with_Z=False, with_Group=True, with_complex=False):
"""
u: r(B D L)
delta: r(B D L)
A: r(D N)
B: r(B N L)
C: r(B N L)
D: r(D)
z: r(B D L)
delta_bias: r(D), fp32
ignores:
[.float(), +, .softplus, .shape, new_zeros, repeat, stack, to(dtype), silu]
"""
import numpy as np
# fvcore.nn.jit_handles
def get_flops_einsum(input_shapes, equation):
np_arrs = [np.zeros(s) for s in input_shapes]
optim = np.einsum_path(equation, *np_arrs, optimize="optimal")[1]
for line in optim.split("\n"):
if "optimized flop" in line.lower():
# divided by 2 because we count MAC (multiply-add counted as one flop)
flop = float(np.floor(float(line.split(":")[-1]) / 2))
return flop
assert not with_complex
flops = 0 # below code flops = 0
if False:
...
"""
dtype_in = u.dtype
u = u.float()
delta = delta.float()
if delta_bias is not None:
delta = delta + delta_bias[..., None].float()
if delta_softplus:
delta = F.softplus(delta)
batch, dim, dstate = u.shape[0], A.shape[0], A.shape[1]
is_variable_B = B.dim() >= 3
is_variable_C = C.dim() >= 3
if A.is_complex():
if is_variable_B:
B = torch.view_as_complex(rearrange(B.float(), "... (L two) -> ... L two", two=2))
if is_variable_C:
C = torch.view_as_complex(rearrange(C.float(), "... (L two) -> ... L two", two=2))
else:
B = B.float()
C = C.float()
x = A.new_zeros((batch, dim, dstate))
ys = []
"""
flops += get_flops_einsum([[B, D, L], [D, N]], "bdl,dn->bdln")
if with_Group:
flops += get_flops_einsum([[B, D, L], [B, N, L], [B, D, L]], "bdl,bnl,bdl->bdln")
else:
flops += get_flops_einsum([[B, D, L], [B, D, N, L], [B, D, L]], "bdl,bdnl,bdl->bdln")
if False:
...
"""
deltaA = torch.exp(torch.einsum('bdl,dn->bdln', delta, A))
if not is_variable_B:
deltaB_u = torch.einsum('bdl,dn,bdl->bdln', delta, B, u)
else:
if B.dim() == 3:
deltaB_u = torch.einsum('bdl,bnl,bdl->bdln', delta, B, u)
else:
B = repeat(B, "B G N L -> B (G H) N L", H=dim // B.shape[1])
deltaB_u = torch.einsum('bdl,bdnl,bdl->bdln', delta, B, u)
if is_variable_C and C.dim() == 4:
C = repeat(C, "B G N L -> B (G H) N L", H=dim // C.shape[1])
last_state = None
"""
in_for_flops = B * D * N
if with_Group:
in_for_flops += get_flops_einsum([[B, D, N], [B, D, N]], "bdn,bdn->bd")
else:
in_for_flops += get_flops_einsum([[B, D, N], [B, N]], "bdn,bn->bd")
flops += L * in_for_flops
if False:
...
"""
for i in range(u.shape[2]):
x = deltaA[:, :, i] * x + deltaB_u[:, :, i]
if not is_variable_C:
y = torch.einsum('bdn,dn->bd', x, C)
else:
if C.dim() == 3:
y = torch.einsum('bdn,bn->bd', x, C[:, :, i])
else:
y = torch.einsum('bdn,bdn->bd', x, C[:, :, :, i])
if i == u.shape[2] - 1:
last_state = x
if y.is_complex():
y = y.real * 2
ys.append(y)
y = torch.stack(ys, dim=2) # (batch dim L)
"""
if with_D:
flops += B * D * L
if with_Z:
flops += B * D * L
if False:
...
"""
out = y if D is None else y + u * rearrange(D, "d -> d 1")
if z is not None:
out = out * F.silu(z)
out = out.to(dtype=dtype_in)
"""
return flops
# If no scaling is needed, use an identity mapping
self.pixel_shuffle = nn.Identity()
self.adjust_channels = nn.Identity()
self.norm = norm_layer(dim // dim_scale)
def forward(self, x):
# Pixel shuffle expects the input in the format (B, C, H, W)
x = rearrange(x, 'b h w c -> b c h w')
if self.dim_scale == 2:
x = self.pixel_shuffle(x)
x = self.adjust_channels(x)
# Convert back to the original format for normalization
x = rearrange(x, 'b c h w -> b h w c')
x = self.norm(x)
return x
class PatchExpand(nn.Module):
def init(self, dim, dim_scale=2, norm_layer=nn.LayerNorm):
super().init()
self.dim = dim
self.expand = nn.Linear(
dim, 2*dim, bias=False) if dim_scale == 2 else nn.Identity()
self.norm = norm_layer(dim // dim_scale)
def forward(self, x):
x = self.expand(x)
B, H, W, C = x.shape
x = rearrange(x, 'b h w (p1 p2 c)-> b (h p1) (w p2) c', p1=2, p2=2, c=C//4)
x= self.norm(x)
return x
class FinalPatchExpand_X4(nn.Module):
def init(self, dim, dim_scale=4, norm_layer=nn.LayerNorm):
super().init()
self.dim = dim
self.dim_scale = dim_scale
self.expand = nn.Linear(dim, 16*dim, bias=False)
self.output_dim = dim
self.norm = norm_layer(self.output_dim)
def forward(self, x):
x = self.expand(x)
B, H, W, C = x.shape
x = rearrange(x, 'b h w (p1 p2 c)-> b (h p1) (w p2) c', p1=self.dim_scale, p2=self.dim_scale, c=C//(self.dim_scale**2))
x= self.norm(x)
return x
def forward(self, input: torch.Tensor):
x = input + self.drop_path(self.self_attention(self.ln_1(input)))
return x
class VSSLayer(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.
"""
def __init__(
self,
dim,
depth,
attn_drop=0.,
drop_path=0.,
norm_layer=nn.LayerNorm,
downsample=None,
use_checkpoint=False,
d_state=16,
**kwargs,
):
super().__init__()
self.dim = dim
self.use_checkpoint = use_checkpoint
self.blocks = nn.ModuleList([
VSSBlock(
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,
)
for i in range(depth)])
if True: # is this really applied? Yes, but been overriden later in VSSM!
def _init_weights(module: nn.Module):
for name, p in module.named_parameters():
if name in ["out_proj.weight"]:
p = p.clone().detach_() # fake init, just to keep the seed ....
nn.init.kaiming_uniform_(p, a=math.sqrt(5))
self.apply(_init_weights)
if downsample is not None:
self.downsample = downsample(dim=dim, norm_layer=norm_layer)
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 VSSLayer_up(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
Upsample (nn.Module | None, optional): Upsample layer at the end of the layer. Default: None
use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False.
"""
def __init__(
self,
dim,
depth,
attn_drop=0.,
drop_path=0.,
norm_layer=nn.LayerNorm,
upsample=None,
use_checkpoint=False,
d_state=16,
**kwargs,
):
super().__init__()
self.dim = dim
self.use_checkpoint = use_checkpoint
self.blocks = nn.ModuleList([
VSSBlock(
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,
)
for i in range(depth)])
if True: # is this really applied? Yes, but been overriden later in VSSM!
def _init_weights(module: nn.Module):
for name, p in module.named_parameters():
if name in ["out_proj.weight"]:
p = p.clone().detach_() # fake init, just to keep the seed ....
nn.init.kaiming_uniform_(p, a=math.sqrt(5))
self.apply(_init_weights)
if upsample is not None:
self.upsample = PatchExpand(dim, dim_scale=2, norm_layer=nn.LayerNorm)
else:
self.upsample = 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.upsample is not None:
x = self.upsample(x)
return x
# resnet18
dims = [64, 128, 256, 512]
self.backbone = timm.create_model("swsl_resnet18", features_only=True, output_stride=32,
out_indices=(1, 2, 3, 4), pretrained=True) # build decoder layers
base_dims = 64
# embed_dim = 128
# dims = [embed_dim, embed_dim*2, embed_dim*4, embed_dim*8]
# num_heads=(4, 8, 16, 32)
# freeze_stages = -1
# self.backbone = SwinTransformer(embed_dim=embed_dim, depths=depths, num_heads=num_heads, frozen_stages=freeze_stages)
# base_dims = 128 # 96
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.num_features_up = int(dims[0] * 2)
self.dims = dims
self.final_upsample = final_upsample
dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))] # stochastic depth decay rule
self.layers_up = nn.ModuleList()
self.concat_back_dim = nn.ModuleList()
for i_layer in range(self.num_layers):
concat_linear = nn.Linear(2*int(dims[0]*2**(self.num_layers-1-i_layer)),
int(dims[0]*2**(self.num_layers-1-i_layer))) if i_layer > 0 else nn.Identity()
if i_layer ==0 :
layer_up = nn.Sequential(
VSSLayer(
dim = int(dims[0] * 2 ** (self.num_layers - 1 - i_layer)),
depth=2,
d_state=math.ceil(dims[0] / 6) if d_state is None else d_state, # 20240109
drop=drop_rate,
attn_drop=attn_drop_rate,
drop_path=dpr[sum(depths[:-1]):sum(depths[:])],
norm_layer=norm_layer,
downsample=None,
use_checkpoint=use_checkpoint),
PatchExpand(dim=int(self.embed_dim * 2 ** (self.num_layers-1-i_layer)), dim_scale=2, norm_layer=norm_layer)
)
# layer_up =PatchExpand(dim=int(self.embed_dim * 2 ** (self.num_layers-1-i_layer)), dim_scale=2, norm_layer=norm_layer)
else:
layer_up = VSSLayer_up(
dim= int(dims[0] * 2 ** (self.num_layers-1-i_layer)),
depth=depths[(self.num_layers-1-i_layer)],
d_state=math.ceil(dims[0] / 6) if d_state is None else d_state, # 20240109
drop=drop_rate,
attn_drop=attn_drop_rate,
drop_path=dpr[sum(depths[:(self.num_layers-1-i_layer)]):sum(depths[:(self.num_layers-1-i_layer) + 1])],
norm_layer=norm_layer,
upsample=PatchExpand if (i_layer < self.num_layers - 1) else None,
use_checkpoint=use_checkpoint,
)
self.layers_up.append(layer_up)
self.concat_back_dim.append(concat_linear)
self.norm = norm_layer(self.num_features)
self.norm_up = norm_layer(self.embed_dim)
if self.final_upsample == "expand_first":
print("---final upsample expand_first---")
self.up = FinalPatchExpand_X4(dim_scale=4,dim=self.embed_dim)
self.output = nn.Conv2d(in_channels=self.embed_dim,out_channels=self.num_classes,kernel_size=1,bias=False)
if self.training:
self.conv4 = nn.Conv2d(base_dims * 2, num_classes, 1, bias=False)
self.conv3 = nn.Conv2d(base_dims, num_classes, 1, bias=False)
self.conv2 = nn.Conv2d(base_dims, num_classes, 1, bias=False)
# self.conv1 = nn.Conv2d(base_dims, num_classes, 1, bias=False)
self.AFFs = nn.ModuleList([
# AFF(96 * 7, 96 * 1),
# AFF(96 * 7, 96 * 2),
# AFF(96 * 7, 96 * 4),
MSFFA(base_dims * 7, base_dims * 1),
MSFFA(base_dims * 7, base_dims * 2),
MSFFA(base_dims * 7, base_dims * 4),
])
self.apply(self._init_weights)
def _init_weights(self, m: nn.Module):
"""
out_proj.weight which is previously initilized in VSSBlock, would be cleared in nn.Linear
no fc.weight found in the any of the model parameters
no nn.Embedding found in the any of the model parameters
so the thing is, VSSBlock initialization is useless
Conv2D is not intialized !!!
"""
# print(m, getattr(getattr(m, "weight", nn.Identity()), "INIT", None), isinstance(m, nn.Linear), "======================")
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)
#Encoder and Bottleneck
def forward_features(self, x):
x = self.patch_embed(x)
x_downsample = []
for layer in self.layers:
x_downsample.append(x)
x = layer(x)
x = self.norm(x) # B H W C
return x, x_downsample
# def forward_backbone(self, x):
# x = self.patch_embed(x)
# for layer in self.layers:
# x = layer(x)
# return x
#Dencoder and Skip connection
def forward_up_features(self, x, x_downsample, h, w):
for inx, layer_up in enumerate(self.layers_up):
if inx == 0:
x = layer_up(x)
else:
down_x = x_downsample[3-inx]
x = torch.cat([x,x_downsample[3-inx]],-1)
x = self.concat_back_dim[inx](x)
x = layer_up(x)
if self.training and inx == 1:
tmp = torch.permute(x, (0,3,1,2))
# h4 = self.up4(tmp)
h4 = self.conv4(tmp)
if self.training and inx == 2:
tmp = torch.permute(x, (0,3,1,2))
# h3 = self.up3(tmp)
h3 = self.conv3(tmp)
if self.training and inx == 3:
tmp = torch.permute(x, (0,3,1,2))
# h2 = self.up2(tmp)
h2 = self.conv2(tmp)
if self.training:
# ah = h4 + h3 + h2
# ah = self.aux_head(ah, h, w)
ah = [h2, h3, h4]
x = self.norm_up(x) # B H W C
return x, ah
else:
x = self.norm_up(x) # B H W C
return x
def up_x4(self, x):
if self.final_upsample=="expand_first":
B,H,W,C = x.shape
x = self.up(x)
x = x.view(B, 4*H, 4*W, -1)
x = x.permute(0, 3, 1, 2) # B,C,H,W
x = self.output(x)
return x
def forward_downfeatures(self, x_downsample):
x_down_last = x_downsample[-1]
x_downsample_2 = x_downsample
x_downsample = []
for feat in x_downsample_2[:-1]:
feat = torch.permute(feat, (0,3,1,2))
x_downsample.append(feat)
x_down_3_2 = F.interpolate(x_downsample[1], scale_factor=2.0, mode="bilinear", align_corners=True)
x_down_4_2 = F.interpolate(x_downsample[2], scale_factor=4.0, mode="bilinear", align_corners=True)
x_down_4_3 = F.interpolate(x_downsample[2], scale_factor=2.0, mode="bilinear", align_corners=True)
x_down_2_3 = F.interpolate(x_downsample[0], scale_factor=0.5, mode="bilinear", align_corners=True)
x_down_2_4 = F.interpolate(x_downsample[0], scale_factor=0.25, mode="bilinear", align_corners=True)
x_down_3_4 = F.interpolate(x_downsample[1], scale_factor=0.5, mode="bilinear", align_corners=True)
x_down_2 = self.AFFs[0](x_downsample[0], x_down_3_2, x_down_4_2)
x_down_3 = self.AFFs[1](x_downsample[1], x_down_2_3, x_down_4_3)
x_down_4 = self.AFFs[2](x_downsample[2], x_down_2_4, x_down_3_4)
x_down_2 = torch.permute(x_down_2, (0,2,3,1))
x_down_3 = torch.permute(x_down_3, (0,2,3,1))
x_down_4 = torch.permute(x_down_4, (0,2,3,1))
return [x_down_2, x_down_3, x_down_4, x_down_last]
def forward_resnet(self, x):
h, w = x.size()[-2:]
res1, res2, res3, res4 = self.backbone(x)
res1 = res1.permute(0,2,3,1)
res2 = res2.permute(0,2,3,1)
res3 = res3.permute(0,2,3,1)
res4 = res4.permute(0,2,3,1)
x_downsample = [res1, res2, res3, res4]
x = res4
return x, x_downsample
def forward(self, x):
h, w = x.size()[-2:]
# x,x_downsample = self.forward_features(x)
x, x_downsample = self.forward_resnet(x)
x_downsample = self.forward_downfeatures(x_downsample)
if self.training:
x, ah = self.forward_up_features(x,x_downsample,h,w)
x = self.up_x4(x)
return x, ah
else:
x = self.forward_up_features(x,x_downsample,h,w)
x = self.up_x4(x)
return x
def flops(self, shape=(3, 224, 224)):
# 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.SelectiveScanFn": selective_scan_flop_jit, # latter
}
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())}"
APIs with VMamba2Dp =================
def check_vssm_equals_vmambadp():
from bak.vmamba_bak1 import VMamba2Dp
# test 1 True =================================
torch.manual_seed(time.time()); torch.cuda.manual_seed(time.time())
oldvss = VMamba2Dp(depths=[2,2,6,2]).half().cuda()
newvss = VSSM(depths=[2,2,6,2]).half().cuda()
newvss.load_state_dict(oldvss.state_dict())
input = torch.randn((12, 3, 224, 224)).half().cuda()
torch.cuda.manual_seed(0)
with torch.cuda.amp.autocast():
y1 = oldvss.forward_backbone(input)
torch.cuda.manual_seed(0)
with torch.cuda.amp.autocast():
y2 = newvss.forward_backbone(input)
print((y1 -y2).abs().sum()) # tensor(0., device='cuda:0', grad_fn=<SumBackward0>)
# test 2 True ==========================================
torch.manual_seed(0); torch.cuda.manual_seed(0)
oldvss = VMamba2Dp(depths=[2,2,6,2]).cuda()
torch.manual_seed(0); torch.cuda.manual_seed(0)
newvss = VSSM(depths=[2,2,6,2]).cuda()
miss_align = 0
for k, v in oldvss.state_dict().items():
same = (oldvss.state_dict()[k] == newvss.state_dict()[k]).all()
if not same:
print(k, same)
miss_align += 1
print("init miss align", miss_align) # init miss align 0
if name == "main":
# check_vssm_equals_vmambadp()
model = VSSM().to('cuda')
int = torch.randn(16,1,224,224).cuda()
out = model(int)
print(out.shape) 为什么模型中的resnet和mamba可以兼容?
The compatibility between the resnet backbone (from timm) and the SS2D layer (reminiscent of Mamba) in the VSSMRes model is due to their architectural design, which allows seamless integration of different modules with compatible input and output dimensions. Here's a detailed explanation of how and why these components can work together effectively:
Feature Maps and Channels:
Both ResNet and Mamba are designed to operate on 4D tensor inputs (B, C, H, W format). This means that the output from a ResNet block can be directly used as the input to another module such as Mamba without requiring reshaping or transformation.
The number of channels (denoted as C) at various stages is set to be compatible. The resnet backbone can output feature maps with dimensions that match what the VSSM processing layer expects.
Hierarchical Feature Representation:
ResNet performs downsampling as it progresses through its layers, creating a hierarchical feature representation. The SS2D-based components in VSSM leverage this hierarchy to process features at different scales effectively.
This hierarchical processing is maintained through the model to capture different levels of abstraction, which is vital for tasks like image segmentation or recognition.
Neck and Head Definitions:
VSSM includes several downsample and upsample layers, e.g., PatchExpand and PatchMerging2D, which handle transitions between different scales of feature maps.
These transitions ensure that the outputs from resnet blocks are at the appropriate resolution for further processing by SS2D-based attention or decoding layers.
Parameter Initialization and Learned Representations:
The model is designed to seamlessly allow transfer of weighted parameters from pretrained models, which means the transformation layers around resnet and SS2D are initialized to be compatible if pretrained weights are loaded.
Flexibility and Modularity:
PyTorch modules (nn.Module) allow flexible stacking and integration. The VSSM uses multiple such modular components wherein resnet can be swapped with other backbones with relative ease, provided component dimensions align properly.
Feature Fusion:
Attention mechanisms and feature fusion layers, such as in VSSM, are designed to handle the diversity of features produced by different models like ResNet or transformers, aligning them for the final task outcome.
Overall, the compatibility results from careful design choices at the dimension and architecture level to ensure smooth interface between different modules like ResNet and Mamba-type SS2D layers within the broader VSSMRes model.