PyTorch:如何绕过运行时错误:就地操作只能用于不与任何其他变量共享存储的变量



使用 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 之间的区别在于,在第一种情况下,b 被添加到就地(因此 a 的内容更改为现在包含 a+b(。在第二种情况下,创建一个包含 a+b 的全新张量,然后将这个新张量分配给名称 a。 为了能够计算梯度,有时需要保留 a 的原始值,因此我们阻止就地操作,否则我们将无法计算梯度。

相关内容

最新更新