分析:import os import time import math import copy from functools import partial from…
Jump to turn (14)
- 1分析:import os import time import math import copy from functools import partial f
- 2中文回答
- 3再分析:import math import torch import torch.nn as nn import torch.nn.functional as
- 4中文回答
- 5import math import torch import numpy as np import torch.nn as nn from einops im
- 6但是那么上文中的FusionMamba和CrossMamba模块有何区别?
- 7当前的两个特征维度都是(2,320,768),那么如何使用上述两个模块?
- 8那么Crossmamba是否可以进一步优化?以实现特征的深度融合?
- 9那么首先给出 方案1的代码
- 10直接在def to3d(x): return rearrange(x, 'b c h w -> b (h w) c') def to4d(x, h, w): r
- 11此处堆叠了几层?
- 12那么基于class CrossMamba(nn.Module): def init(self, dim): super(CrossMamba, self).in
- 13当前模块:def to3d(x): return rearrange(x, 'b c h w -> b (h w) c') def to4d(x, h, w):
- 14但是原始的crossmamba逻辑是: m1resi = m1+m1resi globalf = self.crossmamba(m1, extraemb=m2
- User
分析:import os import time import math import copy from functools import partial from typing import Optional, Callable, Any from collections import OrderedDict
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 except: pass
an alternative for mamba_ssm
try: from selective_scan import selective_scan_fn as selective_scan_fn_v1 except: pass
cross selective scan ===============================
if True: import selective_scan_cuda_core as selective_scan_cuda
codeclass SelectiveScan(torch.autograd.Function): @staticmethod @torch.cuda.amp.custom_fwd(cast_inputs=torch.float32) def forward(ctx, u, delta, A, B, C, D=None, delta_bias=None, delta_softplus=False, nrows=1): assert nrows in [1, 2, 3, 4], f"{nrows}" # 8+ is too slow to compile assert u.shape[1] % (B.shape[1] * nrows) == 0, f"{nrows}, {u.shape}, {B.shape}" ctx.delta_softplus = delta_softplus ctx.nrows = nrows # all in float if u.stride(-1) != 1: u = u.contiguous() if delta.stride(-1) != 1: delta = delta.contiguous() if D is not None: D = D.contiguous() if B.stride(-1) != 1: B = B.contiguous() if C.stride(-1) != 1: C = C.contiguous() if B.dim() == 3: B = B.unsqueeze(dim=1) ctx.squeeze_B = True if C.dim() == 3: C = C.unsqueeze(dim=1) ctx.squeeze_C = True out, x, *rest = selective_scan_cuda.fwd(u, delta, A, B, C, D, delta_bias, delta_softplus, nrows) ctx.save_for_backward(u, delta, A, B, C, D, delta_bias, x) return out @staticmethod @torch.cuda.amp.custom_bwd def backward(ctx, dout, *args): u, delta, A, B, C, D, delta_bias, x = ctx.saved_tensors if dout.stride(-1) != 1: dout = dout.contiguous() du, ddelta, dA, dB, dC, dD, ddelta_bias, *rest = selective_scan_cuda.bwd( u, delta, A, B, C, D, delta_bias, dout, x, ctx.delta_softplus, 1 # u, delta, A, B, C, D, delta_bias, dout, x, ctx.delta_softplus, ctx.nrows, ) dB = dB.squeeze(1) if getattr(ctx, "squeeze_B", False) else dB dC = dC.squeeze(1) if getattr(ctx, "squeeze_C", False) else dC return (du, ddelta, dA, dB, dC, dD, ddelta_bias, None, None) class CrossScan(torch.autograd.Function): @staticmethod def forward(ctx, x: torch.Tensor): B, C, H, W = x.shape ctx.shape = (B, C, H, W) xs = x.new_empty((B, 4, C, H * W)) xs[:, 0] = x.flatten(2, 3) xs[:, 1] = x.transpose(dim0=2, dim1=3).flatten(2, 3) xs[:, 2:4] = torch.flip(xs[:, 0:2], dims=[-1]) return xs @staticmethod def backward(ctx, ys: torch.Tensor): # out: (b, k, d, l) B, C, H, W = ctx.shape L = H * W ys = ys[:, 0:2] + ys[:, 2:4].flip(dims=[-1]).view(B, 2, -1, L) y = ys[:, 0] + ys[:, 1].view(B, -1, W, H).transpose(dim0=2, dim1=3).contiguous().view(B, -1, L) return y.view(B, -1, H, W) class CrossMerge(torch.autograd.Function): @staticmethod def forward(ctx, ys: torch.Tensor): B, K, D, H, W = ys.shape ctx.shape = (H, W) ys = ys.view(B, K, D, -1) ys = ys[:, 0:2] + ys[:, 2:4].flip(dims=[-1]).view(B, 2, D, -1) y = ys[:, 0] + ys[:, 1].view(B, -1, W, H).transpose(dim0=2, dim1=3).contiguous().view(B, D, -1) return y @staticmethod def backward(ctx, x: torch.Tensor): # B, D, L = x.shape # out: (b, k, d, l) H, W = ctx.shape B, C, L = x.shape xs = x.new_empty((B, 4, C, L)) xs[:, 0] = x xs[:, 1] = x.view(B, C, H, W).transpose(dim0=2, dim1=3).flatten(2, 3) xs[:, 2:4] = torch.flip(xs[:, 0:2], dims=[-1]) xs = xs.view(B, 4, C, H, W) return xs, None, None class CrossScan_multimodal(torch.autograd.Function): @staticmethod def forward(ctx, x_rgb: torch.Tensor, x_e: torch.Tensor): # B, C, H, W -> B, 2, C, 2 * H * W B, C, H, W = x_rgb.shape ctx.shape = (B, C, H, W) xs_fuse = x_rgb.new_empty((B, 2, C, 2 * H * W)) xs_fuse[:, 0] = torch.concat([x_rgb.flatten(2, 3), x_e.flatten(2, 3)], dim=2) xs_fuse[:, 1] = torch.flip(xs_fuse[:, 0], dims=[-1]) return xs_fuse @staticmethod def backward(ctx, ys: torch.Tensor): # out: (b, 2, d, l) B, C, H, W = ctx.shape L = 2 * H * W ys = ys[:, 0] + ys[:, 1].flip(dims=[-1]) # B, d, 2 * H * W # get B, d, H*W return ys[:, :, 0:H*W].view(B, -1, H, W), ys[:, :, H*W:2*H*W].view(B, -1, H, W) class CrossMerge_multimodal(torch.autograd.Function): @staticmethod def forward(ctx, ys: torch.Tensor): B, K, D, L = ys.shape # ctx.shape = (H, W) # ys = ys.view(B, K, D, -1) ys = ys[:, 0] + ys[:, 1].flip(dims=[-1]) # B, d, 2 * H * W, broadcast # y = ys[:, :, 0:L//2] + ys[:, :, L//2:L] return ys[:, :, 0:L//2], ys[:, :, L//2:L] @staticmethod def backward(ctx, x1: torch.Tensor, x2: torch.Tensor): # B, D, L = x.shape # out: (b, k, d, l) # H, W = ctx.shape B, C, L = x1.shape xs = x1.new_empty((B, 2, C, 2*L)) xs[:, 0] = torch.cat([x1, x2], dim=2) xs[:, 1] = torch.flip(xs[:, 0], dims=[-1]) xs = xs.view(B, 2, C, 2*L) return xs, None, None def cross_selective_scan( x: torch.Tensor=None, x_proj_weight: torch.Tensor=None, x_proj_bias: torch.Tensor=None, dt_projs_weight: torch.Tensor=None, dt_projs_bias: torch.Tensor=None, A_logs: torch.Tensor=None, Ds: torch.Tensor=None, out_norm: torch.nn.Module=None, softmax_version=False, nrows = -1, delta_softplus = True, ): B, D, H, W = x.shape D, N = A_logs.shape K, D, R = dt_projs_weight.shape L = H * W if nrows < 1: if D % 4 == 0: nrows = 4 elif D % 3 == 0: nrows = 3 elif D % 2 == 0: nrows = 2 else: nrows = 1 xs = CrossScan.apply(x) x_dbl = torch.einsum("b k d l, k c d -> b k c l", xs, x_proj_weight) if x_proj_bias is not None: x_dbl = x_dbl + x_proj_bias.view(1, K, -1, 1) dts, Bs, Cs = torch.split(x_dbl, [R, N, N], dim=2) dts = torch.einsum("b k r l, k d r -> b k d l", dts, dt_projs_weight) xs = xs.view(B, -1, L).to(torch.float) dts = dts.contiguous().view(B, -1, L).to(torch.float) As = -torch.exp(A_logs.to(torch.float)) # (k * c, d_state) Bs = Bs.contiguous().to(torch.float) Cs = Cs.contiguous().to(torch.float) Ds = Ds.to(torch.float) # (K * c) delta_bias = dt_projs_bias.view(-1).to(torch.float) # to enable fvcore.nn.jit_analysis: inputs[i].debugName def selective_scan(u, delta, A, B, C, D=None, delta_bias=None, delta_softplus=True, nrows=1): return SelectiveScan.apply(u, delta, A, B, C, D, delta_bias, delta_softplus, nrows) ys: torch.Tensor = selective_scan( xs, dts, As, Bs, Cs, Ds, delta_bias, delta_softplus, nrows, ).view(B, K, -1, H, W) y = CrossMerge.apply(ys) if softmax_version: y = y.softmax(y, dim=-1).to(x.dtype) y = y.transpose(dim0=1, dim1=2).contiguous().view(B, H, W, -1) else: y = y.transpose(dim0=1, dim1=2).contiguous().view(B, H, W, -1) y = out_norm(y).to(x.dtype) return y def selective_scan_1d( x: torch.Tensor=None, x_proj_weight: torch.Tensor=None, x_proj_bias: torch.Tensor=None, dt_projs_weight: torch.Tensor=None, dt_projs_bias: torch.Tensor=None, A_logs: torch.Tensor=None, Ds: torch.Tensor=None, out_norm: torch.nn.Module=None, softmax_version=False, nrows = -1, delta_softplus = True, ): A_logs = A_logs[: A_logs.shape[0] // 4] Ds = Ds[: Ds.shape[0] // 4] B, D, H, W = x.shape D, N = A_logs.shape # get 1st of dt_projs_weight x_proj_weight = x_proj_weight[0].unsqueeze(0) x_proj_bias = x_proj_bias[0].unsqueeze(0) if x_proj_bias is not None else None dt_projs_weight = dt_projs_weight[0].unsqueeze(0) dt_projs_bias = dt_projs_bias[0].unsqueeze(0) if dt_projs_bias is not None else None K, D, R = dt_projs_weight.shape # K=1 L = H * W if nrows < 1: if D % 4 == 0: nrows = 4 elif D % 3 == 0: nrows = 3 elif D % 2 == 0: nrows = 2 else: nrows = 1 # xs = CrossScan.apply(x) xs = x.view(B, -1, L).unsqueeze(dim=1) x_dbl = torch.einsum("b k d l, k c d -> b k c l", xs, x_proj_weight) if x_proj_bias is not None: x_dbl = x_dbl + x_proj_bias.view(1, K, -1, 1) dts, Bs, Cs = torch.split(x_dbl, [R, N, N], dim=2) dts = torch.einsum("b k r l, k d r -> b k d l", dts, dt_projs_weight) xs = xs.view(B, -1, L).to(torch.float) dts = dts.contiguous().view(B, -1, L).to(torch.float) As = -torch.exp(A_logs.to(torch.float)) # (k * c, d_state) Bs = Bs.contiguous().to(torch.float) Cs = Cs.contiguous().to(torch.float) Ds = Ds.to(torch.float) # (K * c) delta_bias = dt_projs_bias.view(-1).to(torch.float) # to enable fvcore.nn.jit_analysis: inputs[i].debugName def selective_scan(u, delta, A, B, C, D=None, delta_bias=None, delta_softplus=True, nrows=1): return SelectiveScan.apply(u, delta, A, B, C, D, delta_bias, delta_softplus, nrows) ys: torch.Tensor = selective_scan( xs, dts, As, Bs, Cs, Ds, delta_bias, delta_softplus, nrows, ).view(B, K, -1, L) # y = CrossMerge.apply(ys) if softmax_version: y = y.softmax(y, dim=-1).to(x.dtype) y = ys[:, 0].transpose(dim0=1, dim1=2).contiguous().view(B, H, W, -1) else: y = ys[:, 0].transpose(dim0=1, dim1=2).contiguous().view(B, H, W, -1) y = out_norm(y).to(x.dtype) return y def cross_selective_scan_multimodal_k1( x_rgb: torch.Tensor=None, x_e: torch.Tensor=None, x_proj_weight: torch.Tensor=None, x_proj_bias: torch.Tensor=None, dt_projs_weight: torch.Tensor=None, dt_projs_bias: torch.Tensor=None, A_logs: torch.Tensor=None, Ds: torch.Tensor=None, out_norm: torch.nn.Module=None, softmax_version=False, nrows = -1, delta_softplus = True, ): B, D, H, W = x_rgb.shape D, N = A_logs.shape K, D, R = dt_projs_weight.shape L = 2 * H * W if nrows < 1: if D % 4 == 0: nrows = 4 elif D % 3 == 0: nrows = 3 elif D % 2 == 0: nrows = 2 else: nrows = 1 # x_fuse = CrossScan_multimodal.apply(x_rgb, x_e) # B, C, H, W -> B, 1, C, 2 * H * W B, C, H, W = x_rgb.shape x_fuse = x_rgb.new_empty((B, 1, C, 2 * H * W)) x_fuse[:, 0] = torch.concat([x_rgb.flatten(2, 3), x_e.flatten(2, 3)], dim=2) x_dbl = torch.einsum("b k d l, k c d -> b k c l", x_fuse, x_proj_weight) if x_proj_bias is not None: x_dbl = x_dbl + x_proj_bias.view(1, K, -1, 1) dts, Bs, Cs = torch.split(x_dbl, [R, N, N], dim=2) dts = torch.einsum("b k r l, k d r -> b k d l", dts, dt_projs_weight) x_fuse = x_fuse.view(B, -1, L).to(torch.float) dts = dts.contiguous().view(B, -1, L).to(torch.float) As = -torch.exp(A_logs.to(torch.float)) # (k * c, d_state) Bs = Bs.contiguous().to(torch.float) Cs = Cs.contiguous().to(torch.float) Ds = Ds.to(torch.float) # (K * c) delta_bias = dt_projs_bias.view(-1).to(torch.float) # to enable fvcore.nn.jit_analysis: inputs[i].debugName def selective_scan(u, delta, A, B, C, D=None, delta_bias=None, delta_softplus=True, nrows=1): return SelectiveScan.apply(u, delta, A, B, C, D, delta_bias, delta_softplus, nrows) ys: torch.Tensor = selective_scan( x_fuse, dts, As, Bs, Cs, Ds, delta_bias, delta_softplus, nrows, ).view(B, K, -1, 2*H*W) # y = CrossMerge_multimodal.apply(ys) y = ys[:, 0, :, 0:L//2] + ys[:, 0, :, L//2:L] if softmax_version: y = y.softmax(y, dim=-1).to(x_rgb.dtype) y = y.transpose(dim0=1, dim1=2).contiguous().view(B, H, W, -1) else: y = y.transpose(dim0=1, dim1=2).contiguous().view(B, H, W, -1) y = out_norm(y).to(x_rgb.dtype) return y def cross_selective_scan_multimodal_k2( x_rgb: torch.Tensor=None, x_e: torch.Tensor=None, x_proj_weight: torch.Tensor=None, x_proj_bias: torch.Tensor=None, dt_projs_weight: torch.Tensor=None, dt_projs_bias: torch.Tensor=None, A_logs: torch.Tensor=None, Ds: torch.Tensor=None, out_norm1: torch.nn.Module=None, out_norm2: torch.nn.Module=None, softmax_version=False, nrows = -1, delta_softplus = True, ): B, D, H, W = x_rgb.shape D, N = A_logs.shape K, D, R = dt_projs_weight.shape L = 2 * H * W if nrows < 1: if D % 4 == 0: nrows = 4 elif D % 3 == 0: nrows = 3 elif D % 2 == 0: nrows = 2 else: nrows = 1 x_fuse = CrossScan_multimodal.apply(x_rgb, x_e) # B, C, H, W -> B, 2, C, 2 * H * W x_dbl = torch.einsum("b k d l, k c d -> b k c l", x_fuse, x_proj_weight) if x_proj_bias is not None: x_dbl = x_dbl + x_proj_bias.view(1, K, -1, 1) dts, Bs, Cs = torch.split(x_dbl, [R, N, N], dim=2) dts = torch.einsum("b k r l, k d r -> b k d l", dts, dt_projs_weight) x_fuse = x_fuse.view(B, -1, L).to(torch.float) dts = dts.contiguous().view(B, -1, L).to(torch.float) As = -torch.exp(A_logs.to(torch.float)) # (k * c, d_state) Bs = Bs.contiguous().to(torch.float) Cs = Cs.contiguous().to(torch.float) Ds = Ds.to(torch.float) # (K * c) delta_bias = dt_projs_bias.view(-1).to(torch.float) # to enable fvcore.nn.jit_analysis: inputs[i].debugName def selective_scan(u, delta, A, B, C, D=None, delta_bias=None, delta_softplus=True, nrows=1): return SelectiveScan.apply(u, delta, A, B, C, D, delta_bias, delta_softplus, nrows) ys: torch.Tensor = selective_scan( x_fuse, dts, As, Bs, Cs, Ds, delta_bias, delta_softplus, nrows, ).view(B, K, -1, 2*H*W) y_rgb, y_e = CrossMerge_multimodal.apply(ys) y_rgb = y_rgb.transpose(dim0=1, dim1=2).contiguous().view(B, H, W, -1) y_e = y_e.transpose(dim0=1, dim1=2).contiguous().view(B, H, W, -1) y_rgb = out_norm1(y_rgb).to(x_rgb.dtype) y_e = out_norm2(y_e).to(x_e.dtype) return y_rgb, y_efvcore flops =======================================
def flops_selective_scan_fn(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
codeignores: [.float(), +, .softplus, .shape, new_zeros, repeat, stack, to(dtype), silu] """ assert not with_complex # https://github.com/state-spaces/mamba/issues/110 flops = 9 * B * L * D * N if with_D: flops += B * D * L if with_Z: flops += B * D * L return flopsdef 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
codeignores: [.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 flopsdef print_jit_input_names(inputs): # tensor.11, dt.1, A.1, B.1, C.1, D.1, z.1, None try: print("input params: ", end=" ", flush=True) for i in range(10): print(inputs[i].debugName(), end=" ", flush=True) except Exception as e: pass print("", flush=True)
def selective_scan_flop_jit(inputs, outputs): print_jit_input_names(inputs)
code# xs, dts, As, Bs, Cs, Ds (skip), z (skip), dt_projs_bias (skip) assert inputs[0].debugName().startswith("xs") # (B, D, L) assert inputs[1].debugName().startswith("dts") # (B, D, L) assert inputs[2].debugName().startswith("As") # (D, N) assert inputs[3].debugName().startswith("Bs") # (D, N) assert inputs[4].debugName().startswith("Cs") # (D, N) with_Group = len(inputs[3].type().sizes()) == 4 with_D = inputs[5].debugName().startswith("Ds") if not with_D: with_z = len(inputs) > 5 and inputs[5].debugName().startswith("z") else: with_z = len(inputs) > 6 and inputs[6].debugName().startswith("z") B, D, L = inputs[0].type().sizes() N = inputs[2].type().sizes()[1] flops = flops_selective_scan_fn(B=B, L=L, D=D, N=N, with_D=with_D, with_Z=with_z, with_Group=with_Group) # flops = flops_selective_scan_ref(B=B, L=L, D=D, N=N, with_D=with_D, with_Z=with_z, with_Group=with_Group) return flops=====================================================
class PatchMerging2D(nn.Module): def init(self, dim, out_dim=-1, norm_layer=nn.LayerNorm): super().init() self.dim = dim self.reduction = nn.Linear(4 * dim, (2 * dim) if out_dim < 0 else out_dim, bias=False) self.norm = norm_layer(4 * dim)
code@staticmethod def _patch_merging_pad(x: torch.Tensor): H, W, _ = x.shape[-3:] if (W % 2 != 0) or (H % 2 != 0): x = F.pad(x, (0, 0, 0, W % 2, 0, H % 2)) x0 = x[..., 0::2, 0::2, :] # ... H/2 W/2 C x1 = x[..., 1::2, 0::2, :] # ... H/2 W/2 C x2 = x[..., 0::2, 1::2, :] # ... H/2 W/2 C x3 = x[..., 1::2, 1::2, :] # ... H/2 W/2 C x = torch.cat([x0, x1, x2, x3], -1) # ... H/2 W/2 4*C return x def forward(self, x): x = self._patch_merging_pad(x) x = self.norm(x) x = self.reduction(x) return xDEV = False class SS2D(nn.Module): def init( self, # basic dims =========== d_model=96, d_state=16, ssm_ratio=2, dt_rank="auto", # dwconv =============== # d_conv=-1, # < 2 means no conv d_conv=3, # < 2 means no conv conv_bias=True, # ====================== dropout=0., bias=False, # dt init ============== dt_min=0.001, dt_max=0.1, dt_init="random", dt_scale=1.0, dt_init_floor=1e-4, # ====================== softmax_version=False, # ====================== **kwargs, ): if DEV: d_conv = -1
codefactory_kwargs = {"device": None, "dtype": None} super().__init__() self.softmax_version = softmax_version self.d_model = d_model self.d_state = math.ceil(self.d_model / 6) if d_state == "auto" else d_state # 20240109 self.d_conv = d_conv self.expand = ssm_ratio 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 self.in_proj = nn.Linear(self.d_model, self.d_inner * 2, bias=bias, **factory_kwargs) # conv ======================================= if self.d_conv > 1: 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() # x proj; dt proj ============================ self.K = 4 if not (self.forward_core == self.forward_corev1_share_ssm) else 1 # VMamaba set K=4, while original SSM set K=1 if self.forward_core == self.forward_corev0: self.K = 1 self.x_proj = [ nn.Linear(self.d_inner, (self.dt_rank + self.d_state * 2), bias=False, **factory_kwargs) for _ in range(self.K) ] self.x_proj_weight = nn.Parameter(torch.stack([t.weight for t in self.x_proj], dim=0)) # (K, N, inner) 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) for _ in range(self.K) ] self.dt_projs_weight = nn.Parameter(torch.stack([t.weight for t in self.dt_projs], dim=0)) # (K, inner, rank) self.dt_projs_bias = nn.Parameter(torch.stack([t.bias for t in self.dt_projs], dim=0)) # (K, inner) del self.dt_projs # A, D ======================================= self.K2 = self.K if not (self.forward_core == self.forward_corev1_share_a) else 1 # VMamaba set K=4, while original SSM set K=1 if self.forward_core == self.forward_corev0: self.K2 = 1 self.A_logs = self.A_log_init(self.d_state, self.d_inner, copies=self.K2, merge=True) # (K * D, N) self.Ds = self.D_init(self.d_inner, copies=self.K2, merge=True) # (K * D) # out proj ======================================= if not self.softmax_version: 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 nn.Identity() @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, **factory_kwargs): dt_proj = nn.Linear(dt_rank, d_inner, bias=True, **factory_kwargs) # 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) else: raise NotImplementedError # 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 return dt_proj @staticmethod def A_log_init(d_state, d_inner, copies=-1, device=None, merge=True): # 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) # Keep A_log in fp32 if copies > 0: A_log = repeat(A_log, "d n -> r d n", r=copies) if merge: A_log = A_log.flatten(0, 1) A_log = nn.Parameter(A_log) A_log._no_weight_decay = True return A_log @staticmethod def D_init(d_inner, copies=-1, device=None, merge=True): # D "skip" parameter D = torch.ones(d_inner, device=device) if copies > 0: D = repeat(D, "n1 -> r n1", r=copies) if merge: D = D.flatten(0, 1) D = nn.Parameter(D) # Keep in fp32 D._no_weight_decay = True return D def forward_corev0(self, x: torch.Tensor): selective_scan = selective_scan_fn_v1 B, C, H, W = x.shape L = H * W K = 1 #4 # x_hwwh = torch.stack([x.view(B, -1, L), torch.transpose(x, dim0=2, dim1=3).contiguous().view(B, -1, L)], dim=1).view(B, 2, -1, L) # xs = torch.cat([x_hwwh, torch.flip(x_hwwh, dims=[-1])], dim=1) # (b, k, d, l) xs = x.view(B, -1, L).unsqueeze(dim=1) x_dbl = torch.einsum("b k d l, k c d -> b k c l", xs, self.x_proj_weight) # x_dbl = x_dbl + self.x_proj_bias.view(1, K, -1, 1) dts, Bs, Cs = torch.split(x_dbl, [self.dt_rank, self.d_state, self.d_state], dim=2) dts = torch.einsum("b k r l, k d r -> b k d l", dts, self.dt_projs_weight) xs = xs.float().view(B, -1, L) # (b, k * d, l) dts = dts.contiguous().float().view(B, -1, L) # (b, k * d, l) Bs = Bs.float() # (b, k, d_state, l) Cs = Cs.float() # (b, k, d_state, l) As = -torch.exp(self.A_logs.float()) # (k * d, d_state) Ds = self.Ds.float() # (k * d) dt_projs_bias = self.dt_projs_bias.float().view(-1) # (k * d) # assert len(xs.shape) == 3 and len(dts.shape) == 3 and len(Bs.shape) == 4 and len(Cs.shape) == 4 # assert len(As.shape) == 2 and len(Ds.shape) == 1 and len(dt_projs_bias.shape) == 1 out_y = selective_scan( xs, dts, As, Bs, Cs, Ds, #z=None, delta_bias=dt_projs_bias, delta_softplus=True, # return_last_state=False, ).view(B, K, -1, L) # assert out_y.dtype == torch.float # inv_y = torch.flip(out_y[:, 2:4], dims=[-1]).view(B, 2, -1, L) # wh_y = torch.transpose(out_y[:, 1].view(B, -1, W, H), dim0=2, dim1=3).contiguous().view(B, -1, L) # invwh_y = torch.transpose(inv_y[:, 1].view(B, -1, W, H), dim0=2, dim1=3).contiguous().view(B, -1, L) # y = out_y[:, 0] + inv_y[:, 0] + wh_y + invwh_y # y = torch.transpose(y, dim0=1, dim1=2).contiguous().view(B, H, W, -1) y = torch.transpose(out_y[:, 0], dim0=1, dim1=2).contiguous().view(B, H, W, -1) y = self.out_norm(y) return y def forward_corev0_seq(self, x: torch.Tensor): selective_scan = selective_scan_fn B, C, H, W = x.shape L = H * W K = 4 x_hwwh = torch.stack([x.view(B, -1, L), torch.transpose(x, dim0=2, dim1=3).contiguous().view(B, -1, L)], dim=1).view(B, 2, -1, L) xs = torch.cat([x_hwwh, torch.flip(x_hwwh, dims=[-1])], dim=1) # (b, k, d, l) x_dbl = torch.einsum("b k d l, k c d -> b k c l", xs.view(B, K, -1, L), self.x_proj_weight) # x_dbl = x_dbl + self.x_proj_bias.view(1, K, -1, 1) dts, Bs, Cs = torch.split(x_dbl, [self.dt_rank, self.d_state, self.d_state], dim=2) dts = torch.einsum("b k r l, k d r -> b k d l", dts.view(B, K, -1, L), self.dt_projs_weight) xs = xs.float() # (b, k, d, l) dts = dts.contiguous().float() # (b, k, d, l) Bs = Bs.float() # (b, k, d_state, l) Cs = Cs.float() # (b, k, d_state, l) As = -torch.exp(self.A_logs.float()).view(K, -1, self.d_state) # (k, d, d_state) Ds = self.Ds.float().view(K, -1) # (k, d) dt_projs_bias = self.dt_projs_bias.float().view(K, -1) # (k, d) # assert len(xs.shape) == 4 and len(dts.shape) == 4 and len(Bs.shape) == 4 and len(Cs.shape) == 4 # assert len(As.shape) == 3 and len(Ds.shape) == 2 and len(dt_projs_bias.shape) == 2 out_y = [] for i in range(4): yi = selective_scan( xs[:, i], dts[:, i], As[i], Bs[:, i], Cs[:, i], Ds[i], delta_bias=dt_projs_bias[i], delta_softplus=True, ).view(B, -1, L) out_y.append(yi) out_y = torch.stack(out_y, dim=1) assert out_y.dtype == torch.float inv_y = torch.flip(out_y[:, 2:4], dims=[-1]).view(B, 2, -1, L) wh_y = torch.transpose(out_y[:, 1].view(B, -1, W, H), dim0=2, dim1=3).contiguous().view(B, -1, L) invwh_y = torch.transpose(inv_y[:, 1].view(B, -1, W, H), dim0=2, dim1=3).contiguous().view(B, -1, L) y = out_y[:, 0] + inv_y[:, 0] + wh_y + invwh_y y = torch.transpose(y, dim0=1, dim1=2).contiguous().view(B, H, W, -1) y = self.out_norm(y) return y def forward_corev1(self, x: torch.Tensor, float32=True): # float32 should be true in training!!!! otherwise, the output of selective_scan would be inf... selective_scan = selective_scan_fn_v1 B, C, H, W = x.shape L = H * W xs = torch.stack([x.flatten(2, 3), x.transpose(dim0=2, dim1=3).contiguous().flatten(2, 3)], dim=1) xs = torch.cat([xs, torch.flip(xs, dims=[-1])], dim=1) # (b, k, d, l) x_dbl = torch.einsum("b k d l, k c d -> b k c l", xs, self.x_proj_weight) # x_dbl = x_dbl + self.x_proj_bias.view(1, K, -1, 1) dts, Bs, Cs = torch.split(x_dbl, [self.dt_rank, self.d_state, self.d_state], dim=2) dts = torch.einsum("b k r l, k d r -> b k d l", dts, self.dt_projs_weight) xs = xs.view(B, -1, L) # (b, k * d, l) dts = dts.contiguous().view(B, -1, L) # (b, k * d, l) As = -torch.exp(self.A_logs.to(torch.float)) # (k * d, d_state) Ds = self.Ds.to(torch.float) # (k * d) dt_projs_bias = self.dt_projs_bias.to(torch.float).view(-1) # (k * d) if float32: ys: torch.Tensor = selective_scan( xs.to(torch.float), dts.to(torch.float), As, Bs.to(torch.float), Cs.to(torch.float), Ds, delta_bias=dt_projs_bias, delta_softplus=True, ).view(B, 4, -1, L) ys = ys[:, 0:2] + ys[:, 2:4].flip(dims=[-1]).view(B, 2, -1, L) y = ys[:, 0] + ys[:, 1].view(B, -1, W, H).transpose(dim0=2, dim1=3).contiguous().view(B, -1, L) else: out_y: torch.Tensor = selective_scan( xs, dts, As, Bs, Cs, Ds, delta_bias=dt_projs_bias, delta_softplus=True, ).view(B, 4, -1, L) # assert out_y.dtype == torch.float16 inv_y = torch.flip(out_y[:, 2:4], dims=[-1]).view(B, 2, -1, L) wh_y = torch.transpose(out_y[:, 1].view(B, -1, W, H), dim0=2, dim1=3).contiguous().view(B, -1, L) invwh_y = torch.transpose(inv_y[:, 1].view(B, -1, W, H), dim0=2, dim1=3).contiguous().view(B, -1, L) y = out_y[:, 0].float() + inv_y[:, 0].float() + wh_y.float() + invwh_y.float() if self.softmax_version: y = torch.softmax(y, dim=-1).to(x.dtype) y = torch.transpose(y, dim0=1, dim1=2).contiguous().view(B, H, W, -1) else: y = torch.transpose(y, dim0=1, dim1=2).contiguous().view(B, H, W, -1) y = self.out_norm(y).to(x.dtype) # if torch.isinf(y).any() or torch.isnan(y).any(): # for item in [y, xs, dts, As, Bs, Cs, Ds]: # print(torch.isinf(item).any(), torch.isnan(item).any(), item.max(), item.min()) # import time; time.sleep(10000) return y def forward_corev1_share_ssm(self, x: torch.Tensor): selective_scan = selective_scan_fn_v1 B, C, H, W = x.shape L = H * W def cross_scan_2d(x): # (B, C, H, W) => (B, K, C, H * W) with K = len([HW, WH, FHW, FWH]) x_hwwh = torch.stack([x.flatten(2, 3), x.transpose(dim0=2, dim1=3).contiguous().flatten(2, 3)], dim=1) xs = torch.cat([x_hwwh, torch.flip(x_hwwh, dims=[-1])], dim=1) # (b, k, d, l) return xs x_dbl = torch.einsum("b d l, c d -> b c l", x.view(B, -1, L), self.x_proj_weight[0]) # x_dbl = x_dbl + self.x_proj_bias.view(1, -1, 1) dt, BC = torch.split(x_dbl, [self.dt_rank, 2 * self.d_state], dim=1) dt = torch.einsum("b r l, d r -> b d l", dt, self.dt_projs_weight[0]) x_dt_BC = torch.cat([x, dt.view(B, -1, H, W), BC.view(B, -1, H, W)], dim=1) # (b, -1, h, w) x_dt_BCs = cross_scan_2d(x_dt_BC) # (b, k, d, l) xs, dts, Bs, Cs = torch.split(x_dt_BCs, [self.d_inner, self.d_inner, self.d_state, self.d_state], dim=2) xs = xs.contiguous().view(B, -1, L) # (b, k * d, l) dts = dts.contiguous().view(B, -1, L) # (b, k * d, l) As = -torch.exp(self.A_logs.float()).repeat(4, 1) # (k * d, d_state) Ds = self.Ds.repeat(4) # (k * d) dt_projs_bias = self.dt_projs_bias.view(-1).repeat(4) # (k * d) # assert len(xs.shape) == 3 and len(dts.shape) == 3 and len(Bs.shape) == 4 and len(Cs.shape) == 4 # assert len(As.shape) == 2 and len(Ds.shape) == 1 and len(dt_projs_bias.shape) == 1 out_y = selective_scan( xs, dts, As, Bs, Cs, Ds, delta_bias=dt_projs_bias, delta_softplus=True, ).view(B, 4, -1, L) # assert out_y.dtype == torch.float16 inv_y = torch.flip(out_y[:, 2:4], dims=[-1]).view(B, 2, -1, L) wh_y = torch.transpose(out_y[:, 1].view(B, -1, W, H), dim0=2, dim1=3).contiguous().view(B, -1, L) invwh_y = torch.transpose(inv_y[:, 1].view(B, -1, W, H), dim0=2, dim1=3).contiguous().view(B, -1, L) y = out_y[:, 0].float() + inv_y[:, 0].float() + wh_y.float() + invwh_y.float() if self.softmax_version: y = torch.softmax(y, dim=-1).to(x.dtype) y = torch.transpose(y, dim0=1, dim1=2).contiguous().view(B, H, W, -1) else: y = torch.transpose(y, dim0=1, dim1=2).contiguous().view(B, H, W, -1) y = self.out_norm(y).to(x.dtype) return y def forward_corev1_share_a(self, x: torch.Tensor): selective_scan = selective_scan_fn_v1 B, C, H, W = x.shape L = H * W def cross_scan_2d(x, dim=1): # (B, C, H, W) => (B, K, C, H * W) with K = len([HW, WH, FHW, FWH]) x_hwwh = torch.stack([x.flatten(2, 3), x.transpose(dim0=2, dim1=3).contiguous().flatten(2, 3)], dim=dim) xs = torch.cat([x_hwwh, torch.flip(x_hwwh, dims=[-1])], dim=dim) # (b, k, d, l) return xs K = 4 xs = cross_scan_2d(x, dim=1) # (b, d, k, l) x_dbl = torch.einsum("b k d l, k c d -> b k c l", xs, self.x_proj_weight) # x_dbl = x_dbl + self.x_proj_bias.view(1, K, -1, 1) dts, Bs, Cs = torch.split(x_dbl, [self.dt_rank, self.d_state, self.d_state], dim=2) dts = torch.einsum("b k r l, k d r -> b k d l", dts, self.dt_projs_weight) dts = dts + self.dt_projs_bias.to(xs.dtype).view(1, K, -1, 1) xs = xs.transpose(dim0=1, dim1=2).contiguous().view(B, -1, K * L) dts = dts.transpose(dim0=1, dim1=2).contiguous().view(B, -1, K * L) As = -torch.exp(self.A_logs.float()) # (D, N) Ds = self.Ds.view(-1) # (D) Bs = Bs.transpose(dim0=1, dim1=2).contiguous().view(B, 1, -1, K * L) Cs = Cs.transpose(dim0=1, dim1=2).contiguous().view(B, 1, -1, K * L) # assert len(xs.shape) == 3 and len(dts.shape) == 3 and len(Bs.shape) == 4 and len(Cs.shape) == 4 # assert len(As.shape) == 2 and len(Ds.shape) == 1 and len(dt_projs_bias.shape) == 1 # print(self.Ds.dtype, self.A_logs.dtype, self.dt_projs_bias.dtype, flush=True) # fp16, fp16, fp16 out_y = selective_scan( xs, dts, As, Bs, Cs, Ds, delta_bias=None, delta_softplus=True, ).view(B, -1, 4, L) # assert out_y.dtype == torch.float16 inv_y = torch.flip(out_y[:, :, 2:4], dims=[-1]).view(B, -1, 2, L) wh_y = torch.transpose(out_y[:, :, 1].view(B, -1, W, H), dim0=2, dim1=3).contiguous().view(B, -1, L) invwh_y = torch.transpose(inv_y[:, :, 1].view(B, -1, W, H), dim0=2, dim1=3).contiguous().view(B, -1, L) y = out_y[:, :, 0].float() + inv_y[:, :, 0].float() + wh_y.float() + invwh_y.float() if self.softmax_version: y = torch.softmax(y, dim=-1).to(x.dtype) y = torch.transpose(y, dim0=1, dim1=2).contiguous().view(B, H, W, -1) else: y = torch.transpose(y, dim0=1, dim1=2).contiguous().view(B, H, W, -1) y = self.out_norm(y).to(x.dtype) return y def forward_corev2(self, x: torch.Tensor, nrows=-1): return cross_selective_scan( x, self.x_proj_weight, None, self.dt_projs_weight, self.dt_projs_bias, self.A_logs, self.Ds, getattr(self, "out_norm", None), self.softmax_version, nrows=nrows, ) def forward_core_1d(self, x: torch.Tensor): return selective_scan_1d( x, self.x_proj_weight, None, self.dt_projs_weight, self.dt_projs_bias, self.A_logs, self.Ds, getattr(self, "out_norm", None), self.softmax_version, ) # forward_core = forward_core_share_ssm # forward_core = forward_core_share_a # forward_core = forward_corev1 forward_core = forward_corev2 # vmamba # forward_core = forward_corev0 # ori mamba # forward_core = forward_core_1d # ori mamba def forward(self, x: torch.Tensor, **kwargs): xz = self.in_proj(x) if self.d_conv > 1: x, z = xz.chunk(2, dim=-1) # (b, h, w, d) x = x.permute(0, 3, 1, 2).contiguous() x = self.act(self.conv2d(x)) # (b, d, h, w) y = self.forward_core(x) if self.softmax_version: y = y * z else: y = y * F.silu(z) else: if self.softmax_version: x, z = xz.chunk(2, dim=-1) # (b, h, w, d) x = F.silu(x) else: xz = F.silu(xz) x, z = xz.chunk(2, dim=-1) # (b, h, w, d) x = x.permute(0, 3, 1, 2).contiguous() y = self.forward_core(x) y = y * z out = self.dropout(self.out_proj(y)) return outclass ConMB_SS2D(nn.Module): ''' Multimodal Mamba Selective Scan 2D ''' def init( self, # basic dims =========== d_model=96, d_state=4, ssm_ratio=2, dt_rank="auto", # dwconv =============== # d_conv=-1, # < 2 means no conv d_conv=3, # < 2 means no conv conv_bias=True, # ====================== dropout=0., bias=False, # dt init ============== dt_min=0.001, dt_max=0.1, dt_init="random", dt_scale=1.0, dt_init_floor=1e-4, # ====================== softmax_version=False, # ====================== **kwargs, ): if DEV: d_conv = -1
codefactory_kwargs = {"device": None, "dtype": None} super().__init__() self.softmax_version = softmax_version self.d_model = d_model self.d_state = math.ceil(self.d_model / 6) if d_state == "auto" else d_state # 20240109 self.d_conv = d_conv self.expand = ssm_ratio 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 self.in_proj = nn.Linear(self.d_model, self.d_inner, bias=bias, **factory_kwargs) self.in_proj_modalx = nn.Linear(self.d_model, self.d_inner, bias=bias, **factory_kwargs) # conv ======================================= if self.d_conv > 1: 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.conv2d_modalx = 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() # x proj; dt proj ============================ self.K = 2 self.x_proj = [ nn.Linear(self.d_inner, (self.dt_rank + self.d_state * 2), bias=False, **factory_kwargs) for _ in range(self.K) ] self.x_proj_weight = nn.Parameter(torch.stack([t.weight for t in self.x_proj], dim=0)) # (K, N, inner) 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) for _ in range(self.K) ] self.dt_projs_weight = nn.Parameter(torch.stack([t.weight for t in self.dt_projs], dim=0)) # (K, inner, rank) self.dt_projs_bias = nn.Parameter(torch.stack([t.bias for t in self.dt_projs], dim=0)) # (K, inner) del self.dt_projs # A, D ======================================= self.K2 = self.K self.A_logs = self.A_log_init(self.d_state, self.d_inner, copies=self.K2, merge=True) # (K * D, N) self.Ds = self.D_init(self.d_inner, copies=self.K2, merge=True) # (K * D) # out proj ======================================= if not self.softmax_version: self.out_norm1 = nn.LayerNorm(self.d_inner) self.out_norm2 = nn.LayerNorm(self.d_inner) self.out_proj = nn.Linear(self.d_inner*2, self.d_model, bias=bias, **factory_kwargs) self.dropout = nn.Dropout(dropout) if dropout > 0. else nn.Identity() self.avg_pool = nn.AdaptiveAvgPool2d(1) self.fc1 = nn.Sequential( nn.Linear(self.d_inner, self.d_inner // 16, bias=False), nn.SiLU(inplace=True), nn.Linear(self.d_inner // 16, self.d_inner, bias=False), nn.Sigmoid(), ) self.fc2 = nn.Sequential( nn.Linear(self.d_inner, self.d_inner // 16, bias=False), nn.SiLU(inplace=True), nn.Linear(self.d_inner // 16, self.d_inner, bias=False), nn.Sigmoid(), ) @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, **factory_kwargs): dt_proj = nn.Linear(dt_rank, d_inner, bias=True, **factory_kwargs) # 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) else: raise NotImplementedError # 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 return dt_proj @staticmethod def A_log_init(d_state, d_inner, copies=-1, device=None, merge=True): # 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) # Keep A_log in fp32 if copies > 0: A_log = repeat(A_log, "d n -> r d n", r=copies) if merge: A_log = A_log.flatten(0, 1) A_log = nn.Parameter(A_log) A_log._no_weight_decay = True return A_log @staticmethod def D_init(d_inner, copies=-1, device=None, merge=True): # D "skip" parameter D = torch.ones(d_inner, device=device) if copies > 0: D = repeat(D, "n1 -> r n1", r=copies) if merge: D = D.flatten(0, 1) D = nn.Parameter(D) # Keep in fp32 D._no_weight_decay = True return D def forward_corev2_multimodal(self, x_rgb: torch.Tensor, x_e: torch.Tensor, nrows=-1): return cross_selective_scan_multimodal_k2( x_rgb, x_e, self.x_proj_weight, None, self.dt_projs_weight, self.dt_projs_bias, self.A_logs, self.Ds, getattr(self, "out_norm1", None), getattr(self, "out_norm2", None), self.softmax_version, nrows=nrows, ) def forward(self, x_rgb: torch.Tensor, x_e: torch.Tensor): x_rgb = self.in_proj(x_rgb) x_e = self.in_proj_modalx(x_e) if self.d_conv > 1: x_rgb_trans = x_rgb.permute(0, 3, 1, 2).contiguous() x_e_trans = x_e.permute(0, 3, 1, 2).contiguous() x_rgb_conv = self.act(self.conv2d(x_rgb_trans)) # (b, d, h, w) x_e_conv = self.act(self.conv2d_modalx(x_e_trans)) # (b, d, h, w) y_rgb, y_e = self.forward_corev2_multimodal(x_rgb_conv, x_e_conv) # b, d, h, w -> b, h, w, d # SE to get attention, scale b, d, h, w = x_rgb_trans.shape x_rgb_squeeze = self.avg_pool(x_rgb_trans).view(b, d) x_e_squeeze = self.avg_pool(x_e_trans).view(b, d) x_rgb_exitation = self.fc1(x_rgb_squeeze).view(b, d, 1, 1).permute(0, 2, 3, 1).contiguous() # b, 1, 1, d x_e_exitation = self.fc2(x_e_squeeze).view(b, d, 1, 1).permute(0, 2, 3, 1).contiguous() y_rgb = y_rgb * x_e_exitation y_e = y_e * x_rgb_exitation y = torch.concat([y_rgb, y_e], dim=-1) out = self.dropout(self.out_proj(y)) return out=====================================================
class SSM(nn.Module): def init( self, # basic dims =========== d_model=96, d_state=4, ssm_ratio=2, dt_rank="auto", # dt init ============== dt_min=0.001, dt_max=0.1, dt_init="random", dt_scale=1.0, dt_init_floor=1e-4, # ====================== **kwargs, ): factory_kwargs = {"device": None, "dtype": None} super().init() self.d_model = d_model self.d_state = math.ceil(self.d_model / 6) if d_state == "auto" else d_state # 20240109 self.expand = ssm_ratio 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# x proj; dt proj ============================ self.x_proj = nn.Linear(self.d_inner, (self.dt_rank + self.d_state * 2), bias=False, **factory_kwargs) self.dt_proj = self.dt_init(self.dt_rank, self.d_inner, dt_scale, dt_init, dt_min, dt_max, dt_init_floor, **factory_kwargs) # A, D ======================================= self.A_log = self.A_log_init(self.d_state, self.d_inner) # (D, N) self.D = self.D_init(self.d_inner) # (D) # out norm =================================== self.out_norm = nn.LayerNorm(self.d_inner) @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, **factory_kwargs): dt_proj = nn.Linear(dt_rank, d_inner, bias=True, **factory_kwargs) # 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) else: raise NotImplementedError # 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 return dt_proj @staticmethod def A_log_init(d_state, d_inner, copies=-1, device=None, merge=True): # 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) # Keep A_log in fp32 if copies > 0: A_log = repeat(A_log, "d n -> r d n", r=copies) if merge: A_log = A_log.flatten(0, 1) A_log = nn.Parameter(A_log) A_log._no_weight_decay = True return A_log @staticmethod def D_init(d_inner, copies=-1, device=None, merge=True): # D "skip" parameter D = torch.ones(d_inner, device=device) if copies > 0: D = repeat(D, "n1 -> r n1", r=copies) if merge: D = D.flatten(0, 1) D = nn.Parameter(D) # Keep in fp32 D._no_weight_decay = True return D def forward(self, x: torch.Tensor): selective_scan = selective_scan_fn_v1 B, L, d = x.shape x = x.permute(0, 2, 1) x_dbl = self.x_proj(rearrange(x, "b d l -> (b l) d")) # (bl d) dt, B, C = torch.split(x_dbl, [self.dt_rank, self.d_state, self.d_state], dim=-1) dt = self.dt_proj.weight @ dt.t() dt = rearrange(dt, "d (b l) -> b d l", l=L) A = -torch.exp(self.A_log.float()) # (k * d, d_state) B = rearrange(B, "(b l) dstate -> b dstate l", l=L).contiguous() C = rearrange(C, "(b l) dstate -> b dstate l", l=L).contiguous() y = selective_scan( x, dt, A, B, C, self.D.float(), delta_bias=self.dt_proj.bias.float(), delta_softplus=True, ) # assert out_y.dtype == torch.float y = rearrange(y, "b d l -> b l d") y = self.out_norm(y) return y=====================================================
class Cross_Mamba_Attention_SSM(nn.Module): def init( self, # basic dims =========== d_model=96, d_state=4, ssm_ratio=2, dt_rank="auto", # dt init ============== dt_min=0.001, dt_max=0.1, dt_init="random", dt_scale=1.0, dt_init_floor=1e-4, # ====================== **kwargs, ): factory_kwargs = {"device": None, "dtype": None} super().init() self.d_model = d_model self.d_state = math.ceil(self.d_model / 6) if d_state == "auto" else d_state # 20240109 self.expand = ssm_ratio 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# x proj; dt proj ============================ self.x_proj_1 = nn.Linear(self.d_inner, (self.dt_rank + self.d_state * 2), bias=False, **factory_kwargs) self.x_proj_2 = nn.Linear(self.d_inner, (self.dt_rank + self.d_state * 2), bias=False, **factory_kwargs) self.dt_proj_1 = self.dt_init(self.dt_rank, self.d_inner, dt_scale, dt_init, dt_min, dt_max, dt_init_floor, **factory_kwargs) self.dt_proj_2 = self.dt_init(self.dt_rank, self.d_inner, dt_scale, dt_init, dt_min, dt_max, dt_init_floor, **factory_kwargs) # A, D ======================================= self.A_log_1 = self.A_log_init(self.d_state, self.d_inner) # (D, N) self.A_log_2 = self.A_log_init(self.d_state, self.d_inner) # (D) self.D_1 = self.D_init(self.d_inner) # (D) self.D_2 = self.D_init(self.d_inner) # (D) # out norm =================================== self.out_norm_1 = nn.LayerNorm(self.d_inner) self.out_norm_2 = nn.LayerNorm(self.d_inner) @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, **factory_kwargs): dt_proj = nn.Linear(dt_rank, d_inner, bias=True, **factory_kwargs) # 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) else: raise NotImplementedError # 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 return dt_proj @staticmethod def A_log_init(d_state, d_inner, copies=-1, device=None, merge=True): # 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) # Keep A_log in fp32 if copies > 0: A_log = repeat(A_log, "d n -> r d n", r=copies) if merge: A_log = A_log.flatten(0, 1) A_log = nn.Parameter(A_log) A_log._no_weight_decay = True return A_log @staticmethod def D_init(d_inner, copies=-1, device=None, merge=True): # D "skip" parameter D = torch.ones(d_inner, device=device) if copies > 0: D = repeat(D, "n1 -> r n1", r=copies) if merge: D = D.flatten(0, 1) D = nn.Parameter(D) # Keep in fp32 D._no_weight_decay = True return D def forward(self, x_rgb: torch.Tensor, x_e: torch.Tensor): selective_scan = selective_scan_fn_v1 B, L, d = x_rgb.shape x_rgb = x_rgb.permute(0, 2, 1) x_e = x_e.permute(0, 2, 1) x_dbl_rgb = self.x_proj_1(rearrange(x_rgb, "b d l -> (b l) d")) # (bl d) x_dbl_e = self.x_proj_2(rearrange(x_e, "b d l -> (b l) d")) # (bl d) dt_rgb, B_rgb, C_rgb = torch.split(x_dbl_rgb, [self.dt_rank, self.d_state, self.d_state], dim=-1) dt_e, B_e, C_e = torch.split(x_dbl_e, [self.dt_rank, self.d_state, self.d_state], dim=-1) dt_rgb = self.dt_proj_1.weight @ dt_rgb.t() dt_e = self.dt_proj_2.weight @ dt_e.t() dt_rgb = rearrange(dt_rgb, "d (b l) -> b d l", l=L) dt_e = rearrange(dt_e, "d (b l) -> b d l", l=L) A_rgb = -torch.exp(self.A_log_1.float()) # (k * d, d_state) A_e = -torch.exp(self.A_log_2.float()) # (k * d, d_state) B_rgb = rearrange(B_rgb, "(b l) dstate -> b dstate l", l=L).contiguous() B_e = rearrange(B_e, "(b l) dstate -> b dstate l", l=L).contiguous() C_rgb = rearrange(C_rgb, "(b l) dstate -> b dstate l", l=L).contiguous() C_e = rearrange(C_e, "(b l) dstate -> b dstate l", l=L).contiguous() y_rgb = selective_scan( x_rgb, dt_rgb, A_rgb, B_rgb, C_e, self.D_1.float(), delta_bias=self.dt_proj_1.bias.float(), delta_softplus=True, ) y_e = selective_scan( x_e, dt_e, A_e, B_e, C_rgb, self.D_2.float(), delta_bias=self.dt_proj_2.bias.float(), delta_softplus=True, ) # assert out_y.dtype == torch.float y_rgb = rearrange(y_rgb, "b d l -> b l d") y_rgb = self.out_norm_1(y_rgb) y_e = rearrange(y_e, "b d l -> b l d") y_e = self.out_norm_2(y_e) return y_rgb, y_e=====================================================
class CrossMambaFusion_SS2D_SSM(nn.Module): ''' Cross Mamba Attention Fusion Selective Scan 2D Module with SSM ''' def init( self, # basic dims =========== d_model=96, d_state=16, ssm_ratio=2, dt_rank="auto", # dwconv =============== # d_conv=-1, # < 2 means no conv d_conv=3, # < 2 means no conv conv_bias=True, # ====================== dropout=0., bias=False, # dt init ============== dt_min=0.001, dt_max=0.1, dt_init="random", dt_scale=1.0, dt_init_floor=1e-4, # ====================== softmax_version=False, # ====================== **kwargs, ):
factory_kwargs = {"device": None, "dtype": None} super().init() self.softmax_version = softmax_version self.d_model = d_model self.d_state = math.ceil(self.d_model / 6) if d_state == "auto" else d_state # 20240109 self.d_conv = d_conv self.expand = ssm_ratio self.d_inner = int(self.expand * self.d_model) self.dt_rank = math.ceil(self.d_model / 16) if dt_rank == "auto" else dt_rankcodeself.in_proj = nn.Linear(self.d_model, self.d_inner, bias=bias, **factory_kwargs) self.in_proj_modalx = nn.Linear(self.d_model, self.d_inner, bias=bias, **factory_kwargs) # conv ======================================= if self.d_conv > 1: 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.out_proj_rgb = nn.Linear(self.d_inner, self.d_model, bias=bias, **factory_kwargs) self.out_proj_e = nn.Linear(self.d_inner, self.d_model, bias=bias, **factory_kwargs) self.dropout_rgb = nn.Dropout(dropout) if dropout > 0. else nn.Identity() self.dropout_e = nn.Dropout(dropout) if dropout > 0. else nn.Identity() self.CMA_ssm = Cross_Mamba_Attention_SSM( d_model=self.d_model, d_state=self.d_state, ssm_ratio=ssm_ratio, dt_rank=dt_rank, dt_min=dt_min, dt_max=dt_max, dt_init=dt_init, dt_scale=dt_scale, dt_init_floor=dt_init_floor, **kwargs, ) def forward(self, x_rgb: torch.Tensor, x_e: torch.Tensor): x_rgb = self.in_proj(x_rgb) x_e = self.in_proj_modalx(x_e) B, H, W, D = x_rgb.shape if self.d_conv > 1: x_rgb_trans = x_rgb.permute(0, 3, 1, 2).contiguous() x_e_trans = x_e.permute(0, 3, 1, 2).contiguous() x_rgb_conv = self.act(self.conv2d(x_rgb_trans)) # (b, d, h, w) x_e_conv = self.act(self.conv2d(x_e_trans)) # (b, d, h, w) x_rgb_conv = rearrange(x_rgb_conv, "b d h w -> b (h w) d") x_e_conv = rearrange(x_e_conv, "b d h w -> b (h w) d") y_rgb, y_e = self.CMA_ssm(x_rgb_conv, x_e_conv) # to b, d, h, w y_rgb = y_rgb.view(B, H, W, -1) y_e = y_e.view(B, H, W, -1) out_rgb = self.dropout_rgb(self.out_proj_rgb(y_rgb)) out_e = self.dropout_e(self.out_proj_e(y_e)) return out_rgb, out_eclass Permute(nn.Module): def init(self, *args): super().init() self.args = args
codedef forward(self, x: torch.Tensor): return x.permute(*self.args)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
codeLinear = partial(nn.Conv2d, kernel_size=1, padding=0) if channels_first else nn.Linear self.fc1 = Linear(in_features, hidden_features) self.act = act_layer() self.fc2 = 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 xclass VSSBlock(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_rank: Any = "auto", ssm_ratio=2.0, shared_ssm=False, softmax_version=False, use_checkpoint: bool = False, mlp_ratio=4.0, act_layer=nn.GELU, drop: float = 0.0, **kwargs, ): super().init() self.use_checkpoint = use_checkpoint self.norm = norm_layer(hidden_dim) self.op = SS2D( d_model=hidden_dim, dropout=attn_drop_rate, d_state=d_state, ssm_ratio=ssm_ratio, dt_rank=dt_rank, shared_ssm=shared_ssm, softmax_version=softmax_version, **kwargs ) self.drop_path = DropPath(drop_path)
codeself.mlp_branch = mlp_ratio > 0 if self.mlp_branch: self.norm2 = norm_layer(hidden_dim) mlp_hidden_dim = int(hidden_dim * mlp_ratio) self.mlp = Mlp(in_features=hidden_dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop, channels_first=False) def _forward(self, input: torch.Tensor): x = input + self.drop_path(self.op(self.norm(input))) if self.mlp_branch: x = x + self.drop_path(self.mlp(self.norm2(x))) # FFN return x def forward(self, input: torch.Tensor): if self.use_checkpoint: return checkpoint.checkpoint(self._forward, input) else: return self._forward(input)class ChannelAttention(nn.Module): def init(self, num_feat, squeeze_factor=16): super(ChannelAttention, self).init() self.avg_pool = nn.AdaptiveAvgPool2d(1) self.max_pool = nn.AdaptiveMaxPool2d(1) self.fc = nn.Sequential( nn.Conv2d(num_feat, num_feat // squeeze_factor, 1, bias=False), nn.SiLU(inplace=True), nn.Conv2d(num_feat // squeeze_factor, num_feat, 1, bias=False), ) self.sigmoid = nn.Sigmoid()
codedef forward(self, x): avg_out = self.fc(self.avg_pool(x)) max_out = self.fc(self.max_pool(x)) attn = avg_out + max_out return x * self.sigmoid(attn)class ChannelAttentionBlock(nn.Module):
codedef __init__(self, num_feat, compress_ratio=3, squeeze_factor=30): super(ChannelAttentionBlock, self).__init__() self.cab = nn.Sequential( nn.Conv2d(num_feat, num_feat // compress_ratio, 3, 1, 1), nn.GELU(), nn.Conv2d(num_feat // compress_ratio, num_feat, 3, 1, 1), ChannelAttention(num_feat, squeeze_factor) ) def forward(self, x): return self.cab(x)class CVSSDecoderBlock(nn.Module): ''' Channel-Aware VSS ''' 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_rank: Any = "auto", ssm_ratio=2.0, shared_ssm=False, softmax_version=False, use_checkpoint: bool = False, mlp_ratio=4.0, act_layer=nn.GELU, drop: float = 0.0, **kwargs, ): super().init() self.use_checkpoint = use_checkpoint self.norm1 = norm_layer(hidden_dim) self.scale1 = nn.Parameter(torch.ones(hidden_dim)) self.op = SS2D( d_model=hidden_dim, dropout=attn_drop_rate, d_state=d_state, ssm_ratio=ssm_ratio, dt_rank=dt_rank, shared_ssm=shared_ssm, softmax_version=softmax_version, **kwargs ) self.drop_path = DropPath(drop_path) self.conv_blk = ChannelAttentionBlock(hidden_dim) self.norm2 = norm_layer(hidden_dim) self.scale2 = nn.Parameter(torch.ones(hidden_dim))
codedef _forward(self, input: torch.Tensor): x = input*self.scale1 + self.drop_path(self.op(self.norm1(input))) y = self.conv_blk(self.norm2(x).permute(0, 3, 1, 2).contiguous()) + (x*self.scale2).permute(0, 3, 1, 2).contiguous() y = y.permute(0, 2, 3, 1).contiguous() return y def forward(self, input: torch.Tensor): if self.use_checkpoint: return checkpoint.checkpoint(self._forward, input) else: return self._forward(input)class CrossMambaFusionBlock(nn.Module): ''' Cross Mamba Fusion (CroMB) fusion, with 2d SSM ''' 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 = 4, dt_rank: Any = "auto", ssm_ratio=2.0, shared_ssm=False, softmax_version=False, use_checkpoint: bool = False, mlp_ratio=0.0, act_layer=nn.GELU, drop: float = 0.0, **kwargs, ): super().init() self.use_checkpoint = use_checkpoint # self.norm = norm_layer(hidden_dim) self.op = CrossMambaFusion_SS2D_SSM( d_model=hidden_dim, dropout=attn_drop_rate, d_state=d_state, ssm_ratio=ssm_ratio, dt_rank=dt_rank, shared_ssm=shared_ssm, softmax_version=softmax_version, **kwargs ) self.drop_path1 = DropPath(drop_path) self.drop_path2 = DropPath(drop_path)
codeself.mlp_branch = mlp_ratio > 0 if self.mlp_branch: self.norm2 = norm_layer(hidden_dim) mlp_hidden_dim = int(hidden_dim * mlp_ratio) self.mlp = Mlp(in_features=hidden_dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop, channels_first=False) def _forward(self, x_rgb: torch.Tensor, x_e: torch.Tensor): x_rgb_cross, x_e_cross = self.op(x_rgb, x_e) x_rgb = x_rgb + self.drop_path1(x_rgb_cross) x_e = x_e + self.drop_path2(x_e_cross) return x_rgb, x_e def forward(self, x_rgb: torch.Tensor, x_e: torch.Tensor): ''' B C H W, B C H W -> B C H W ''' if self.use_checkpoint: return checkpoint.checkpoint(self._forward, x_rgb, x_e) else: return self._forward(x_rgb, x_e)class ConcatMambaFusionBlock(nn.Module): ''' Concat Mamba (ConMB) fusion, with 2d SSM ''' 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 = 4, dt_rank: Any = "auto", ssm_ratio=2.0, shared_ssm=False, softmax_version=False, use_checkpoint: bool = False, mlp_ratio=0.0, act_layer=nn.GELU, drop: float = 0.0, **kwargs, ): super().init() self.use_checkpoint = use_checkpoint # self.norm = norm_layer(hidden_dim) self.op = ConMB_SS2D( d_model=hidden_dim, dropout=attn_drop_rate, d_state=d_state, ssm_ratio=ssm_ratio, dt_rank=dt_rank, shared_ssm=shared_ssm, softmax_version=softmax_version, **kwargs ) self.drop_path = DropPath(drop_path)
codeself.mlp_branch = mlp_ratio > 0 if self.mlp_branch: self.norm2 = norm_layer(hidden_dim) mlp_hidden_dim = int(hidden_dim * mlp_ratio) self.mlp = Mlp(in_features=hidden_dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop, channels_first=False) def _forward(self, x_rgb: torch.Tensor, x_e: torch.Tensor): x = x_rgb + x_e + self.drop_path(self.op(x_rgb, x_e)) if self.mlp_branch: x = x + self.drop_path(self.mlp(self.norm2(x))) # FFN return x def forward(self, x_rgb: torch.Tensor, x_e: torch.Tensor): ''' B C H W, B C H W -> B C H W ''' if self.use_checkpoint: return checkpoint.checkpoint(self._forward, x_rgb, x_e) else: return self._forward(x_rgb, x_e)class VSSM(nn.Module): def init( self, patch_size=4, in_chans=3, num_classes=1000, depths=[2, 2, 9, 2], dims=[96, 192, 384, 768], # ========================= d_state=16, dt_rank="auto", ssm_ratio=2.0, attn_drop_rate=0., shared_ssm=False, softmax_version=False, # ========================= drop_rate=0., drop_path_rate=0.1, mlp_ratio=4.0, patch_norm=True, norm_layer=nn.LayerNorm, downsample_version: str = "v2", 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 = dimscodeself.patch_embed = nn.Sequential( nn.Conv2d(in_chans, self.embed_dim, kernel_size=patch_size, stride=patch_size, bias=True), Permute(0, 2, 3, 1), (norm_layer(self.embed_dim) if patch_norm else nn.Identity()), ) 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): if downsample_version == "v2": downsample = self._make_downsample( self.dims[i_layer], self.dims[i_layer + 1], norm_layer=norm_layer, ) if (i_layer < self.num_layers - 1) else nn.Identity() else: downsample = PatchMerging2D( self.dims[i_layer], self.dims[i_layer + 1], norm_layer=norm_layer, ) if (i_layer < self.num_layers - 1) else nn.Identity() self.layers.append(self._make_layer( dim = self.dims[i_layer], depth = depths[i_layer], drop_path = dpr[sum(depths[:i_layer]):sum(depths[:i_layer + 1])], use_checkpoint=use_checkpoint, norm_layer=norm_layer, downsample=downsample, d_state=d_state, dt_rank=dt_rank, ssm_ratio=ssm_ratio, attn_drop_rate=attn_drop_rate, shared_ssm=shared_ssm, softmax_version=softmax_version, mlp_ratio=mlp_ratio, drop_rate=drop_rate, )) self.classifier = nn.Sequential(OrderedDict( norm=norm_layer(self.num_features), # B,H,W,C permute=Permute(0, 3, 1, 2), avgpool=nn.AdaptiveAvgPool2d(1), flatten=nn.Flatten(1), head=nn.Linear(self.num_features, num_classes), )) 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) @staticmethod def _make_downsample(dim=96, out_dim=192, norm_layer=nn.LayerNorm): return nn.Sequential( Permute(0, 3, 1, 2), nn.Conv2d(dim, out_dim, kernel_size=2, stride=2), Permute(0, 2, 3, 1), norm_layer(out_dim), ) @staticmethod def _make_layer( dim=96, depth=2, drop_path=[0.1, 0.1], use_checkpoint=False, norm_layer=nn.LayerNorm, downsample=nn.Identity(), # =========================== d_state=16, dt_rank="auto", ssm_ratio=2.0, attn_drop_rate=0.0, shared_ssm=False, softmax_version=False, # =========================== mlp_ratio=4.0, drop_rate=0.0, **kwargs, ): assert depth == len(drop_path) blocks = [] for d in range(depth): blocks.append(VSSBlock( hidden_dim=dim, drop_path=drop_path[d], norm_layer=norm_layer, attn_drop_rate=attn_drop_rate, d_state=d_state, dt_rank=dt_rank, ssm_ratio=ssm_ratio, shared_ssm=shared_ssm, softmax_version=softmax_version, use_checkpoint=use_checkpoint, mlp_ratio=mlp_ratio, act_layer=nn.GELU, drop=drop_rate, **kwargs, )) return nn.Sequential(OrderedDict( blocks=nn.Sequential(*blocks,), downsample=downsample, )) def forward(self, x: torch.Tensor): x = self.patch_embed(x) for layer in self.layers: x = layer(x) x = self.classifier(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.CrossScan": None, "prim::PythonOp.CrossMerge": None, "prim::PythonOp.SelectiveScan": selective_scan_flop_jit, "prim::PythonOp.SelectiveScanFn": selective_scan_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())}" # used to load ckpt from previous training code def _load_from_state_dict(self, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs): def check_name(src, state_dict: dict = state_dict, strict=False): if strict: if prefix + src in list(state_dict.keys()): return True else: key = prefix + src for k in list(state_dict.keys()): if k.startswith(key): return True return False def change_name(src, dst, state_dict: dict = state_dict, strict=False): if strict: if prefix + src in list(state_dict.keys()): state_dict[prefix + dst] = state_dict[prefix + src] state_dict.pop(prefix + src) else: key = prefix + src for k in list(state_dict.keys()): if k.startswith(key): new_k = prefix + dst + k[len(key):] state_dict[new_k] = state_dict[k] state_dict.pop(k) change_name("patch_embed.proj", "patch_embed.0") change_name("patch_embed.norm", "patch_embed.2") for i in range(100): for j in range(100): change_name(f"layers.{i}.blocks.{j}.ln_1", f"layers.{i}.blocks.{j}.norm") change_name(f"layers.{i}.blocks.{j}.self_attention", f"layers.{i}.blocks.{j}.op") change_name("norm", "classifier.norm") change_name("head", "classifier.head") # print('after:', state_dict.keys()) return super()._load_from_state_dict(state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs)compatible with openmmlab
class Backbone_VSSM(VSSM): def init(self, patch_size=4, in_chans=3, num_classes=1000, depths=[2, 2, 9, 2], dims=[96, 192, 384, 768], d_state=16, ssm_ratio=2.0, attn_drop_rate=0., drop_rate=0., drop_path_rate=0.1, mlp_ratio=4.0, patch_norm=True, norm_layer=nn.LayerNorm, downsample_version: str = "v2", use_checkpoint=False, out_indices=(0, 1, 2, 3), pretrained=None, **kwargs, ): super().init(patch_size=patch_size, in_chans=in_chans, num_classes=num_classes, depths=depths, dims=dims, d_state=d_state, ssm_ratio=ssm_ratio, attn_drop_rate=attn_drop_rate, drop_rate=drop_rate, drop_path_rate=drop_path_rate, mlp_ratio=mlp_ratio, patch_norm=patch_norm, norm_layer=norm_layer, downsample_version=downsample_version, use_checkpoint=use_checkpoint, **kwargs)
codeself.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) del self.classifier self.load_pretrained(pretrained) 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}") # print(f"ckpt keys: {_ckpt['model'].keys()}") incompatibleKeys = self.load_state_dict(_ckpt[key], strict=False) print('incompatible:', incompatibleKeys) except Exception as e: print(f"Failed loading checkpoint form {ckpt}: {e}") def forward(self, x): def layer_forward(l, x): x = l.blocks(x) y = l.downsample(x) return x, y x = self.patch_embed(x) outs = [] for i, layer in enumerate(self.layers): o, x = layer_forward(layer, x) # (B, H, W, C) if i in self.out_indices: norm_layer = getattr(self, f'outnorm{i}') out = norm_layer(o) out = out.permute(0, 3, 1, 2).contiguous() outs.append(out) if len(self.out_indices) == 0: return x return outs中的CrossMambaFusionBlock - Assistant
The given code defines a variety of classes designed for building neural network models, particularly for computer vision tasks. Here, I'll focus on the
CrossMambaFusionBlockclass and other components associated with it.CrossMambaFusionBlock
The
CrossMambaFusionBlockclass is a neural network block that incorporates selective scanning mechanisms (SSM) for efficient computation and fusion of multi-modal inputs. It includes several key components:-
Selective Scan 2D (SS2D): Utilizes selective scan functions to process 2D inputs with specific warp patterns, enhancing spatial relationships within the data.
-
Cross Mamba Fusion:
- It facilitates multi-modal information fusion through selective cross-attention mechanisms.
- The block primarily considers two inputs, likely from different modalities or channels, and fuses them using cross-attention mechanisms before further processing.
-
Drop Path: A regularization technique to improve model accuracy by randomly dropping a subset of network paths during training.
-
MLP Layers: Provide additional flexibility and non-linearity to the model through fully-connected layers, enhancing its representational power.
Other Components
-
VSSM & Backbone_VSSM:
VSSMis a model class that leverages SS2D blocks for efficient processing of visual data, organizing them into layers.Backbone_VSSMis a subclass ofVSSMdesigned for compatibility with certain deep learning frameworks, facilitating pretrained model loading and feature extraction.
-
CrossMambaFusion_SS2D_SSM:
- This variant of SS2D uses a selective scanning approach to combine information from two streams (
x_rgbandx_e) by utilizing cross-attention to focus on important features. - It incorporates cross-modal attention SSM (CMSSM) for efficient interaction between modalities, ensuring robust information fusion.
- This variant of SS2D uses a selective scanning approach to combine information from two streams (
-
SS2D:
- Implements selective 2D convolutional layers that adaptively process patches of the input data for capturing spatial dependencies.
- It involves a novel mechanism, boosting the expressiveness of the model with optimized computational efficiency.
-
Supporting Layers:
- Mlp, ChannelAttention, ChannelAttentionBlock, Permute, etc.: These are helper classes that provide basic functionalities like multi-layer perceptrons, channel-wise attention, and tensor permutation to adjust data between different modules in the network.
Together, these blocks and classes enable the construction of a sophisticated neural network architecture designed to process high-dimensional visual data, particularly leveraging the strengths of multi-modal fusion through selective scanning techniques that enhance spatial and channel-wise dependencies while maintaining computational efficiency.
-
- User
中文回答
- Assistant
给定的代码定义了一系列用于构建神经网络模型的类,特别是用于计算机视觉任务。在这里,我将重点讲解其中的
CrossMambaFusionBlock类及其相关组件。CrossMambaFusionBlock
CrossMambaFusionBlock类是一个神经网络模块,结合了选择性扫描(SSM)技术,用于高效计算和多模态输入融合。它包含以下关键组件:-
选择性扫描2D (SS2D): 利用选择性扫描功能处理二维输入,通过特定的扫描模式增强数据中的空间关系。
-
Cross Mamba Fusion(交叉曼巴融合):
- 促进多模态信息融合,通过选择性交叉注意机制融合来自不同模态或通道的输入。
- 该模块主要考虑两个输入,可能来自不同的模态或通道,并通过交叉注意机制进行融合后进一步处理。
-
Drop Path(路径丢弃): 一种正则化技术,通过在训练期间随机丢弃网络的一部分路径来提高模型的准确性。
-
MLP层(多层感知器): 通过全连接层提供额外的灵活性和非线性能力,提升模型的表示能力。
其他组件
-
VSSM 和 Backbone_VSSM:
VSSM是一个利用SS2D模块高效处理视觉数据的模型类,将这些模块组织成网络层。Backbone_VSSM是VSSM的子类,设计用于与某些深度学习框架的兼容性,支持预训练模型加载和特征提取。
-
CrossMambaFusion_SS2D_SSM:
- 该SS2D的变体利用选择性扫描方法结合来自两个流(
x_rgb和x_e)的信息,使用交叉注意机制聚焦于重要特征。 - 它整合了跨模态注意SSM(CMSSM),确保多模态信息的高效交互和融合。
- 该SS2D的变体利用选择性扫描方法结合来自两个流(
-
SS2D:
- 实现选择性2D卷积层,自适应地处理输入数据的各个补丁,以捕获空间依赖关系。
- 它采用一种新的机制,提升了模型的表示能力,同时优化计算效率。
-
辅助层:
- Mlp、ChannelAttention、ChannelAttentionBlock、Permute 等: 这些是辅助类,提供基本功能,如多层感知器、通道注意和张量置换,用于在网络不同模块之间调整数据。
综合来看,这些模块和类支持构建一个复杂的神经网络架构,专为处理高维视觉数据而设计,特别是通过选择性扫描技术增强空间和通道依赖的多模态融合,同时保持计算的高效性。
-
- User
再分析: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)
codeassert 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.weightclass 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)
codeassert 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.biasclass 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)
codedef 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") # 使用v3版本,会使用额外的输入extra_emb进行特殊处理 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 - Assistant
The given code is a part of a PyTorch module designed for neural network operations, particularly focusing on a module named
CrossMambathat makes use of another module calledMamba. Here's a breakdown of the components and their functionalities:Utility Functions
to_3d(x)andto_4d(x, h, w):- These functions utilize the
einopslibrary to reshape tensors. to_3d: Converts a 4D tensor(b, c, h, w)to a 3D tensor(b, h*w, c).to_4d: Converts a 3D tensor(b, h*w, c)back to a 4D tensor(b, c, h, w).
- These functions utilize the
Normalization Layers
Normalization layers standardize the input to have a mean of zero and a variance of one, which helps stabilize learning.
-
BiasFree_LayerNorm:- A type of layer normalization without a bias parameter.
- It learns scaling factors (
weight) to normalize the data, focusing on the variance.
-
WithBias_LayerNorm:- Similar to
BiasFree_LayerNormbut includes a bias parameter (bias). - Normalizes not only based on variance but also adjusts according to the mean.
- Similar to
-
LayerNorm:- A wrapper around the two types of layer normalization (
BiasFree_LayerNormandWithBias_LayerNorm). - Determines which type to use based on the initialization parameter
LayerNorm_type.
- A wrapper around the two types of layer normalization (
Main Component: CrossMamba
-
CrossMamba:- A neural network module designed to integrate and process features from two modalities or sources,
m1andm2. - Components:
cross_mamba: An instance of theMambaclass, which is not fully detailed here. The version "v3" is specifically mentioned, indicating it has certain features, such as processing an extra embedding (extra_emb).norm1andnorm2: Instances ofLayerNorm, applying normalization with bias to the input data.dwconv: A depth-wise separable convolution, which applies a convolution over each channel independently. This is beneficial for capturing spatial information with reduced computational cost.
- A neural network module designed to integrate and process features from two modalities or sources,
-
forwardMethod:- This method outlines how the module processes a batch of inputs step-by-step.
m1_resiis an intermediate result combiningm1andm1_resi.- The
global_ffeature is computed by passingm1andm2(asextra_emb) through thecross_mambamodule. - The purpose is likely to fuse features from
m1and contextual information fromm2, facilitating more informed processing.
Overall Summary
- The code focuses on efficient data modulation and fusion within neural networks, particularly emphasizing the integration of multi-modal information through the
CrossMambaclass. - The use of layer normalization and depth-wise convolutional layers suggests a design emphasizing stable and computationally efficient operations.
- The modular design allows for flexible integration into larger network architectures, facilitating tasks that require the fusion of information from multiple sources or modalities.
- User
中文回答
- Assistant
该代码是一个用于深度学习的PyTorch模块,主要包含
CrossMamba模块,该模块利用另一个称为Mamba的模块。以下是各部分的功能介绍:实用函数
to_3d(x)和to_4d(x, h, w):- 这些函数使用
einops库来重塑张量。 to_3d:将四维张量(b, c, h, w)转换为三维张量(b, h*w, c)。to_4d:将三维张量(b, h*w, c)转回四维张量(b, c, h, w)。
- 这些函数使用
归一化层
归一化层用于标准化输入数据达到零均值和单位方差,帮助加速模型训练和提高稳定性。
-
BiasFree_LayerNorm:- 一种不含偏置参数的Layer Normalization(层归一化)。
- 通过学习尺度参数 (
weight) 来实现数据标准化,主要处理方差部分。
-
WithBias_LayerNorm:- 与
BiasFree_LayerNorm类似,但包含一个偏置参数 (bias)。 - 进行标准化处理时不仅考虑方差,还会根据均值进行调整。
- 与
-
LayerNorm:- 包装了两种类型的层归一化(
BiasFree_LayerNorm和WithBias_LayerNorm)。 - 根据初始化参数
LayerNorm_type确定使用哪种类型的归一化。
- 包装了两种类型的层归一化(
主要组件:CrossMamba
-
CrossMamba:- 该模块用于整合和处理来自两个模态或来源(
m1和m2)的特征。 - 组件:
cross_mamba:Mamba类的实例,具体行为由"v3"版本决定,表示它可以处理额外的embedding(extra_emb)。norm1和norm2:LayerNorm的实例,对输入数据应用带偏置的归一化。dwconv: 深度可分离卷积(depth-wise convolution),对每个通道独立进行卷积,能够有效捕获空间信息且减少计算开销。
- 该模块用于整合和处理来自两个模态或来源(
-
forward方法:- 定义模块如何逐步处理输入数据。
m1_resi通过组合m1和m1_resi得到。global_f特征是通过将m1和m2(作为extra_emb)传入cross_mamba模块计算获得。- 主要目的是将
m1中的特征与m2的上下文信息进行融合,从而更为全面地处理信息。
总结
- 该代码重点在于神经网络中高效的数据调节和融合,特别是通过
CrossMamba类实现多模态信息的整合。 - 使用层归一化和深度卷积层表明设计注重操作的稳定性和计算效率。
- 模块化的设计便于将其集成到更大型的网络架构中,适用于需要从多源或多模态中融合信息的任务。
- User
import math import torch import numpy as np import torch.nn as nn from einops import rearrange import torch.nn.functional as F from mamba_ssm.modules.mamba_simple import Mamba from mamba_ssm.ops.triton.layernorm import RMSNorm, layer_norm_fn, rms_norm_fn
class SingleMambaBlock(nn.Module): def init(self, dim, H, W): super().init() self.norm = nn.LayerNorm(dim) # self.norm1 = nn.LayerNorm(dim) self.block = Mamba(dim, expand=1, d_state=8, bimamba_type='v6', if_devide_out=True, use_norm=True, input_h=H, input_w=W)
codedef forward(self, input): # input: (B, N, C) skip = input input = self.norm(input) output = self.block(input) # output = self.norm1(output) return output + skipclass CrossMambaBlock(nn.Module): def init(self, dim, H, W): super().init() self.norm0 = nn.LayerNorm(dim) self.norm1 = nn.LayerNorm(dim) # self.norm2 = nn.LayerNorm(dim) self.block = Mamba(dim, expand=1, d_state=8, bimamba_type='v7', if_devide_out=True, use_norm=True, input_h=H, input_w=W)
codedef forward(self, input0, input1): # input0: (B, N, C) | input1: (B, N, C) skip = input0 input0 = self.norm0(input0) input1 = self.norm1(input1) output = self.block(input0, extra_emb=input1) # output = self.norm2(output) return output + skipclass FusionMamba(nn.Module): def init(self, dim, H, W, depth=1): super().init() self.spa_mamba_layers = nn.ModuleList([]) self.spe_mamba_layers = nn.ModuleList([]) for _ in range(depth): self.spa_mamba_layers.append(SingleMambaBlock(dim, H, W)) self.spe_mamba_layers.append(SingleMambaBlock(dim, H, W)) self.spa_cross_mamba = CrossMambaBlock(dim, H, W) self.spe_cross_mamba = CrossMambaBlock(dim, H, W) self.out_proj = nn.Linear(dim, dim)
codedef forward(self, pan, ms): b, c, h, w = pan.shape pan = rearrange(pan, 'b c h w -> b (h w) c', h=h, w=w) ms = rearrange(ms, 'b c h w -> b (h w) c', h=h, w=w) for spa_layer, spe_layer in zip(self.spa_mamba_layers, self.spe_mamba_layers): pan = spa_layer(pan) ms = spe_layer(ms) spa_fusion = self.spa_cross_mamba(pan, ms) spe_fusion = self.spe_cross_mamba(ms, pan) fusion = self.out_proj((spa_fusion + spe_fusion) / 2) pan = rearrange(pan, 'b (h w) c -> b c h w', h=h, w=w) ms = rearrange(ms, 'b (h w) c -> b c h w', h=h, w=w) output = rearrange(fusion, 'b (h w) c -> b c h w', h=h, w=w) return pan, ms + output中的Fusionmamba模块是如何执行的?(中文回答) - Assistant
FusionMamba模块主要用于融合两个输入特征图:全色图 (pan) 和多光谱图 (ms)。这个模块将这两个输入分别进行处理,然后通过交叉注意机制进行特征融合,最终输出处理后的特征。以下是FusionMamba模块的执行过程的详细说明:1. 输入变换:
- 模块接收两个维度为
(B, C, H, W)的输入pan和ms,其中B是批量大小,C是通道数,H和W是特征图的高度和宽度。 - 使用
rearrange函数将输入pan和ms从(B, C, H, W)转换为(B, H*W, C),这一步是为了方便在Mamba模块中执行线性层操作。
2. 单模态处理(SingleMambaBlock):
spa_mamba_layers和spe_mamba_layers分别是多层的SingleMambaBlock,用于对pan和ms输入进行逐层处理。- 每一层中:
- 先对输入进行归一化(
LayerNorm)。 - 然后使用
Mamba模块进行处理。 - 确保输入的残差连接,输出结果加上输入作为输出。
- 先对输入进行归一化(
3. 交叉模态融合(CrossMambaBlock):
spa_cross_mamba和spe_cross_mamba分别是用于融合pan和ms特征的交叉融合块。spa_cross_mamba(pan, ms):- 将
pan作为主要输入,ms作为额外的嵌入输入到Mamba模块中,进行特征的交叉融合。
- 将
spe_cross_mamba(ms, pan):- 将
ms作为主要输入,pan作为额外的嵌入输入到Mamba模块中,进行特征的交叉融合。
- 将
- 这两步的目的是使两种模态的信息相互交融,提取出更丰富的特征。
4. 输出变换和融合:
- 通过线性层
out_proj对经过交叉融合的spa_fusion和spe_fusion进行进一步处理,并对两者取均值,得到融合结果fusion。 - 将处理后的
pan和ms重新变换回原来的形状(B, C, H, W)。 - 最终输出为处理后的
pan和ms,其中ms与融合后的结果相加作为最终的多光谱输出。
总结:
FusionMamba模块通过一系列的处理和融合操作,实现了对全色图和多光谱图的特征增强,其中单模态处理用于提升各自模态的特征表达能力,而交叉模态融合通过Mamba模块更好地结合了两个模态的信息。 - 模块接收两个维度为
- User
但是那么上文中的FusionMamba和CrossMamba模块有何区别?
- Assistant
FusionMamba和CrossMamba是两个不同的模块,尽管它们在功能上都涉及到多模态信息的处理和融合,但它们的设计和实现上存在一些区别:FusionMamba
-
结构复杂度:
FusionMamba是一个更复杂的模块,它集成了多个SingleMambaBlock和CrossMambaBlock层。这种设计旨在通过多个层的叠加,提高对输入特征的表达和融合能力。- 它包含两条单独的处理路径,一条用于处理全色图 (
pan),一条用于处理多光谱图 (ms),这些路径中的每一个都独立通过一系列的SingleMambaBlock层进行处理。
-
处理流程:
- 每个输入特征图首先通过一系列
SingleMambaBlock进行预处理,以强化单模态特征。 - 然后使用两个
CrossMambaBlock分别进行交叉模式的融合。 FusionMamba最终通过对交叉融合后的结果进行投影和叠加,输出处理后的特征。
- 每个输入特征图首先通过一系列
-
目标应用场景:
- 设计上更适用于复杂的多模态输入处理需求,例如在遥感图像分析中同时融合全色图和多光谱图来增强图像分辨率或细节。
CrossMamba
-
模块简单性:
CrossMamba是一个相对简单的模块,专注于利用Mamba模块的交叉注意机制进行特征融合。- 它主要功能是从两个输入中提取特征并进行跨模态融合。
-
处理流程:
- 输入经过
LayerNorm进行标准化处理。 - 使用
Mamba模块进行融合,其中一个输入作为主要输入传入,另一个输入作为额外的嵌入向量 (extra_emb)。 - 输出为融合后的特征,并加上主要输入的残差连接。
- 输入经过
-
目标应用场景:
- 更适合于简单的特征融合任务,适用场景包括需要快速进行两个特征集间的交互或融合的情况。
总结
FusionMamba是一个较为复杂的综合模块,包含多个层级的操作,适合于需要较强表达能力和信息融合深度的任务。而CrossMamba则是一个相对简单的单一模块,专注于实现基础的跨模态特征融合。因此,FusionMamba可以看作是一个通过多个CrossMamba和其他处理块组合而成的模块,提供更高级别的处理和融合能力。 -
- User
当前的两个特征维度都是(2,320,768),那么如何使用上述两个模块?
- Assistant
给定两个特征表示,其尺寸均为
(2, 320, 768),可以将它们视为两个批次的数据,每个批次有320个特征,每个特征维度为768。这种情况下,FusionMamba和CrossMamba都可以用于处理这些特征以进行信息融合。具体使用方式如下:使用 CrossMamba 模块
CrossMamba模块设计用于处理两个输入并实现它们的融合。其使用方式如下:-
实例化 CrossMamba 模块:
pythondim = 768 H = 20 # 假设H * W = 320,选择 H 和 W 可以是任意乘积为320的数 W = 16 cross_mamba = CrossMamba(dim, H, W) -
前向计算:
假设你有两个输入张量
input0和input1,它们的尺寸均为(2, 320, 768),你可以通过以下方式进行特征融合:pythonoutput = cross_mamba(input0, input1)
使用 FusionMamba 模块
FusionMamba模块提供了更复杂的特征处理及融合功能,并且处理过程中包含多个层和交叉融合步骤:-
实例化 FusionMamba 模块:
pythondim = 768 H = 20 # 同样假设H * W = 320 W = 16 depth = 2 # 定义需要的深度 fusion_mamba = FusionMamba(dim, H, W, depth) -
前向计算:
对两个输入
pan和ms,均为(2, 320, 768),进行处理:pythonpan_output, ms_output = fusion_mamba(pan, ms)使用
FusionMamba时,需要分别提供两个输入,然后经过一系列的SingleMambaBlock和CrossMambaBlock层进行处理和融合。
常见注意事项
- H 和 W 选择: 在上述示例中,
H和W是偶然选择的。选择时满足H * W = 320即可。 - 输入数据格式: 确保输入数据的形状能符合模块内部所需的转换格式,比如使用
rearrange格式进行适当的维度转换。 - 深度参数(depth):
FusionMamba中的depth参数指定了SingleMambaBlock的堆叠层数,调整它可改变网络的复杂程度。
若需要更为具体的代码实现或调试设置,需根据自己的应用场景和性能要求进行适当调整。
-
- User
那么Cross_mamba是否可以进一步优化?以实现特征的深度融合?
- Assistant
CrossMamba模块通过Mamba模块的交叉注意机制在两个输入间实现基本的特征融合。要实现更深层次的特征融合,可以考虑以下优化和扩展方案:1. 增加深度和层数
- 堆叠更多层次: 在
CrossMamba模块中,增加多个层次意味着引入更多的CrossMambaBlock层,通过累积多个融合步骤实现更深层次的特征交互。 - 引入Skip Connections: 使用残差连接可以保持梯度流,避免梯度消失问题,同时实现信息的直接传递。
2. 引入更多的注意力机制
- 多头注意力机制(Multi-head Attention): 可以将特征分成多个子空间,每个子空间进行独立的注意力计算,再将结果拼接,增强模型捕捉不同特征模式的能力。
- 自注意力与交叉注意结合: 首先对单个模态进行自注意力操作以增强自身特征,再在两个模态之间执行交叉注意操作。
3. 采用增强的特征表示
- 特征变换: 在进入
Mamba模块之前可以采用非线性变换(例如,通过卷积层或MLP层)对输入特征进行增强和变换。 - 融合位置编码: 使用位置编码以捕获位置信息,增强特征的空间上下文表达。
4. 改善归一化和正则化技巧
- 多形式的归一化: 考虑在
LayerNorm的基础上,尝试使用其他形式的归一化,例如Batch Normalization或Group Normalization,或混合使用。 - 执行正则化: 使用Dropout在
Mamba模块中可以有助于减轻过拟合风险,提供更好的泛化性能。
5. 模块并行与交互
- 并行模块处理: 除顺序堆叠外,可以构建并行的融合路径,采用不同的融合策略后再进行聚合。
- 交互增强模块: 在
CrossMambaBlock中增添其他增强模块(例如CNN模块、MLP),以协助从不同视角进行特征交互和融合。
总结
通过结构化的模块设计与多种机制的引入,可以显著提升
CrossMamba模块的特征融合性能。然而,深度融合通常带来计算复杂度的增加,需要在精度和效率之间进行权衡,以满足具体应用场景的要求。在实践中,可通过实验比较不同配置下的性能以找到最佳组合。 - 堆叠更多层次: 在
- User
那么首先给出 方案1的代码
- Assistant
方案1的建议是通过增加
CrossMamba模块的层数来实现更深层次的特征融合。我们可以通过多次堆叠CrossMambaBlock模块来达到这一目标。以下是一个可能的实现代码示例:pythonimport torch import torch.nn as nn from einops import rearrange from mamba_ssm.modules.mamba_simple import Mamba class CrossMambaBlock(nn.Module): def __init__(self, dim, H, W): super(CrossMambaBlock, self).__init__() self.norm0 = nn.LayerNorm(dim) self.norm1 = nn.LayerNorm(dim) self.block = Mamba(dim, expand=1, d_state=8, bimamba_type='v7', if_devide_out=True, use_norm=True, input_h=H, input_w=W) def forward(self, input0, input1): # input0: (B, N, C) | input1: (B, N, C) skip = input0 input0 = self.norm0(input0) input1 = self.norm1(input1) output = self.block(input0, extra_emb=input1) return output + skip class DeepCrossMamba(nn.Module): def __init__(self, dim, H, W, num_layers=3): super(DeepCrossMamba, self).__init__() self.layers = nn.ModuleList([CrossMambaBlock(dim, H, W) for _ in range(num_layers)]) def forward(self, input0, input1): # input0: (B, N, C) | input1: (B, N, C) for layer in self.layers: input0 = layer(input0, input1) return input0 # 示例使用 B, C, H, W = 2, 768, 20, 16 # 假设 pan 和 ms 特征维度 pan = torch.randn(B, H * W, C) ms = torch.randn(B, H * W, C) deep_cross_mamba = DeepCrossMamba(dim=C, H=H, W=W, num_layers=3) output = deep_cross_mamba(pan, ms) print(output.shape)代码说明:
- CrossMambaBlock: 每个
CrossMambaBlock模块实现了一次特征融合,包含特征归一化和通过Mamba模块的交叉融合。 - DeepCrossMamba: 通过
nn.ModuleList来创建多个CrossMambaBlock的实例,这意味着可以堆叠指定数量的层(由num_layers控制)。 - 前向传播: 在前向传播中,依次通过每个
CrossMambaBlock将特征一步步融合。
通过这种方式,可以根据需要灵活地增加特征融合的层数,实现更深层次的特征交互和处理。这种设计同时保持模块化和扩展性,可以适应不同复杂程度的任务要求。
- CrossMambaBlock: 每个
- User
直接在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)
codeassert 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.weightclass 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)
codeassert 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.biasclass 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)
codedef 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") # 使用v3版本,会使用额外的输入extra_emb进行特殊处理 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上改 - Assistant
为了扩展
CrossMamba模块以实现方案1所述的深度融合,我们可以在CrossMamba模块中增加额外的堆叠层次。即,在CrossMamba类中,增加一个ModuleList来存储多个CrossMamba块,实现特征的多层处理与融合。以下是修改后的代码示例:pythonimport torch import torch.nn as nn from einops import rearrange from mamba_ssm.modules.mamba_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) # 改进后的 CrossMamba 实现方案1 class CrossMamba(nn.Module): def __init__(self, dim, num_layers=3): super(CrossMamba, self).__init__() self.normalizations = nn.ModuleList([LayerNorm(dim, 'with_bias') for _ in range(num_layers * 2)]) self.blocks = nn.ModuleList([Mamba(dim, bimamba_type="v3") for _ in range(num_layers)]) self.dwconv = nn.Conv2d(dim, dim, kernel_size=3, padding=1, groups=dim) self.num_layers = num_layers def forward(self, m1, m1_resi, m2): for i in range(self.num_layers): # 进行归一化 m1 = self.normalizations[2 * i](m1) m2 = self.normalizations[2 * i + 1](m2) # 进行特征融合 m1_resi = m1 + m1_resi m1_resi = self.blocks[i](m1_resi, extra_emb=m2) + m1_resi global_f = m1_resi return global_f # 模拟的使用 dim = 768 B, C, H, W = 2, 320, 768, 768 m1 = torch.randn(B, C, H, W) m1_resi = torch.randn(B, C, H, W) m2 = torch.randn(B, C, H, W) cross_mamba = CrossMamba(dim) output = cross_mamba(m1, m1_resi, m2) print("输出尺寸:", output.shape)说明:
- Layer Stack: 在
CrossMamba中,我们使用nn.ModuleList来创建多个LayerNorm和Mamba模块的实例。在每个堆叠层中,输入经过规一化处理,然后通过Mamba模块融合与extra_emb的特征。 - 多次融合: 通过多层的堆叠,我们让每个特征都多次参与到融合与交互中,进而实现特征的深度融合。
- 灵活性: 通过
num_layers参数控制模型的深度,可以很容易扩展模块以适应不同任务的复杂性要求。
- Layer Stack: 在
- User
此处堆叠了几层?
- Assistant
在上述代码中的
CrossMamba类中,特征融合的堆叠层数由num_layers参数控制。在代码示例中,num_layers的初始化值是 3,这意味着堆叠了 3 层特征融合模块。每一层包括:- 两个
LayerNorm(用于规范化m1和m2)。 - 一次
Mamba模块的调用(用于交叉融合m1_resi和m2的特征)。
因此,当
num_layers=3时,意味着在CrossMamba中进行了 3 次重复的归一化和特征融合计算。这个设计允许我们通过改变num_layers的值来控制特征融合过程的深度。这种方式对处理复杂的多模态数据非常有用,因为更多的层数可以提供更复杂的融合和交互能力,从而提升模型的表现力。 - 两个
- User
那么基于class CrossMamba(nn.Module): def init(self, dim): super(CrossMamba, self).init() self.cross_mamba = Mamba(dim,bimamba_type="v3") # 使用v3版本,会使用额外的输入extra_emb进行特殊处理 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,给出上文中方案5的代码 - Assistant
方案5中建议的优化涉及模块并行与交互,以增强特征融合效果。为此,我们可以在
CrossMamba模块中引入多个并行分支,每个分支处理输入特征的不同方面,最后将结果进行聚合。这可以通过创建多个并行Mamba模块以及其他辅助模块(如CNN模块或MLP模块)来实现。以下是一个实现方案的代码示例:pythonimport torch import torch.nn as nn from einops import rearrange from mamba_ssm.modules.mamba_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,) self.weight = nn.Parameter(torch.ones(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,) self.weight = nn.Parameter(torch.ones(normalized_shape)) self.bias = nn.Parameter(torch.zeros(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) # CrossMamba with Parallel and Interacting Modules class CrossMamba(nn.Module): def __init__(self, dim): super(CrossMamba, self).__init__() # Parallel Mamba branches self.cross_mamba1 = Mamba(dim, bimamba_type="v3") self.cross_mamba2 = Mamba(dim, bimamba_type="v3") # Normalization layers self.norm1 = LayerNorm(dim, 'with_bias') self.norm2 = LayerNorm(dim, 'with_bias') # Depthwise convolution for additional spatial interaction self.dwconv = nn.Conv2d(dim, dim, kernel_size=3, padding=1, groups=dim) def forward(self, m1, m1_resi, m2): # Normalize inputs m1 = self.norm1(m1) m2 = self.norm2(m2) # Parallel feature fusion m1_resi = m1 + m1_resi fusion1 = self.cross_mamba1(m1_resi, extra_emb=m2) fusion2 = self.cross_mamba2(m2, extra_emb=m1_resi) # Alternate processing # Aggregating results from parallel branches combined = (fusion1 + fusion2) / 2 # Additional spatial interaction through depthwise convolution combined_4d = to_4d(combined, m1_resi.shape[-2], m1_resi.shape[-1]) interaction = self.dwconv(combined_4d) # Returning the output return interaction + combined_4d # Example usage dim = 768 B, C, H, W = 2, 320, 768, 768 m1 = torch.randn(B, C, H, W) m1_resi = torch.randn(B, C, H, W) m2 = torch.randn(B, C, H, W) cross_mamba = CrossMamba(dim) output = cross_mamba(m1, m1_resi, m2) print("输出尺寸:", output.shape)方案5 代码说明:
-
Parallel Mamba branches: 我们在
CrossMamba中引入了两个并行的Mamba模块,使得不同路径上可以独立处理特征,并以不同的方式进行交叉模态融合。 -
Layer Normalization: 使用
LayerNorm对每个输入进行标准化,有助于稳定训练过程。 -
Depthwise Convolution: 通过深度卷积操作提供额外的空间交互能力,对融合后的特征进行进一步处理。这能捕获更多局部空间上下文信息。
-
Output Fusion: 通过平均融合来自不同路径的特征结果,确保特征经过丰富的交互后得到增强。
这种并行处理和交互增强的方法,实际上更能发挥两个输入特征不同视角的作用,通过叠加多个特征融合策略来实现更为深层次的特征融合。
-
- User
当前模块: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)
codeassert 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.weightclass 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)
codeassert 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.biasclass 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)
codedef 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") # 使用v3版本,会使用额外的输入extra_emb进行特殊处理 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,调用crossmamba时,输入维度(B,N,L)输出维度也是(B,N,L)。那么现在修改crossmamba模块,使其实现两次交互融合,但是在此过程中,不能改变shape。 - Assistant
为了实现
CrossMamba模块中两次交互融合,并保持输入输出的形状不变,您可以通过多次调用Mamba模块,进行特征交互融合而不改变形状。以下是修改后的代码:pythonimport torch import torch.nn as nn from einops import rearrange from mamba_ssm.modules.mamba_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,) self.weight = nn.Parameter(torch.ones(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,) self.weight = nn.Parameter(torch.ones(normalized_shape)) self.bias = nn.Parameter(torch.zeros(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) class CrossMamba(nn.Module): def __init__(self, dim): super(CrossMamba, self).__init__() self.cross_mamba1 = Mamba(dim, bimamba_type="v3") # 第一次交互 self.cross_mamba2 = Mamba(dim, bimamba_type="v3") # 第二次交互 self.norm1 = LayerNorm(dim, 'with_bias') self.norm2 = LayerNorm(dim, 'with_bias') def forward(self, m1, m1_resi, m2): # 规一化 m1 = self.norm1(m1) m2 = self.norm2(m2) # 第一次交互融合 fusion1 = self.cross_mamba1(m1 + m1_resi, extra_emb=m2) # 第二次交互融合,不改变输入输出形状 global_f = self.cross_mamba2(fusion1, extra_emb=m2) return global_f # 测试 dim = 768 B, N, L = 2, 320, 768 m1 = torch.randn(B, N, L) m1_resi = torch.randn(B, N, L) m2 = torch.randn(B, N, L) cross_mamba = CrossMamba(dim) output = cross_mamba(m1, m1_resi, m2) print("输出尺寸:", output.shape)代码说明:
-
多次交叉融合: 通过两次调用
Mamba模块实现特征的两次交互融合,确保每次融合后的特征都和输入保持相同的形状。 -
规范化处理: 每次融合之前对输入进行规范化,以确保数值稳定性。
-
设计意义: 两次融合步骤使得特征交互更充分,能够获得更丰富的信息表达,同时保持形状的一致性。
此次的设计有效利用多次交互机制提升了网络性能,而不需要对输入和输出形状进行修改。
-
- User
但是原始的crossmamba逻辑是: m1_resi = m1+m1_resi
global_f = self.cross_mamba(m1, extra_emb=m2) return global_f - Assistant
理解您的需求后,我们可以在保持逻辑不改变的情况下,增加第二次融合操作,以实现更深层次的特征交互融合,同时保持输入和输出的维度形状不变。这可以通过在返回
global_f之前添加一次额外的交互来实现。以下是修改后的代码:pythonimport torch import torch.nn as nn from einops import rearrange from mamba_ssm.modules.mamba_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,) self.weight = nn.Parameter(torch.ones(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,) self.weight = nn.Parameter(torch.ones(normalized_shape)) self.bias = nn.Parameter(torch.zeros(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) class CrossMamba(nn.Module): def __init__(self, dim): super(CrossMamba, self).__init__() self.cross_mamba1 = Mamba(dim, bimamba_type="v3") # 第一次交互 self.cross_mamba2 = Mamba(dim, bimamba_type="v3") # 第二次交互 self.norm1 = LayerNorm(dim, 'with_bias') self.norm2 = LayerNorm(dim, 'with_bias') def forward(self, m1, m1_resi, m2): # 原始逻辑:增量合并 m1_resi = m1 + m1_resi # 第一次交互融合 fusion1 = self.cross_mamba1(m1, extra_emb=m2) # 第二次交互融合,加入初次融合结果 global_f = self.cross_mamba2(fusion1, extra_emb=m2) return global_f # 测试 dim = 768 B, N, L = 2, 320, 768 m1 = torch.randn(B, N, L) m1_resi = torch.randn(B, N, L) m2 = torch.randn(B, N, L) cross_mamba = CrossMamba(dim) output = cross_mamba(m1, m1_resi, m2) print("输出尺寸:", output.shape)代码说明:
-
两次融合: 新增了
cross_mamba2,用于对cross_mamba1的输出结果fusion1进行二次交互融合。这样可以让模型进一步优化对潜在特征的捕捉和融合。 -
保持形状不变: 每次融合操作的输入和输出形状都不发生变化,始终保持为
(B, N, L)。 -
特征深度交互: 通过反复使用跨模态融合,特征得到了更深层次的处理和交互,提升了信息表达的丰富度。
这样设计的
CrossMamba能够持久化输入的逻辑并更深入地进行特征处理,同时保证输入和输出的形状一致,满足原始需求。 -