Pytorch学习 ( 十三 ) ----- Pytorch自定义层出现多Variable共享内存错误

25 篇文章 27 订阅
在Pytorch中,由于in-place操作、indexing或转置可能导致多个Variable共享内存,从而在自动求导时引发RuntimeError。错误信息表明存在4个对象共享同一内存。解决此类问题通常需要确保变量独立,例如通过深拷贝避免内存共享。文中通过具体示例分析了错误原因,并提出了避免错误的方法。
摘要由CSDN通过智能技术生成

错误信息: RuntimeError: in-place operations can be only used on variables that don’t share storage with any other variables, but detected that there are 4 objects sharing it

自动求导是很方便, 但是想想, 如果两个Variable共享内存, 再对这个共享的内存的数据进行修改, 就会引起错误!
一般是由于 inplace操作或是indexing或是转置. 这些都是共享内存的.

    @staticmethod
    def backward(ctx, grad_output):
        ind_lst = ctx.ind_lst
        flag = ctx.flag

        c = grad_output.size(1)
        grad_former_all = grad_output[:, 0:c//3, :, :]
        grad_latter_all = grad_output[:, c//3: c*2//3, :, :]
        grad_swapped_all = grad_output[:, c*2//3:c, :, :]

        spatial_size = ctx.h * ctx.w

        W_mat_all = Variable(ctx.Tensor(ctx.bz, spatial_size, spatial_size).zero_())
        for idx in range(ctx.bz):
            W_mat = W_mat_all.select(0,idx)
            for cnt in range(spatial_size):
                indS = ind_lst[idx][cnt] 

                if flag[cnt] == 1:
                    # 这里W_mat是W_mat_all通过select出来的, 他们共享内存.
                    W_mat[cnt, indS] = 1

            W_mat_t = W_mat.t()

            grad_swapped_weighted = torch.mm(W_mat_t, grad_swapped_all[idx].view(c//3, -1).t())
            grad_swapped_weighted = grad_swapped_weighted.t().contiguous().view(1, c//3, ctx.h, ctx.w)
            grad_latter_all[idx] = torch.add(grad_latter_all[idx], grad_swapped_weighted.mul(ctx.triple_w))

由于 这里W_matW_mat_all通过select出来的, 他们共享内存. 所以当对这个共享的内存进行修改W_mat[cnt, indS] = 1, 就会出错. 此时我们可以通过clone()W_matW_mat_all独立出来. 这样的话, 梯度也会通过 clone()操作将W_mat的梯度正确反传到W_mat_all中.

    @staticmethod
    def backward(ctx, grad_output):
        ind_lst = ctx.ind_lst
        flag = ctx.flag

        c = grad_output.size(1)
        grad_former_all = grad_output[:, 0:c//3, :, :]
        grad_latter_all = grad_output[:, c//3: c*2//3, :, :]
        grad_swapped_all = grad_output[:, c*2//3:c, :, :]

        spatial_size = ctx.h * ctx.w

        W_mat_all = Variable(ctx.Tensor(ctx.bz, spatial_size, spatial_size).zero_())
        for idx in range(ctx.bz):
            # 这里使用clone了
            W_mat = W_mat_all.select(0,idx).clone()
            for cnt in range(spatial_size):
                indS = ind_lst[idx][cnt]

                if flag[cnt] == 1:
                    W_mat[cnt, indS] = 1

            W_mat_t = W_mat.t()

            grad_swapped_weighted = torch.mm(W_mat_t, grad_swapped_all[idx].view(c//3, -1).t())
            grad_swapped_weighted = grad_swapped_weighted.t().contiguous().view(1, c//3, ctx.h, ctx.w)

            # 这句话删了不会出错, 加上就吹出错
            grad_latter_all[idx] = torch.add(grad_latter_all[idx], grad_swapped_weighted.mul(ctx.triple_w))

但是现在却出现 4个objects共享内存. 如果将最后一句话删掉, 那么则不会出错.
如果没有最后一句话, 我们看到

grad_swapped_weighted = torch.mm(W_mat_t, grad_swapped_all[idx].view(c//3, -1).t())
grad_swapped_weighted = grad_swapped_weighted.t().contiguous().view(1, c//3, ctx.h, ctx.w)

grad_swapped_weighted 一个新的Variable, 因此并没有和其他Variable共享内存, 所以不会出错. 但是最后一句话,

grad_latter_all[idx] = torch.add(grad_latter_all[idx], grad_swapped_weighted.mul(ctx.triple_w))

你可能会说, 不对啊, 修改grad_latter_all[idx]又没有创建新的Variable, 怎么会出错. 这是因为grad_latter_allgrad_output是共享内存的. 因为 grad_latter_all = grad_output[:, c//3: c*2//3, :, :], 所以这里的解决方案是:

    @staticmethod
    def backward(ctx, grad_output):
        ind_lst = ctx.ind_lst
        flag = ctx.flag

        c = grad_output.size(1)
        grad_former_all = grad_output[:, 0:c//3, :, :]
        # 这两个后面修改值了, 所以也要加clone, 防止它们与grad_output共享内存
        grad_latter_all = grad_output[:, c//3: c*2//3, :, :].clone()
        grad_swapped_all = grad_output[:, c*2//3:c, :, :].clone()

        spatial_size = ctx.h * ctx.w

        W_mat_all = Variable(ctx.Tensor(ctx.bz, spatial_size, spatial_size).zero_())
        for idx in range(ctx.bz):
            W_mat = W_mat_all.select(0,idx).clone()
            for cnt in range(spatial_size):
                indS = ind_lst[idx][cnt]

                if flag[cnt] == 1:
                    W_mat[cnt, indS] = 1

            W_mat_t = W_mat.t()

            grad_swapped_weighted = torch.mm(W_mat_t, grad_swapped_all[idx].view(c//3, -1).t())

            grad_swapped_weighted = grad_swapped_weighted.t().contiguous().view(1, c//3, ctx.h, ctx.w)
            grad_latter_all[idx] = torch.add(grad_latter_all[idx], grad_swapped_weighted.mul(ctx.triple_w))

        grad_input = torch.cat([grad_former_all, grad_latter_all], 1)

        return grad_input, None, None, None, None, None, None, None, None, None, None
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值