PyTorch: How to get around the RuntimeError: in-place operations can be only used on variables that don't share storage with any other variables

PyTorch: How to get around the RuntimeError: in-place operations can be only used on variables that don't share storage with any other variables

使用 PyTorch 我在使用两个变量进行操作时遇到问题:

sub_patch  : [torch.FloatTensor of size 9x9x32]

pred_patch : [torch.FloatTensor of size 5x5x32]

sub_patch 是由 torch.zeros 创建的变量 pred_patch 是一个变量,我用一个嵌套的 for 循环为 25 个节点中的每一个节点编制索引,然后我将其与其相应的大小为 [5,5,32] 的唯一过滤器 (sub_filt_patch) 相乘。结果被添加到 sub_patch.

中的相应位置

这是我的一段代码:

for i in range(filter_sz):
    for j in range(filter_sz):

        # index correct filter from filter tensor
        sub_filt_col = (patch_col + j) * filter_sz
        sub_filt_row = (patch_row + i) * filter_sz

        sub_filt_patch = sub_filt[sub_filt_row:(sub_filt_row + filter_sz), sub_filt_col:(sub_filt_col+filter_sz), :]

        # multiply filter and pred_patch and sum onto sub patch
        sub_patch[i:(i + filter_sz), j:(j + filter_sz), :] += (sub_filt_patch * pred_patch[i,j]).sum(dim=3)

我从这段代码的底线得到的错误是

RuntimeError: in-place operations can be only used on variables that don't share storage with any other variables, but detected that there are 2 objects sharing it

我知道为什么会这样,因为 sub_patch 是一个变量,pred_patch 也是一个变量,但是我该如何解决这个错误?任何帮助将不胜感激!

谢谢!

我发现问题出在

        sub_patch[i:(i + filter_sz), j:(j + filter_sz), :] += (sub_filt_patch * pred_patch[i,j]).sum(dim=3)

将此行分隔为:

sub_patch[i:(i + filter_sz), j:(j + filter_sz), :] = sub_patch[i:(i + filter_sz), j:(j + filter_sz), :] + (sub_filt_patch * pred_patch[i,j]).sum(dim=3)

然后成功了!

a += b 和a = a + b 的区别在于,第一种情况是在a inplace 中添加了b(因此a 的内容改为现在包含a+b)。在第二种情况下,创建了一个包含 a+b 的全新张量,然后将这个新张量分配给名称 a。 为了能够计算梯度,您有时需要保留 a 的原始值,因此我们阻止进行就地操作,否则我们将无法计算梯度。