欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

RuntimeError: a leaf Variable that requires grad has been used in an in-place operation

程序员文章站 2022-06-15 19:23:08
...

Traceback (most recent call last):
File “E:\迅雷下载\向量\000、代码+数据+课件\YOLO5\yolov5-master\train.py”, line 466, in
train(hyp, opt, device, tb_writer)
File “E:\迅雷下载\向量\000、代码+数据+课件\YOLO5\yolov5-master\train.py”, line 79, in train
model = Model(opt.cfg, ch=3, nc=nc).to(device) # create 灏辨槸鍜变滑涔嬪墠璁茬殑鍒涘缓妯″瀷閭e潡
File “E:\迅雷下载\向量\000、代码+数据+课件\YOLO5\yolov5-master\models\yolo.py”, line 89, in init
self._initialize_biases() # only run once
File “E:\迅雷下载\向量\000、代码+数据+课件\YOLO5\yolov5-master\models\yolo.py”, line 149, in _initialize_biases
b[:, 4] =b[:, 4]+ math.log(8 / (640 / s) ** 2) # obj (8 objects per 640 image)
RuntimeError: a view of a leaf Variable that requires grad is being used in an in-place operation.

解决办法:
叶子节点不能执行in-place(原地)操作,因为在进行前向传播的时候得到的是叶子结点的地址,再进行反向传播的时候这个地址不变才不会报错,地址改变了就会出错

要将

a += torch.ones((1, ))

改为

a = a + torch.ones((1, ))

原代码:

for mi, s in zip(m.m, m.stride):  #  from
            b = mi.bias.view(m.na, -1)  # conv.bias(255) to (3,85)
            b[:, 4]+= math.log(8 / (640 / s) ** 2)  # obj (8 objects per 640 image)
            b[:, 5:]+= math.log(0.6 / (m.nc - 0.99)) if cf is None else torch.log(cf / cf.sum())  # cls
            mi.bias = torch.nn.Parameter(b.view(-1), requires_grad=True)

本错误的解决办法:

 for mi, s in zip(m.m, m.stride):  #  from
            b = mi.bias.view(m.na, -1)  # conv.bias(255) to (3,85)
            bb = b[:, 4]
            bb = bb + math.log(8 / (640 / s) ** 2)  # obj (8 objects per 640 image)
            bbb = b[:, 5:]
            bbb = bbb + math.log(0.6 / (m.nc - 0.99)) if cf is None else torch.log(cf / cf.sum())  # cls
            mi.bias = torch.nn.Parameter(b.view(-1), requires_grad=True)
相关标签: bug