2023年11月29日发(作者:)
pytorch使⽤过程中的报错收集(持续更新...)
Tensor
ValueError: only one element tensors can be converted to Python scalars
我在将⼀个list中包含有的tensor转化为LongTensor时报错如上,错误原因是只能将含有⼀个元素的tensor转化为python标量。修改
dim>=2
⽅式为:将list中的tensor改为形式,就可以将这个list转化为Tensor了。
()
el
RuntimeError: Expected object of device type cuda but got device type cpu for argument #1 'self' in call to _th_addmm
这⾥需要查看⾃⼰的tensor是否全部copy⾄gpu。
RuntimeError: arguments are located on different GPUs at /pytorch/aten/src/THC/generic/:270
这⾥还是需要检查⾃⼰的⽹络层定义是否规范。我在这个坑⾥爬了半天,建议⼤家⼀开始写⽹络层时还是多多参考主流代码书写习惯,我就是在⽹
络层⾥乱传tensor,导致⼀开始的tensor由`DataParallel``分配⾄gpu,⾃定义函数⾥的tensor没有被分到和其他参与运算的tensor于同⼀块
gpu。推⼀个该问题的详细解决⽅案:传送门
规范的⽹络层定义格式:
再补充⼀点,由于也是Pytorch的,因此模型和优化器都需要使⽤来定义,⾃定义⽹络层要注意继承,
DataParallel.module
若不想按照规范格式定义的话也可以直接在变量后加。
.module
RuntimeError: module must have its parameters and buffers on device cuda:0 (device_ids[0]) but found one of them on device: cuda:1
该错误定位在没有设定主GPU的ID。我在GPU使⽤过程中选择第3,4块,对应的,因此在调⽤dataParallel时申明:
device_ids = [2,3]
device = ("cuda:{}".format("2,3") if _available())
model = rallel(model, device_ids = [2,3])
注意在tensor定义时需使⽤,不能直接使⽤,因为会默认使⽤gpu0作为主GPU。
(deivce).cuda().cuda()
RuntimeError: expected condition, x and y to be on the same device, but condition is on cuda:2 and x and y are on cuda:1 and cuda:2 respectively
这个错误定位是由于我的tensor1是⽹络输⼊时送⼊的,其他tensor是在训练过程中通过计算得到或模型定义时初始化的,在dataParallel中,各
个tensor被分配的gpu位置不同,从⽽导致这个错误。
处理⽅法是简单粗暴的在tensor后⾯加。
.cuda()
UserWarning: Was asked to gather along dimension 0, but all input tensors were scalars; will instead unsqueeze and return a vector.
说明⼀下:每张卡上的loss都是要汇总到第0张卡上求梯度,更新好以后把权重分发到其余卡。多卡的时候采⽤rallel训练会出现这个
warning,由于计算loss的时候是分别在多卡计算的,那么返回的也就是多个loss,你使⽤了多少个gpu,就会返回多少个loss。但如果使⽤gpu
的数量为单数,这意味着每块gpu处理的batchsize不同,因此在求平均loss可以使⽤作为参数。每个GPU上的
size_average=False,reduce=True
损失将相加,但不除以GPU上的批⼤⼩。然后将所有平⾏损耗相加,除以整批的⼤⼩,那么不管⼏块GPU最终得到的平均loss都是⼀样的。
RuntimeError: CUDA error: device-side assert triggered
index
有溢出。建议⾸要排查预处理代码的索引是否正确。⼀开始遇到这个错误以为是多块GPU并⾏计算⽅⾯的问题,因为我是在tensor操作这
块报错,与百度到的没有从0开始之类的情况不相符,所以⼀开始排查了内存⽅⾯。后来排到还是预处理阶段index设置不规范导致。所以
label id
⼤家还是多去prep阶段找bug呀~
(更新:⼜遇到这个错了,在标签序列⾥设置了-1。难受了,再来记⼀遍。
butedDataParallel
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
ble unused parameter detection by (1) passing the keyword argument `find_unused_parameters=True` to `butedDataParallel`; (2) making sure all `forw
e 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 you


发布评论