当前模型:import math
import logging
from functools import partial
from collections import OrderedDict
from copy import deepcopy
import torch
import torch.nn as nn
import torch.nn.functional as F
from timm.models.layers import to_2tuple
from lib.models.layers.patch_embed import PatchEmbed, PatchEmbed_event, xcorr_depthwise
from .utils import combine_tokens, recover_tokens
from .vit import VisionTransformer
from …layers.attn_blocks import CEBlock
import random
import numpy as np
from .cross_module import Counter_Guide_Enhanced, Cross_Attention
from .UEP import UEPModule
_logger = logging.getLogger(name)
class VisionTransformerCE(VisionTransformer):
“”" Vision Transformer with candidate elimination (CE) module
A PyTorch impl of : An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale
dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)] # stochastic depth decay rule
blocks = []
ce_index = 0
self.ce_loc = ce_loc
for i in range(depth):
ce_keep_ratio_i = 1.0
if ce_loc is not None and i in ce_loc:
ce_keep_ratio_i = ce_keep_ratio[ce_index]
ce_index += 1
if mask_z is not None and mask_x is not None:
mask_z = F.interpolate(mask_z[None].float(), scale_factor=1. / self.patch_size).to(torch.bool)[0]
mask_z = mask_z.flatten(1).unsqueeze(-1)
if self.add_cls_token:
cls_tokens = self.cls_token.expand(B, -1, -1)
cls_tokens = cls_tokens + self.cls_pos_embed
if self.add_sep_seg:
x += self.search_segment_pos_embed
z += self.template_segment_pos_embed
x = combine_tokens(z, x, mode=self.cat_mode)
if self.add_cls_token:
x = torch.cat([cls_tokens, x], dim=1)
x = self.pos_drop(x)
if self.ce_loc is not None and i in self.ce_loc:
removed_indexes_s.append(removed_index_s)
removed_indexes_s1.append(removed_index_s1)
if i == 0 :
enhanced_x, enhanced_event_x = self.counter_guide(x, event_x)
x = x + enhanced_x
event_x = event_x + enhanced_event_x
应用LayerNorm归一化处理
x = self.norm(x)
event_x = self.norm(event_x)
x_cat = torch.cat([event_x, x], dim=1)
x = x_cat
aux_dict = {
“attn”: attn,
“attn1”: attn1,
“removed_indexes_s”: removed_indexes_s, # used for visualization
‘removed_indexes_s1’: removed_indexes_s1, # used for visualization
}
return x, aux_dict
def _create_vision_transformer(pretrained=False, **kwargs):
model = VisionTransformerCE(**kwargs)
if pretrained:
if ‘npz’ in pretrained:
model.load_pretrained(pretrained, prefix=‘’)
else:
checkpoint = torch.load(pretrained, map_location=“cpu”)
missing_keys, unexpected_keys = model.load_state_dict(checkpoint[“model”], strict=False)
print('Load pretrained model from: ’ + pretrained)
return model
def vit_base_patch16_224_ce(pretrained=False, **kwargs):
“”” ViT-Base model (ViT-B/16) from original paper (https://arxiv.org/abs/2010.11929).
“”“
model_kwargs = dict(
patch_size=16, embed_dim=768, depth=12, num_heads=12, **kwargs)
model = _create_vision_transformer(pretrained=pretrained, **model_kwargs)
return model
def vit_large_patch16_224_ce(pretrained=False, **kwargs):
“”” ViT-Large model (ViT-L/16) from original paper (https://arxiv.org/abs/2010.11929).
“”"
model_kwargs = dict(
patch_size=16, embed_dim=1024, depth=24, num_heads=16, **kwargs)
model = _create_vision_transformer(pretrained=pretrained, **model_kwargs)
return model,其中rgb分支读取的aps目录下的文件,event分支读取的是dvs目录下的文件,那么上文中的fusion目录下的文件,是否可以替换或者作为新的输入源?其中生成fusion目录文件的代码是:import os
import cv2
from PIL import Image
import matplotlib.pyplot as plt
import time
data_path = r'/data2/local_userdata/heyuting/datasets/COESOT/train'
save_path = r'/data2/local_userdata/heyuting/datasets/COESOT/train'
if not os.path.exists(save_path):
os.mkdir(save_path)
filenames = sorted([f for f in os.listdir(data_path) if os.path.isdir(os.path.join(data_path, f))])
pip install mmcv-full==1.1.5 -f https://download.openmmlab.com/mmcv/dist/cu101/torch1.6.0/index.html
Looking in links: https://download.openmmlab.com/mmcv/dist/cu101/torch1.6.0/index.html
Collecting mmcv-full==1.1.5
Using cached https://download.openmmlab.com/mmcv/dist/cu101/torch1.6.0/mmcv_full-1.1.5-cp38-cp38-manylinux1_x86_64.whl (18.5 MB)
Collecting addict (from mmcv-full==1.1.5)
Using cached addict-2.4.0-py3-none-any.whl.metadata (1.0 kB)
Requirement already satisfied: numpy in /home/heyuting/anaconda3/envs/spike/lib/python3.8/site-packages (from mmcv-full==1.1.5) (1.24.3)
Requirement already satisfied: pyyaml in /home/heyuting/anaconda3/envs/spike/lib/python3.8/site-packages (from mmcv-full==1.1.5) (6.0.1)
Collecting yapf (from mmcv-full==1.1.5)
Using cached yapf-0.40.2-py3-none-any.whl.metadata (45 kB)
WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ReadTimeoutError("HTTPSConnectionPool(host='pypi.org', port=443): Read timed out. (read timeout=15)")': /simple/opencv-python/
WARNING: Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ReadTimeoutError("HTTPSConnectionPool(host='pypi.org', port=443): Read timed out. (read timeout=15)")': /simple/opencv-python/
INFO: pip is looking at multiple versions of mmcv-full to determine which version is compatible with other requirements. This could take a while.
ERROR: Could not find a version that satisfies the requirement opencv-python>=3 (from mmcv-full) (from versions: none)
ERROR: No matching distribution found for opencv-python>=3报错如何解决?
mim install mmdet
Traceback (most recent call last):
File "/home/heyuting/anaconda3/envs/spike/bin/mim", line 5, in
from mim.cli import cli
File "/home/heyuting/anaconda3/envs/spike/lib/python3.8/site-packages/mim/init.py", line 16, in
from .commands import (
File "/home/heyuting/anaconda3/envs/spike/lib/python3.8/site-packages/mim/commands/init.py", line 2, in
from .download import download
File "/home/heyuting/anaconda3/envs/spike/lib/python3.8/site-packages/mim/commands/download.py", line 12, in
from mim.click import (
File "/home/heyuting/anaconda3/envs/spike/lib/python3.8/site-packages/mim/click/init.py", line 8, in
from .customcommand import CustomCommand
File "/home/heyuting/anaconda3/envs/spike/lib/python3.8/site-packages/mim/click/customcommand.py", line 14, in
from mim.utils import (
File "/home/heyuting/anaconda3/envs/spike/lib/python3.8/site-packages/mim/utils/init.py", line 14, in
from .utils import (
File "/home/heyuting/anaconda3/envs/spike/lib/python3.8/site-packages/mim/utils/utils.py", line 18, in
import requests
File "/home/heyuting/anaconda3/envs/spike/lib/python3.8/site-packages/requests/init.py", line 48, in
from charset_normalizer import version as charset_normalizer_version
File "/home/heyuting/anaconda3/envs/spike/lib/python3.8/site-packages/charset_normalizer/init.py", line 23, in
from charset_normalizer.api import from_fp, from_path, from_bytes, normalize
File "/home/heyuting/anaconda3/envs/spike/lib/python3.8/site-packages/charset_normalizer/api.py", line 10, in
from charset_normalizer.md import mess_ratio
AttributeError: partially initialized module 'charset_normalizer' has no attribute 'md__mypyc' (most likely due to a circular import)
通过以上步骤,你应该能够解决 attributeError: partially initialized module 'charset_normalizer' has no attribute 'md__mypyc' 这个错误,并成功安装 mmdet。
User
mim install mmdet --timeout 300
Looking in links: https://download.openmmlab.com/mmcv/dist/cu117/torch1.13.0/index.html
WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ProtocolError('Connection aborted.', ConnectionResetError(104, 'Connection reset by peer'))': /simple/mmdet/
Collecting mmdet
Using cached mmdet-3.3.0-py3-none-any.whl.metadata (29 kB)
WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ProtocolError('Connection aborted.', ConnectionResetError(104, 'Connection reset by peer'))': /simple/matplotlib/
Collecting matplotlib (from mmdet)
Using cached matplotlib-3.7.5-cp38-cp38-manylinux_2_12_x86_64.manylinux2010_x86_64.whl.metadata (5.7 kB)
Requirement already satisfied: numpy in /home/heyuting/anaconda3/envs/spike/lib/python3.8/site-packages (from mmdet) (1.24.3)
Collecting pycocotools (from mmdet)
Using cached pycocotools-2.0.7-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl.metadata (1.1 kB)
^[[A^[[BINFO: pip is looking at multiple versions of mmdet to determine which version is compatible with other requirements. This could take a while.
Collecting mmdet
Using cached mmdet-3.2.0-py3-none-any.whl.metadata (32 kB)
Using cached mmdet-3.1.0-py3-none-any.whl.metadata (28 kB)
Downloading mmdet-3.0.0-py3-none-any.whl.metadata (26 kB)
Downloading mmdet-2.28.2-py3-none-any.whl.metadata (25 kB)
Downloading mmdet-2.28.1-py3-none-any.whl.metadata (23 kB)
Downloading mmdet-2.28.0-py3-none-any.whl.metadata (23 kB)
ERROR: Exception:
Traceback (most recent call last):
File "/home/heyuting/anaconda3/envs/spike/lib/python3.8/site-packages/pip/_vendor/urllib3/response.py", line 438, in _error_catcher
yield
File "/home/heyuting/anaconda3/envs/spike/lib/python3.8/site-packages/pip/_vendor/urllib3/response.py", line 561, in read
data = self._fp_read(amt) if not fp_closed else b""
File "/home/heyuting/anaconda3/envs/spike/lib/python3.8/site-packages/pip/_vendor/urllib3/response.py", line 527, in _fp_read
return self._fp.read(amt) if amt is not None else self._fp.read()
File "/home/heyuting/anaconda3/envs/spike/lib/python3.8/site-packages/pip/_vendor/cachecontrol/filewrapper.py", line 98, in read
data: bytes = self.__fp.read(amt)
File "/home/heyuting/anaconda3/envs/spike/lib/python3.8/http/client.py", line 459, in read
n = self.readinto(b)
File "/home/heyuting/anaconda3/envs/spike/lib/python3.8/http/client.py", line 503, in readinto
n = self.fp.readinto(b)
File "/home/heyuting/anaconda3/envs/spike/lib/python3.8/socket.py", line 669, in readinto
return self._sock.recv_into(b)
File "/home/heyuting/anaconda3/envs/spike/lib/python3.8/ssl.py", line 1274, in recv_into
return self.read(nbytes, buffer)
File "/home/heyuting/anaconda3/envs/spike/lib/python3.8/ssl.py", line 1132, in read
return self._sslobj.read(len, buffer)
socket.timeout: The read operation timed out
During handling of the above exception, another exception occurred:
报错: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 12, in
import cv2
File "/home/heyuting/anaconda3/envs/spike/lib/python3.8/site-packages/cv2/init.py", line 181, in
bootstrap()
File "/home/heyuting/anaconda3/envs/spike/lib/python3.8/site-packages/cv2/init.py", line 175, in bootstrap
if __load_extra_py_code_for_module("cv2", submodule, DEBUG):
File "/home/heyuting/anaconda3/envs/spike/lib/python3.8/site-packages/cv2/init.py", line 28, in __load_extra_py_code_for_module
py_module = importlib.import_module(module_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)
File "/home/heyuting/anaconda3/envs/spike/lib/python3.8/site-packages/cv2/typing/init.py", line 64, in
import cv2.mat_wrapper
File "/home/heyuting/anaconda3/envs/spike/lib/python3.8/site-packages/cv2/mat_wrapper/init.py", line 40, in
cv._registerMatType(Mat)
AttributeError: partially initialized module 'cv2' has no attribute '_registerMatType' (most likely due to a circular import)
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 20, in
from mmcv.utils import _BatchNorm
ImportError: cannot import name '_BatchNorm' from 'mmcv.utils' (/home/heyuting/anaconda3/envs/spike/lib/python3.8/site-packages/mmcv/utils/init.py)
Assistant
这个错误表明你试图从 mmcv.utils 导入 _BatchNorm,但它并不存在于该模块中。这可能是因为 mmcv 中的 API 已经发生了变化,或者是在某个版本中被移除了。
import torch.nn as nn
# 将 _BatchNorm 替换为 nn.BatchNorm2d 或其他适合的 PyTorch 内部实现
_BatchNorm = nn.BatchNorm2d
示例
假设你使用 PyTorch 提供的 BatchNorm2d 替代:
python
import torch.nn as nn
class YourModel(nn.Module):
def __init__(self):
super(YourModel, self).__init__()
self.batch_norm = nn.BatchNorm2d(num_features=64)
def forward(self, x):
return self.batch_norm(x)
可以在代码中找到所有使用 from mmcv.utils import _BatchNorm 的地方,将其替换为 PyTorch 中的 BatchNorm 实现。
希望通过以上步骤,你可以解决导入 _BatchNorm 的问题,并使你的代码能够正常运行。如果 mmcv 的 API 有重大变化,建议查阅最新的官方文档,以获取更新后的 API 信息。
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
Traceback (most recent call last):
File "/home/heyuting/anaconda3/envs/spike/lib/python3.8/site-packages/pip/_internal/cli/base_command.py", line 180, in exc_logging_wrapper
status = run_func(*args)
File "/home/heyuting/anaconda3/envs/spike/lib/python3.8/site-packages/pip/_internal/cli/req_command.py", line 245, in wrapper
return func(self, options, args)
File "/home/heyuting/anaconda3/envs/spike/lib/python3.8/site-packages/pip/_internal/commands/install.py", line 377, in run
requirement_set = resolver.resolve(
File "/home/heyuting/anaconda3/envs/spike/lib/python3.8/site-packages/pip/_internal/resolution/resolvelib/resolver.py", line 95, in resolve
result = self._result = resolver.resolve(
File "/home/heyuting/anaconda3/envs/spike/lib/python3.8/site-packages/pip/_vendor/resolvelib/resolvers.py", line 546, in resolve
state = resolution.resolve(requirements, max_rounds=max_rounds)
File "/home/heyuting/anaconda3/envs/spike/lib/python3.8/site-packages/pip/_vendor/resolvelib/resolvers.py", line 427, in resolve
failure_causes = self._attempt_to_pin_criterion(name)
File "/home/heyuting/anaconda3/envs/spike/lib/python3.8/site-packages/pip/_vendor/resolvelib/resolvers.py", line 237, in _attempt_to_pin_criterion
for candidate in criterion.candidates:
File "/home/heyuting/anaconda3/envs/spike/lib/python3.8/site-packages/pip/_internal/resolution/resolvelib/found_candidates.py", line 143, in
return (c for c in iterator if id(c) not in self._incompatible_ids)
File "/home/heyuting/anaconda3/envs/spike/lib/python3.8/site-packages/pip/_internal/resolution/resolvelib/found_candidates.py", line 47, in _iter_built
candidate = func()
File "/home/heyuting/anaconda3/envs/spike/lib/python3.8/site-packages/pip/_internal/resolution/resolvelib/factory.py", line 182, in _make_candidate_from_link
base: Optional[BaseCandidate] = self._make_base_candidate_from_link(
File "/home/heyuting/anaconda3/envs/spike/lib/python3.8/site-packages/pip/_internal/resolution/resolvelib/factory.py", line 228, in _make_base_candidate_from_link
self._link_candidate_cache[link] = LinkCandidate(
File "/home/heyuting/anaconda3/envs/spike/lib/python3.8/site-packages/pip/_internal/resolution/resolvelib/candidates.py", line 290, in init
super().init(
File "/home/heyuting/anaconda3/envs/spike/lib/python3.8/site-packages/pip/_internal/resolution/resolvelib/candidates.py", line 156, in init
self.dist = self._prepare()
File "/home/heyuting/anaconda3/envs/spike/lib/python3.8/site-packages/pip/_internal/resolution/resolvelib/candidates.py", line 222, in _prepare
dist = self._prepare_distribution()
File "/home/heyuting/anaconda3/envs/spike/lib/python3.8/site-packages/pip/_internal/resolution/resolvelib/candidates.py", line 301, in _prepare_distribution
return preparer.prepare_linked_requirement(self._ireq, parallel_builds=True)
File "/home/heyuting/anaconda3/envs/spike/lib/python3.8/site-packages/pip/_internal/operations/prepare.py", line 519, in prepare_linked_requirement
metadata_dist = self._fetch_metadata_only(req)
File "/home/heyuting/anaconda3/envs/spike/lib/python3.8/site-packages/pip/_internal/operations/prepare.py", line 371, in _fetch_metadata_only
return self._fetch_metadata_using_link_data_attr(
File "/home/heyuting/anaconda3/envs/spike/lib/python3.8/site-packages/pip/_internal/operations/prepare.py", line 391, in _fetch_metadata_using_link_data_attr
metadata_file = get_http_url(
File "/home/heyuting/anaconda3/envs/spike/lib/python3.8/site-packages/pip/_internal/operations/prepare.py", line 109, in get_http_url
from_path, content_type = download(link, temp_dir.path)
File "/home/heyuting/anaconda3/envs/spike/lib/python3.8/site-packages/pip/_internal/network/download.py", line 147, in call
for chunk in chunks:
File "/home/heyuting/anaconda3/envs/spike/lib/python3.8/site-packages/pip/_internal/network/utils.py", line 63, in response_chunks
for chunk in response.raw.stream(
File "/home/heyuting/anaconda3/envs/spike/lib/python3.8/site-packages/pip/_vendor/urllib3/response.py", line 622, in stream
data = self.read(amt=amt, decode_content=decode_content)
File "/home/heyuting/anaconda3/envs/spike/lib/python3.8/site-packages/pip/_vendor/urllib3/response.py", line 587, in read
raise IncompleteRead(self._fp_bytes_read, self.length_remaining)
File "/home/heyuting/anaconda3/envs/spike/lib/python3.8/contextlib.py", line 131, in exit
self.gen.throw(type, value, traceback)
File "/home/heyuting/anaconda3/envs/spike/lib/python3.8/site-packages/pip/_vendor/urllib3/response.py", line 443, in _error_catcher
raise ReadTimeoutError(self._pool, None, "Read timed out.")
pip._vendor.urllib3.exceptions.ReadTimeoutError: HTTPSConnectionPool(host='files.pythonhosted.org', port=443): Read timed out.安装超时