在# Copyright (c) 2023, Tri Dao, Albert Gu. import math from typing import Optional…
- User
在# Copyright (c) 2023, Tri Dao, Albert Gu.
import math from typing import Optional
import torch import torch.nn as nn import torch.nn.functional as F from torch import Tensor
from einops import rearrange, repeat
try: from causal_conv1d import causal_conv1d_fn, causal_conv1d_update except ImportError: causal_conv1d_fn, causal_conv1d_update = None
try: from mamba_ssm.ops.selective_scan_interface import selective_scan_fn, mamba_inner_fn, bimamba_inner_fn, mamba_inner_fn_no_out_proj except ImportError: # selective_scan_fn, mamba_inner_fn, bimamba_inner_fn, mamba_inner_fn_no_out_proj = None, None, None, None, None selective_scan_fn, mamba_inner_fn, bimamba_inner_fn, mamba_inner_fn_no_out_proj = None, None, None, None try: from mamba_ssm.ops.triton.selective_state_update import selective_state_update except ImportError: selective_state_update = None
try: from mamba_ssm.ops.triton.layernorm import RMSNorm, layer_norm_fn, rms_norm_fn except ImportError: RMSNorm, layer_norm_fn, rms_norm_fn = None, None, None
class Mamba(nn.Module): def init( self, d_model, d_state=16, d_conv=4, expand=2, dt_rank="auto", dt_min=0.001, dt_max=0.1, dt_init="random", dt_scale=1.0, dt_init_floor=1e-4, conv_bias=True, bias=False, use_fast_path=True, # Fused kernel options layer_idx=None, device=None, dtype=None, bimamba_type="v2", if_devide_out=False, init_layer_scale=None, ): factory_kwargs = {"device": device, "dtype": dtype} super().init() self.d_model = d_model self.d_state = d_state self.d_conv = d_conv self.expand = expand self.d_inner = int(self.expand * self.d_model) self.dt_rank = math.ceil(self.d_model / 16) if dt_rank == "auto" else dt_rank self.use_fast_path = use_fast_path self.layer_idx = layer_idx self.bimamba_type = bimamba_type self.if_devide_out = if_devide_out
self.init_layer_scale = init_layer_scale if init_layer_scale is not None: self.gamma = nn.Parameter(init_layer_scale * torch.ones((d_model)), requires_grad=True) self.in_proj = nn.Linear(self.d_model, self.d_inner * 2, bias=bias, **factory_kwargs) self.conv1d = nn.Conv1d( in_channels=self.d_inner, out_channels=self.d_inner, bias=conv_bias, kernel_size=d_conv, groups=self.d_inner, padding=d_conv - 1, **factory_kwargs, ) self.activation = "silu" self.act = nn.SiLU() self.x_proj = nn.Linear( self.d_inner, self.dt_rank + self.d_state * 2, bias=False, **factory_kwargs ) self.dt_proj = nn.Linear(self.dt_rank, self.d_inner, bias=True, **factory_kwargs) # Initialize special dt projection to preserve variance at initialization dt_init_std = self.dt_rank**-0.5 * dt_scale if dt_init == "constant": nn.init.constant_(self.dt_proj.weight, dt_init_std) elif dt_init == "random": nn.init.uniform_(self.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(self.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(): self.dt_proj.bias.copy_(inv_dt) # Our initialization would set all Linear.bias to zero, need to mark this one as _no_reinit self.dt_proj.bias._no_reinit = True # S4D real initialization A = repeat( torch.arange(1, self.d_state + 1, dtype=torch.float32, device=device), "n -> d n", d=self.d_inner, ).contiguous() A_log = torch.log(A) # Keep A_log in fp32 self.A_log = nn.Parameter(A_log) self.A_log._no_weight_decay = True # D "skip" parameter self.D = nn.Parameter(torch.ones(self.d_inner, device=device)) # Keep in fp32 self.D._no_weight_decay = True # bidirectional if bimamba_type == "v1": A_b = repeat( torch.arange(1, self.d_state + 1, dtype=torch.float32, device=device), "n -> d n", d=self.d_inner, ).contiguous() A_b_log = torch.log(A_b) # Keep A_b_log in fp32 self.A_b_log = nn.Parameter(A_b_log) self.A_b_log._no_weight_decay = True elif bimamba_type == "v2" or bimamba_type=='v3': A_b = repeat( torch.arange(1, self.d_state + 1, dtype=torch.float32, device=device), "n -> d n", d=self.d_inner, ).contiguous() A_b_log = torch.log(A_b) # Keep A_b_log in fp32 self.A_b_log = nn.Parameter(A_b_log) self.A_b_log._no_weight_decay = True self.conv1d_b = nn.Conv1d( in_channels=self.d_inner, out_channels=self.d_inner, bias=conv_bias, kernel_size=d_conv, groups=self.d_inner, padding=d_conv - 1, **factory_kwargs, ) self.x_proj_b = nn.Linear( self.d_inner, self.dt_rank + self.d_state * 2, bias=False, **factory_kwargs ) self.dt_proj_b = nn.Linear(self.dt_rank, self.d_inner, bias=True, **factory_kwargs) self.D_b = nn.Parameter(torch.ones(self.d_inner, device=device)) # Keep in fp32 self.D_b._no_weight_decay = True self.in_proj_extra = nn.Linear(self.d_model, self.d_inner * 2, bias=bias, **factory_kwargs) self.out_proj = nn.Linear(self.d_inner, self.d_model, bias=bias, **factory_kwargs) def forward(self, hidden_states, inference_params=None,extra_emb=None): """ hidden_states: (B, L, D) Returns: same shape as hidden_states """ batch, seqlen, dim = hidden_states.shape conv_state, ssm_state = None, None if inference_params is not None: conv_state, ssm_state = self._get_states_from_cache(inference_params, batch) if inference_params.seqlen_offset > 0: # The states are updated inplace out, _, _ = self.step(hidden_states, conv_state, ssm_state) return out if extra_emb is None: # We do matmul and transpose BLH -> HBL at the same time xz = rearrange( self.in_proj.weight @ rearrange(hidden_states, "b l d -> d (b l)"), "d (b l) -> b d l", l=seqlen, ) if self.in_proj.bias is not None: xz = xz + rearrange(self.in_proj.bias.to(dtype=xz.dtype), "d -> d 1") else: xz = rearrange( self.in_proj.weight @ rearrange(hidden_states, "b l d -> d (b l)"), "d (b l) -> b d l", l=seqlen, ) if self.in_proj.bias is not None: xz = xz + rearrange(self.in_proj.bias.to(dtype=xz.dtype), "d -> d 1") extra_emb = rearrange( self.in_proj_extra.weight @ rearrange(extra_emb, "b l d -> d (b l)"), "d (b l) -> b d l", l=seqlen, ) if self.in_proj_extra.bias is not None: extra_emb = extra_emb + rearrange(self.in_proj_extra.bias.to(dtype=xz.dtype), "d -> d 1") A = -torch.exp(self.A_log.float()) # (d_inner, d_state) # In the backward pass we write dx and dz next to each other to avoid torch.cat if self.use_fast_path and inference_params is None: # Doesn't support outputting the states if self.bimamba_type == "v1": A_b = -torch.exp(self.A_b_log.float()) out = bimamba_inner_fn( xz, self.conv1d.weight, self.conv1d.bias, self.x_proj.weight, self.dt_proj.weight, self.out_proj.weight, self.out_proj.bias, A, A_b, None, # input-dependent B None, # input-dependent C self.D.float(), delta_bias=self.dt_proj.bias.float(), delta_softplus=True, ) elif self.bimamba_type == "v2": A_b = -torch.exp(self.A_b_log.float()) out = mamba_inner_fn_no_out_proj( xz, self.conv1d.weight, self.conv1d.bias, self.x_proj.weight, self.dt_proj.weight, A, None, # input-dependent B None, # input-dependent C self.D.float(), delta_bias=self.dt_proj.bias.float(), delta_softplus=True, ) out_b = mamba_inner_fn_no_out_proj( xz.flip([-1]), self.conv1d_b.weight, self.conv1d_b.bias, self.x_proj_b.weight, self.dt_proj_b.weight, A_b, None, None, self.D_b.float(), delta_bias=self.dt_proj_b.bias.float(), delta_softplus=True, ) # F.linear(rearrange(out_z, "b d l -> b l d"), out_proj_weight, out_proj_bias) if not self.if_devide_out: out = F.linear(rearrange(out + out_b.flip([-1]), "b d l -> b l d"), self.out_proj.weight, self.out_proj.bias) else: out = F.linear(rearrange(out + out_b.flip([-1]), "b d l -> b l d") / 2, self.out_proj.weight, self.out_proj.bias) elif self.bimamba_type == "v3": A_b = -torch.exp(self.A_b_log.float()) out = mamba_inner_fn_no_out_proj( xz, self.conv1d.weight, self.conv1d.bias, self.x_proj.weight, self.dt_proj.weight, A, None, # input-dependent B None, # input-dependent C self.D.float(), delta_bias=self.dt_proj.bias.float(), delta_softplus=True, ) out_b = mamba_inner_fn_no_out_proj( # extra_emb同上文中xz.flip不同 extra_emb, self.conv1d_b.weight, self.conv1d_b.bias, self.x_proj_b.weight, self.dt_proj_b.weight, A_b, None, None, self.D_b.float(), delta_bias=self.dt_proj_b.bias.float(), delta_softplus=True, ) # F.linear(rearrange(out_z, "b d l -> b l d"), out_proj_weight, out_proj_bias) if not self.if_devide_out: #True out = F.linear(rearrange(out + out_b, "b d l -> b l d"), self.out_proj.weight, self.out_proj.bias) else: #False out = F.linear(rearrange(out + out_b, "b d l -> b l d") / 2, self.out_proj.weight, self.out_proj.bias) else: #False out = mamba_inner_fn( xz, self.conv1d.weight, self.conv1d.bias, self.x_proj.weight, self.dt_proj.weight, self.out_proj.weight, self.out_proj.bias, A, None, # input-dependent B None, # input-dependent C self.D.float(), delta_bias=self.dt_proj.bias.float(), delta_softplus=True, ) else: #False x, z = xz.chunk(2, dim=1) # Compute short convolution if conv_state is not None: # If we just take x[:, :, -self.d_conv :], it will error if seqlen < self.d_conv # Instead F.pad will pad with zeros if seqlen < self.d_conv, and truncate otherwise. conv_state.copy_(F.pad(x, (self.d_conv - x.shape[-1], 0))) # Update state (B D W) if causal_conv1d_fn is None: x = self.act(self.conv1d(x)[..., :seqlen]) else: assert self.activation in ["silu", "swish"] x = causal_conv1d_fn( x=x, weight=rearrange(self.conv1d.weight, "d 1 w -> d w"), bias=self.conv1d.bias, activation=self.activation, ) # We're careful here about the layout, to avoid extra transposes. # We want dt to have d as the slowest moving dimension # and L as the fastest moving dimension, since those are what the ssm_scan kernel expects. 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=seqlen) B = rearrange(B, "(b l) dstate -> b dstate l", l=seqlen).contiguous() C = rearrange(C, "(b l) dstate -> b dstate l", l=seqlen).contiguous() assert self.activation in ["silu", "swish"] y = selective_scan_fn( x, dt, A, B, C, self.D.float(), z=z, delta_bias=self.dt_proj.bias.float(), delta_softplus=True, return_last_state=ssm_state is not None, ) if ssm_state is not None: y, last_state = y ssm_state.copy_(last_state) y = rearrange(y, "b d l -> b l d") out = self.out_proj(y) if self.init_layer_scale is not None: #False out = out * self.gamma return out def step(self, hidden_states, conv_state, ssm_state): dtype = hidden_states.dtype assert hidden_states.shape[1] == 1, "Only support decoding with 1 token at a time for now" xz = self.in_proj(hidden_states.squeeze(1)) # (B 2D) x, z = xz.chunk(2, dim=-1) # (B D) # Conv step if causal_conv1d_update is None: conv_state.copy_(torch.roll(conv_state, shifts=-1, dims=-1)) # Update state (B D W) conv_state[:, :, -1] = x x = torch.sum(conv_state * rearrange(self.conv1d.weight, "d 1 w -> d w"), dim=-1) # (B D) if self.conv1d.bias is not None: x = x + self.conv1d.bias x = self.act(x).to(dtype=dtype) else: x = causal_conv1d_update( x, conv_state, rearrange(self.conv1d.weight, "d 1 w -> d w"), self.conv1d.bias, self.activation, ) x_db = self.x_proj(x) # (B dt_rank+2*d_state) dt, B, C = torch.split(x_db, [self.dt_rank, self.d_state, self.d_state], dim=-1) # Don't add dt_bias here dt = F.linear(dt, self.dt_proj.weight) # (B d_inner) A = -torch.exp(self.A_log.float()) # (d_inner, d_state) # SSM step if selective_state_update is None: # Discretize A and B dt = F.softplus(dt + self.dt_proj.bias.to(dtype=dt.dtype)) dA = torch.exp(torch.einsum("bd,dn->bdn", dt, A)) dB = torch.einsum("bd,bn->bdn", dt, B) ssm_state.copy_(ssm_state * dA + rearrange(x, "b d -> b d 1") * dB) y = torch.einsum("bdn,bn->bd", ssm_state.to(dtype), C) y = y + self.D.to(dtype) * x y = y * self.act(z) # (B D) else: y = selective_state_update( ssm_state, x, dt, A, B, C, self.D, z=z, dt_bias=self.dt_proj.bias, dt_softplus=True ) out = self.out_proj(y) return out.unsqueeze(1), conv_state, ssm_state def allocate_inference_cache(self, batch_size, max_seqlen, dtype=None, **kwargs): device = self.out_proj.weight.device conv_dtype = self.conv1d.weight.dtype if dtype is None else dtype conv_state = torch.zeros( batch_size, self.d_model * self.expand, self.d_conv, device=device, dtype=conv_dtype ) ssm_dtype = self.dt_proj.weight.dtype if dtype is None else dtype # ssm_dtype = torch.float32 ssm_state = torch.zeros( batch_size, self.d_model * self.expand, self.d_state, device=device, dtype=ssm_dtype ) return conv_state, ssm_state def _get_states_from_cache(self, inference_params, batch_size, initialize_states=False): assert self.layer_idx is not None if self.layer_idx not in inference_params.key_value_memory_dict: batch_shape = (batch_size,) conv_state = torch.zeros( batch_size, self.d_model * self.expand, self.d_conv, device=self.conv1d.weight.device, dtype=self.conv1d.weight.dtype, ) ssm_state = torch.zeros( batch_size, self.d_model * self.expand, self.d_state, device=self.dt_proj.weight.device, dtype=self.dt_proj.weight.dtype, # dtype=torch.float32, ) inference_params.key_value_memory_dict[self.layer_idx] = (conv_state, ssm_state) else: conv_state, ssm_state = inference_params.key_value_memory_dict[self.layer_idx] # TODO: What if batch size changes between generation, and we reuse the same states? if initialize_states: conv_state.zero_() ssm_state.zero_() return conv_state, ssm_state - Assistant
- User
当前模型中有两个并行的不同的输入,采用哪个版本的crossmamba更合适?
- Assistant
在模型具有两个并行不同输入的情况下,选择合适的版本主要取决于你希望如何融合这些输入以及它们之间的关系。如果假设有两个输入
m1和m2,我们来分析一下每个版本的CrossMamba的适用场景:分析各个版本的适用性
-
v1版本:
- 特点:v1 版本涉及双向处理(forward 和 backward)。
- 适用性:如果你的并行输入需要在双向(如时序数据的前后处理)上都进行复杂操作,并且这两种处理方式需要融合,那么 v1 可能适合。不过 v1 版本并不特别针对两个不同的输入,而是双向处理同一序列的不同方向。
-
v2版本:
- 特点:v2 版本处理单向和反向,可以并行处理和融合,但不直接使用输出投影合并结果。而是分别计算每个方向的状态更新。
-
- User
Traceback (most recent call last): File "tools/train.py", line 136, in main() File "tools/train.py", line 129, in main runner = Runner.from_cfg(cfg) File "/home/heyuting/anaconda3/envs/spike/lib/python3.8/site-packages/mmengine/runner/runner.py", line 462, in from_cfg runner = cls( File "/home/heyuting/anaconda3/envs/spike/lib/python3.8/site-packages/mmengine/runner/runner.py", line 397, in self.log_processor = self.build_log_processor(log_processor) File "/home/heyuting/anaconda3/envs/spike/lib/python3.8/site-packages/mmengine/runner/runner.py", line 1650, in build_log_processor log_processor = LOG_PROCESSORS.build(log_processor_cfg) File "/home/heyuting/anaconda3/envs/spike/lib/python3.8/site-packages/mmengine/registry/registry.py", line 570, in build return self.build_func(cfg, *args, **kwargs, registry=self) File "/home/heyuting/anaconda3/envs/spike/lib/python3.8/site-packages/mmengine/registry/build_functions.py", line 95, in build_from_cfg with registry.switch_scope_and_registry(scope) as registry: File "/home/heyuting/anaconda3/envs/spike/lib/python3.8/contextlib.py", line 113, in return next(self.gen) File "/home/heyuting/anaconda3/envs/spike/lib/python3.8/site-packages/mmengine/registry/registry.py", line 287, in switch_scope_and_registry import_module(f'{scope_name}.registry') File "/home/heyuting/anaconda3/envs/spike/lib/python3.8/importlib/.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 1014, in _gcd_import File "", line 991, in _find_and_load File "", line 961, in _find_and_load_unlocked File "", line 219, in _call_with_frames_removed File "", line 1014, in _gcd_import File "", line 991, in _find_and_load File "", line 975, in _find_and_load_unlocked File "", line 671, in _load_unlocked File "", line 843, in exec_module File "", line 219, in _call_with_frames_removed File "/data2/local_userdata/heyuting/SSTFormer/SSTFormer-main/mmaction2/mmaction/.py", line 16, in assert (digit_version(mmcv_minimum_version) <= mmcv_version AssertionError: MMCV==2.2.0 is used but incompatible. Please install mmcv>=2.0.0rc4, <2.2.0.
- Assistant
你的错误信息指出当前使用的
MMCV版本(2.2.0)与项目不兼容,需要安装特定版本范围内的MMCV。解决方法
-
卸载当前版本的
MMCV: 首先,卸载现有的MMCV以确保没有冲突:pip uninstall mmcv -
安装兼容的
MMCV版本: 根据错误信息,你需要安装mmcv版本区间为>=2.0.0rc4, <2.2.0。你可以安装2.1.0作为一个安全的选择:pip install mmcv-full==2.1.0
或者你可以选择任意在 2.0.0rc4 到 2.1.9 之间的版本:
pip install mmcv-full==2.1.0确保安装的版本在
[2.0.0rc4, 2.2.0)范围内。验证安装
安装之后,你可以检查安装的
MMCV版本来确认是否正确:python -c "import mmcv; print(mmcv.__version__)"如果返回的版本在指定的范围内,那么你可以重新运行你的模型训练任务。
注意事项
在运行上述命令之前,请确保你的虚拟环境或conda环境已经激活(如果你在使用这些环境):
conda activate spike这样可以确保在你项目环境中执行安装和验证步骤。通过确保 mmcv 版本兼容你的项目依赖,应该能够解决之前的问题并成功运行项目。
-
- User
为什么mmcv变成了mmcv-ful?
- Assistant
理解到
MMCV以及MMCV-FULL的区别有助于确保你安装了正确的版本来满足你项目的需求。下面是简要的解释:MMCV vs. MMCV-FULL
- MMCV 包含了一般的基础组件和功能。
- MMCV-FULL 则包含了所有
MMCV的功能,以及一些额外的依赖项,比如 CUDA 的加速功能。
在项目中,如果没有用到 CUDA 加速等高级功能,可以选择安装
MMCV。如果需要完整的功能集,特别是涉及到一些 CUDA 加速的操作,选择MMCV-FULL会更合适。解决你的问题
根据你项目的需求和错误提示,简要总结两个安装命令:
安装普通版本的 MMCV
pip install mmcv==2.1.0如果需要安装
MMCV-FULL:pip install mmcv-full==2.1.0下面是步骤详细总结:
卸载已经安装的 mmcv
首先,卸载现有的
MMCV包(无论是普通版还是 FULL 版):pip uninstall mmcv mmcv-full安装兼容版本的 mmcv
安装普通版 MMCV
根据你的项目要求,只需普通版
MMCV即可:pip install mmcv==2.1.0或者,使用FULL版本方法:
pip install mmcv-full==2.1.0验证安装
安装完成后,可以运行以下命令来验证:
- User
/data2/local_userdata/heyuting/SSTFormer/SSTFormer-main/SpikingF_MST/hardutils.py:15: ImportWarning: failed to load custom correlation module which is needed for FlowNetC warnings.warn("failed to load custom correlation module which is needed for FlowNetC", ImportWarning) Traceback (most recent call last): File "train.py", line 13, in import model, utils File "/data2/local_userdata/heyuting/SSTFormer/SSTFormer-main/SpikingF_MST/model.py", line 13, in from MST_model import MST File "/data2/local_userdata/heyuting/SSTFormer/SSTFormer-main/SpikingF_MST/MST_model.py", line 15, in from mmcv.ops import DeformConv2dPack as DCN
File "/data2/local_userdata/heyuting/SSTFormer/SSTFormer-main/SpikingF_MST/mmcv/ops/init.py", line 3, in from .active_rotated_filter import active_rotated_filter File "/data2/local_userdata/heyuting/SSTFormer/SSTFormer-main/SpikingF_MST/mmcv/ops/active_rotated_filter.py", line 10, in ext_module = ext_loader.load_ext( File "/data2/local_userdata/heyuting/SSTFormer/SSTFormer-main/SpikingF_MST/mmcv/utils/ext_loader.py", line 13, in load_ext ext = importlib.import_module('mmcv.' + name) File "/home/heyuting/anaconda3/envs/spike/lib/python3.8/importlib/init.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) ImportError: /data2/local_userdata/heyuting/SSTFormer/SSTFormer-main/SpikingF_MST/mmcv/_ext.cpython-38-x86_64-linux-gnu.so: undefined symbol: _ZNK2at6Tensor7is_cudaEv - Assistant
您遇到的问题似乎是由于与
MMCV库相关的依赖项或编译问题,尤其是与CUDA和相关扩展模块有关。而且,如果你正在使用自定义编译的MMCV扩展模块,比如_ext.cpython-38-x86_64-linux-gnu.so,这个错误通常表示你的编译环境和运行环境之间存在不一致的问题。解决策略
-
确保
MMCV-FULL正确安装:- 如果你需要使用
MMCV的所有功能(包括DeformConv2dPack和其他需要 CUDA 支持的模块),请确认你安装的是MMCV-FULL。
- 如果你需要使用
-
重新编译
MMCV扩展:- 有冒号错误,可能是因为
MMCV的扩展模块没有正确编译。你可以尝试重新编译这些扩展模块。
- 有冒号错误,可能是因为
-
检查 CUDA 和 PyTorch 版本一致性:
-
- User
/data2/local_userdata/heyuting/SSTFormer/SSTFormer-main/SpikingF_MST/hardutils.py:15: ImportWarning: failed to load custom correlation module which is needed for FlowNetC warnings.warn("failed to load custom correlation module which is needed for FlowNetC", ImportWarning) Traceback (most recent call last): File "train.py", line 13, in import model, utils File "/data2/local_userdata/heyuting/SSTFormer/SSTFormer-main/SpikingF_MST/model.py", line 13, in from MST_model import MST File "/data2/local_userdata/heyuting/SSTFormer/SSTFormer-main/SpikingF_MST/MST_model.py", line 19, in from mmcv.utils import _BatchNorm ImportError: cannot import name '_BatchNorm' from 'mmcv.utils' (/data2/local_userdata/heyuting/SSTFormer/SSTFormer-main/SpikingF_MST/mmcv/utils/init.py)
- Assistant
ImportError: cannot import name '_BatchNorm' from 'mmcv.utils'这个错误指出从mmcv.utils中无法导入_BatchNorm,这是因为mmcv的 API 可能在不同版本中有所不同。可能解决方案
-
检查 mmcv 的版本与项目的兼容性:
- 确保你使用的
mmcv版本与项目所期望的版本一致。 - 检查项目的
requirements.txt或其他依赖文件,确保版本匹配。
- 确保你使用的
-
正确导入 _BatchNorm:
_BatchNorm可能已经移到其他模块或更改名称。- 检查
mmcv文档或源码,寻找_BatchNorm的定义。
解决步骤
检查 mmcv 版本
确保
mmcv版本是项目所期望的:import mmcv print(mmcv.__version__)确保版本在项目兼容的范围内。如果版本不匹配,就需要安装合适的版本。例如,如果版本是
2.1.0:pip install mmcv-full==2.1.0 -f https://download.openmmlab.com/mmcv/dist/cu111/torch1.9.0/index.html -
- User
报错:python train.py --T=16 -b=6 --num-classes=300 --workers=8 --epochs=100 --print-freq=300 --output-dir='.logs' --warmup-epochs=0 --warmup-lr=0.0001 --opt=sgd --weight-decay=0.0005 --decay-epochs=20 --lr=0.001 --decay-rate=0.1 /data2/local_userdata/heyuting/SSTFormer/SSTFormer-main/SpikingF_MST/hardutils.py:15: ImportWarning: failed to load custom correlation module which is needed for FlowNetC warnings.warn("failed to load custom correlation module which is needed for FlowNetC", ImportWarning) Not using distributed mode Namespace(T=16, T_train=None, amp=True, batch_size=6, connect_f='ADD', cooldown_epochs=10, cutmix=0.0, cutmix_minmax=None, data_path='/media/data/cifar10dvs/', dataset='cifar10dvs', decay_epochs=20.0, decay_rate=0.1, device='cuda', dist_url='env://', distributed=False, epoch_repeats=0.0, epochs=100, log_interval=100, lr=0.001, lr_cycle_limit=1, lr_cycle_mul=1.0, lr_noise=None, lr_noise_pct=0.67, lr_noise_std=1.0, min_lr=1e-05, mixup=0.5, mixup_mode='batch', mixup_off_epoch=0, mixup_prob=0.5, mixup_switch_prob=0.5, model='SEWResNet', momentum=0.9, num_classes=300, opt='sgd', opt_betas=None, opt_eps=1e-08, output_dir='.logs', patience_epochs=10, print_freq=300, resume='', sched='cosine', smoothing=0.1, start_epoch=0, sync_bn=False, tb=True, test_only=False, warmup_epochs=0, warmup_lr=0.0001, weight_decay=0.0005, workers=8, world_size=1) Traceback (most recent call last): File "train.py", line 629, in main(args) File "train.py", line 476, in main train_data = train_data_loader(data_set=args.dataset) File "train.py", line 281, in train_data_loader train_data = VideoDataset(list_file="/data2/local_userdata/heyuting/datasets/PokerEvent/train_label.txt", TypeError: () got an unexpected keyword argument 'num_segments'
- Assistant
TypeError: __init__() got an unexpected keyword argument 'num_segments'这个错误表示 的初始化方法不接受 这个参数。这可能是因为 类的定义已经改变,或者你使用了错误版本的代码。 - User
- Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.