ImportError: cannot import name ‘container_abcs‘ from ‘torch._six‘

导入apex时出错

import apex

错误信息:

Traceback (most recent call last):
  File "", line 1, in 
  File "/mnt/lustre/chenshoufa/anaconda3/envs/pytorch18/lib/python3.8/site-packages/apex/__init__.py", line 8, in 
    from . import amp
  File "/mnt/lustre/chenshoufa/anaconda3/envs/pytorch18/lib/python3.8/site-packages/apex/amp/__init__.py", line 1, in 
    from .amp import init, half_function, float_function, promote_function,\
  File "/mnt/lustre/chenshoufa/anaconda3/envs/pytorch18/lib/python3.8/site-packages/apex/amp/amp.py", line 1, in 
    from . import compat, rnn_compat, utils, wrap
  File "/mnt/lustre/chenshoufa/anaconda3/envs/pytorch18/lib/python3.8/site-packages/apex/amp/rnn_compat.py", line 1, in 
    from . import utils, wrap
  File "/mnt/lustre/chenshoufa/anaconda3/envs/pytorch18/lib/python3.8/site-packages/apex/amp/wrap.py", line 3, in 
    from ._amp_state import _amp_state
  File "/mnt/lustre/chenshoufa/anaconda3/envs/pytorch18/lib/python3.8/site-packages/apex/amp/_amp_state.py", line 14, in 
    from torch._six import container_abcs
ImportError: cannot import name 'container_abcs' from 'torch._six' (/mnt/lustre/chenshoufa/anaconda3/envs/pytorch18/lib/python3.8/site-packages/torch/_six.py)

解决思路:

出错的原因是torch不同版本中container_abcs导入差异导致的。因为1.8版本之后container_abcs就已经被移除了。cannot import name 'container_abcs' from 'torch._six'

在使用一些开源代码的时候,可能会遇到该错误。解决方法也很简单我们只需要给它更新。

例如在apex/amp/_amp_state.py中

TORCH_MAJOR = int(torch.__version__.split('.')[0])
TORCH_MINOR = int(torch.__version__.split('.')[1])
if TORCH_MAJOR == 0:
    import collections.abc as container_abcs
else:
    from torch._six import container_abcs
    

改为:

TORCH_MAJOR = int(torch.__version__.split('.')[0])
TORCH_MINOR = int(torch.__version__.split('.')[1])
if TORCH_MAJOR == 1 and TORCH_MINOR < 8:
    from torch._six import container_abcs
else:
    import collections.abc as container_abcs

参考:

关于升级pytorch1.9后出现cannot import name ‘container_abcs‘ from ‘torch._six‘错误的解决方法_星辰辰大海的博客-CSDN博客

你可能感兴趣的:(Python,pytorch,人工智能,python,apex)