Pytorch遇到的错误及解决方法

1、RuntimeError: CUDA error: device-side assert triggered


使用pytorch的时候报这个错误说明你label中有些指不在[0, num classes), 区间左闭右开。比如类别数num_class=3, 你的label出现了-1或者3, 4, 5等!!!!

2、RuntimeError:invalid argument 5:k not in range for dimension at /pytorch/ate ... 


训练只有3类,没办法算top5,所以需要修改计算acc时候的topk=(1,3);

3、ValueError: optimizer got an empty parameter list


出现这个问题,很多原因,但是主要原因就是网络定义的不好,有些层没有加进来,或者被改掉了;model.parameters()这个 是看到torch提供的借口里面定义的结构,应该外面也可以,至于加载不进来,和使用了特殊的方法有关,如下: def get_optimizer(model, args): parameters = [] # for name, param in model.named_parameters(): # if 'fc' in name or 'class' in name or 'last_linear' in name or 'ca' in name or 'sa' in name: # parameters.append({'params': param, 'lr': args.base_lr * args.lr_fc_times}) # else: # parameters.append({'params': param, 'lr': args.base_lr}) # parameters = model.parameters() if args.optimizer == 'sgd': optimizer = torch.optim.SGD(model.parameters(), lr=args.base_lr, momentum=args.momentum, weight_decay=args.weight_decay) # return torch.optim.SGD(parameters, # # model.parameters(), # args.base_lr, # momentum=args.momentum, nesterov=args.nesterov, # weight_decay=args.weight_decay) 对的,正常你定义一个模型,如resnet,是可以使用for name, param in model.named_parameters(): 并且,nesterov=args.nesterov这个参数也有问题,即不能够随便乱用。 当然,

4、The size of tensor a (197) must match the size of tensor b (257) at non-singleton dimension 1


这个就是维度对不上,一般就是几个错误,数据维度跟网络为度不一致,数据要能够被batch整除,一个就是对dataloader的一个参数drop_last=False; 当然,如果你网络定义有错误,即中间层每层输入,和输出的维度不一致,就是网络在forward操作过程中没对齐,没做好。还是网络问题。

5、RuntimeError: version_ <= kMaxSupportedFileFormatVersion INTERNAL ASSERT FAILED at /pytorch/caffe2/serialize/inline_container.cc:132, please report a bug to PyTorch. Attempted to read a PyTorch file with version 3, but the maximum supported version for reading is 2. Your PyTorch installation may be too old. (init at /pytorch/caffe2/serialize/inline_container.cc:132)
 

pytorch load模型参数(.pth),RuntimeError: version_ <= kMaxSupportedFileFormatVersion INTERNAL ASSERT FAIL 原因:使用较高版本的pytorch训练得到的模型,在低版本的ptorch中load时,存在的版本问题。 我使用1.6.0版本训练的模型,在1.4.0中是load不了的。 解决:升级版本或者使用低版本训练。要不找个一种兼容的保持和读取方法。 升级到1.6就行,但是需要注意的是ddp可能也会有问题,如下面,

6、RuntimeError: Expected to have finished reduction in the prior iteration before starting a new one. This error indicates that your module has parameters that were not used in producing loss. You can enable unused parameter detection by (1) passing the keyword argument `find_unused_parameters=True` to `torch.nn.parallel.DistributedDataParallel`; (2) making sure all `forward` function outputs participate in calculating loss. If you already have done the above two steps, then the distributed data parallel module wasn't able to locate the output tensors in the return value of your module's `forward` function. Please include the loss function and the structure of the return value of `forward` of your module when reporting this issue (e.g. list, dict, iterable).


在DistributedDataParallel 中加入find_unused_parameters=True model = torch.nn.parallel.DistributedDataParallel(model,device_ids=[args.local_rank],output_device=args.local_rank, find_unused_parameters=True)

7、Setting OMP_NUM_THREADS environment variable for each process to be 1 in def


OMP_NUM_THREADS 用于控制线程并发数. 测试条件:单个循环请求,持续时间大于15m; 基础数据:200w 软件环境:docker; ubuntu 16.04 ;python2.7; faiss:1.4.0-cpu 检索服务功能: (汉明距离计算 + 欧式距离计算 ) OMP 设置线程的3种方法 设置线程的3种方法 1. 在子语句 data clause 中设置 : num_threads( ) #pragma omp parallel for default(none) shared(x) private (i) num_threads(3) for(i=0; i<10; i++){ x[i]=i; } 2. 在 run time 函数库中设置 : omp_set_num_threads( ) omp_set_num_threads(2) #pragma omp parallel for default(none) shared(x) private (i) for(i=0; i<10; i++){ x[i]=i; } 3. 在环境变量中设置environment variables 在命令窗口中配置 : export OMP_NUM_THREADS = 3 module load intel //call intel module icc -0 -qopenmp myOMP.c -o myOMP.exe //compile export OMP_NUM_THREADS=3 ./myOMP.exe //run Summary: 1、2、3 优先级依次降低的,也就是前面的设置可以覆盖后面的设置,当然也是相对而言,num_threads子句只会影响当前的并行区域,而omp_set_num_threads对OMP_NUM_THREADS环境变量的覆盖是在整个程序运行期间全局的。

8、'NoneType' object has no attribute 'parameters' model.parameters()


这个问题是python变量的问题,即model是一个NoneType的类型,这是一个空类型,说明你的model是一个空的,没有在调用的地方进行返回实际的对象。 然后就引发了一系列利用到model的属性出错的问题。 不用怀疑问题是出现在了model没有了paramenters的问题,这个方法是获取model的一个value,通常是一个generate,区别于state_dict是后者是一个dict,还有key的属性,类似的方法有name_paramenters()

9、view size is not compatible with input tensor's size and stride (at least one dimension spans across


原因:用多卡训练的时候tensor不连续,即tensor分布在不同的内存或显存中。 解决方法:对tensor进行操作时先调用contiguous()。如tensor.contiguous().view()。

10、semaphore_tracker: There appear to be 11 leaked semaphores to clean up at shutdown


最近在跑代码的时候总是会遇到这个错误,明明是UserWarning,但是程序会停止运行,错误提示为 multiprocessing/semaphore_tracker.py:144: UserWarning: semaphore_tracker: There appear to be 4 leaked semaphores to clean up at shutdown len(cache)) 查了很多资料,这个问题似乎很早之前就有,最早能找到的是在2013年,但是没有什么很好的解决方法,最终发现,需要忽略这个警告就可以了,在运行代码之前加入这一句,希望能帮到大家,我被这个错误耽误了太长时间了 export PYTHONWARNINGS='ignore:semaphore_tracker:UserWarning'

11、ImportError: libGL.so.1: cannot open shared object file: No such file or directory


想要一块小小的GPU做推断和测试都无法满足。。。唯一一块卡还被业务拿走了。。。 强烈建议能够给深度学习工作的小伙伴,配置一块淘汰下来的卡,1080也行啊。。。服务器长期被霸占,还咋个玩,夹缝中求生存。 在新的docker中import的时候出现如下问题: ImportError: libGL.so.1: cannot open shared object file: No such file or directory 其实就是新容器缺少依赖,安装一下就行了 apt update apt install libgl1-mesa-glx

12、RuntimeError: cuda runtime error (11) : invalid argument at /opt/conda/conda-bld/pytorch_1535491974311/work/aten/src/THC/THCGeneral.cpp:663


这是一个老问题了。主要原因是pytorch和cuda版本太老,而你用的硬件确实蛋疼的2080ti。 一般是pytorch你用了0.4.1,是基于cuda9.0或者9.2 为什么不能升级,主要是因为DCNv2这种卷积改写了cuda代码,才能够实现梯度计算。这种操作pytorch不支持 自动梯度更新。 但是作者既然已经更新了DCNv2的cuda代码,即支持了pytorch>1.X版本,那么你要升级代码,其他模块最多是 接口或者方法调用上有区别,这些是都可以改的。 解决办法如下: 方法1: I have the same issue. RTX2080, for CUDA 10.0 and pytorch 1.0.0. Anyone has solved the same problem please provide the information of the solution. It would help a lot of people. Thanks! Okay I have solve the problem. You cannot directly install pytorch, instead “pip3 install -U https://download.pytorch.org/whl/cu100/torch-1.0.0-cp36-cp36m-linux_x86_64.whl” work for me. 或者你手动下载,然后用 python3.6 -m pip install https://download.pytorch.org/whl/cu100/torch-1.0.0-cp36-cp36m-linux_x86_64.whl 安装好对应版本的pytorch以后,然后参考如下: 7- cd /CenterNet/src/lib/models/networks rm -r DCNv2 git clone https://github.com/CharlesShang/DCNv2.git cd /CenterNet/src/lib/models/networks/DCNv2 python setup.py build develop 即安装新的支持了pytorch>1.X版本。 然后对于BN: Disable cudnn batch normalization(follow [CenterNet](https://github.com/xingyizhou/pytorch-pose-hg-3d/issues/16)). ~~~powershell # PYTORCH=/path/to/pytorch # usually ~/anaconda3/envs/MOC/lib/python3.5/site-packages/ # for pytorch v0.4.1 sed -i "1254s/torch\.backends\.cudnn\.enabled/False/g" ${PYTORCH}/torch/nn/functional.py ~~~ For other pytorch version, you can manually open `torch/nn/functional.py` and find the line with `torch.batch_norm` and replace the `torch.backends.cudnn.enabled` with `False`. OK!!!搞定。 按照道理来讲,这个问题就是DCN的问题,那么对于pytorch按照它说的,只要>1.X不死活都行吗,可以验证一下。 验证结果是,的确是,现在的pytorch版本是1.4.所以网上的答案都是垃圾吧。

13、[PyTorch] IndexError: Dimension out of range (expected to be in range of [-1, 0], but got 1 Process finished with exit code 1

其实问题很明显,就是这个操作ret = input.log_softmax(dim)不支持batch_size=1的操作。 解决办法就是让batch_size>1.

14.pytorch报错:ValueError: Expected more than 1 value per channel when training, got input size torch.Size([1,512,1,1])


网上查找的原因为模型中用了batchnomolization,训练中用batch训练的时候当前batch恰好只含一个sample,而由于BatchNorm操作需要多于一个数据计算平均值,因此造成该错误。 3.解决方法:在torch.utils.data.DataLoader类中或自己创建的继承于DataLoader的类中设置参数drop_last=True,把不够一个batch_size的数据丢弃。 成功解决。

15.RuntimeError: zero-dimensional tensor (at position 0) cannot be concatenated


简单就是转位int,再使用torch.tensor([x]]) torch.cat() 函数传入的tuple里面的tensor维度不可以为0,而我们直接创建一个非list的tensor的时候,就有了zero-dimensional tensor, 这在pytorch0.3 版本没有什么问题,但pytorch0.4版本中,加入了zero-dimensional tensor 的概念,做出了区分。 之所以会这样,是因为我想要做concatenate操作的是一个tensor的浮点型数据,loss.data, 而loss.data 是一个tensor()类型, 跟tensor([])类型是完全不一样的!

16.object of type <class 'numpy.float64'> cannot be safely interpreted as an integer.
错误详情 在使用pycocotools的时候报TypeError: object of type <class 'numpy.float64'> cannot be safely interpreted as an integer.

解决办法 这个原因应该是numpy更新以后导致的; 1.通过上面的信息可以看到,错误原因是cocoeval.py中的np.linspace函数导致的,发生这个原因是因为np.linspace函数的num参数不支持float类型导致的,找到lib/python3.6/site-packages/pycocotools下的cocoeval.py文件,将507行改成如下 self.iouThrs = np.linspace(.5, 0.95, int(np.round((0.95 - .5) / .05)) + 1, endpoint=True) 原来的是:self.iouThrs = np.linspace(.5, 0.95, np.round((0.95 - .5) / .05) + 1, endpoint=True);具体就是进行int将float强制转换 2.或者安装numpy的1.11.0的版本 如:pip install numpy==1.16

17.RuntimeError: Expected object of scalar type Long but got scalar type Float for argument #2 'target' in call to _thnn_nll_loss_forward


导致这个问题,一般是你重新处理过label;并非由dataloader返回的。比如无监督学习当中你生成了一个label的编码。 在用pytorch的时候,报错RuntimeError: Expected object of scalar type Long but got scalar type Float for argument #2 'target'。研究了一下,发现是关于label的错误。修改办法总结一下: 1、RuntimeError: Expected object of scalar type Long but got scalar type Float for argument #2 'target',在这个报错中,标红的地方是关键,找到程序中的label,比如说在loss处,如下所示: Loss = torch.nn.CrossEntropyLoss() loss = Loss(out, label) 修改的时候,直接在label后面加上.long(),如下所示: Loss = torch.nn.CrossEntropyLoss() loss = Loss(out, label.long()) 2、多次报这个错误后发现,它说是什么类型,直接在label后面加上对应的类型即可。

18.tensorboard ValueError: Duplicate plugins for name projector


解决方案:去torch安装路径的site-packages文件夹下, 删掉tensorboard--2.0.0dist-info  造成的原因是安装了多个版本,然后冲突了。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值