RuntimeError: expected scalar type Half but found Float

起因:将CCNet的十字交叉注意力模块移植到YOLOv5中。

经过:在注意力模块中,会有较多的矩阵运算,在训练时出现了cuda和cup类型的冲突(另一篇我写的文章);而在验证时出现了上述错误。

出错的代码如下:

        # [b1*w1, c1, h1] -> [b1, w1, c1, h1] -> [b1, c1, h1, w1]
        out_H = torch.bmm(value_H, att_H.permute(0, 2, 1)).view(b1, w1, -1, h1).permute(0, 2, 3, 1)
        # [b1 * h1, c1, w1] -> [b1, h1, c1, w1] -> [b1, c1, h1, w1]
        out_W = torch.bmm(value_W, att_W.permute(0, 2, 1)).view(b1, h1, -1, w1).permute(0, 2, 1, 3)

出错的位置在torch.bmm()处,在这里进行了一次矩阵乘法运算。由于两个数据的类型不同,因此发生冲突。

解决方案:仍然是用to()方法,修改数据类型为另一个数据的类型。

        # [b1*w1, c1, h1] -> [b1, w1, c1, h1] -> [b1, c1, h1, w1]
        out_H = torch.bmm(value_H, att_H.permute(0, 2, 1).to(value_H.dtype)).view(b1, w1, -1, h1).permute(0, 2, 3, 1)
        # [b1 * h1, c1, w1] -> [b1, h1, c1, w1] -> [b1, c1, h1, w1]
        out_W = torch.bmm(value_W, att_W.permute(0, 2, 1).to(value_W.dtype)).view(b1, h1, -1, w1).permute(0, 2, 1, 3)

文章出处登录后可见!

已经登录?立即刷新

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
扎眼的阳光的头像扎眼的阳光普通用户
上一篇 2023年7月6日
下一篇 2023年7月6日

相关推荐