解决Pytorch自定义层出现多Variable共享内存错误问题
作者:Hungryof 发布时间:2023-12-14 14:43:46
错误信息:
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_mat是W_mat_all通过select出来的, 他们共享内存. 所以当对这个共享的内存进行修改W_mat[cnt, indS] = 1, 就会出错. 此时我们可以通过clone()将W_mat和W_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_all和grad_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
补充知识:Pytorch 中 expand, expand_as是共享内存的,只是原始数据的一个视图 view
如下所示:
mask = mask_miss.expand_as(sxing).clone() # type: torch.Tensor
mask[:, :, -2, :, :] = 1 # except for person mask channel
为了避免对expand后对某个channel操作会影响原始tensor的全部元素,需要使用clone()
如果没有clone(),对mask_miss的某个通道赋值后,所有通道上的tensor都会变成1!
# Notice! expand does not allocate more memory but just make the tensor look as if you expanded it.
# You should call .clone() on the resulting tensor if you plan on modifying it
# https://discuss.pytorch.org/t/very-strange-behavior-change-one-element-of-a-tensor-will-influence-all-elements/41190
来源:https://blog.csdn.net/Hungryof/article/details/80012477
猜你喜欢
- 列表有自己的sort方法,其对列表进行原址排序,既然是原址排序,那显然元组不可能拥有这种方法,因为元组是不可修改的。排序,数字、字符串按照A
- 1.什么是局部视图局部视图是在其他视图中呈现的视图。通过执行局部视图生成的HTML输出呈现在调用视图中。与视图一样,局部视图使用 .csht
- ul: unordered lists ol: ordered lists li: Listsol 有序列表:<ol>
- python中reduce和map简介map(func,seq1[,seq2...]) :将函数func作用于给定序列的每个元素,并用一个列
- 使用JdbcTemplate的步骤1、设置spring-jdbc和spring-tx的坐标(也就是导入依赖) <depen
- 共同点两者都接收两个参数,第一个参数是行的范围,第二个参数是列的范围不同点loc函数接收的是行/列的名称,iloc函数接收的是行/列的下标(
- Python项目中很多时候会需要将时间在Datetime格式和TimeStamp格式之间转化,又或者你需要将UTC时间转化为本地时间,本文总
- 一、表命令1.查看所有表show tables;2.创建表CREATE TABLE table_name ( co
- 很多人认为python中的字典是无序的,因为它是按照hash来存储的,但是python中有个模块collections(英文,收集、集合),
- 本文实例讲述了mysql、mssql及oracle分页查询方法。分享给大家供大家参考。具体分析如下:分页查询在web开发中是最常见的一种技术
- 在用ThinkPHP做tags标签的时候,出现了一个问题,就是能获取到参数,但是查不出相应的结果。查看数据库发现数据是存在的。问题出在哪了呢
- 安装通过 pip 安装 Beautiful Soup 模块:pip install beautifulsoup4 。 还可以使用 PyCha
- Pygame是一个多用于游戏开发的模块。本文实例主要是在演示框里实现一个移动的矩形实例代码,完整代码如下:#moving rectangle
- 前言词云的使用相信大家已经不陌生了,使用很简单,直接调用wordcloud包就可以了。它的主要功能是根据文本词汇和词汇频率生成图片,从中可以
- 很多开发人员在使用MySQL时经常会在部分列上进行函数计算等,导致无法走索引,在数据量大的时候,查询效率低下。针对此种情况本文从MySQL5
- Jupyter Notebook默认不显示行号,可是当我们代码报错时,发现会显示自己多少行出现错误。eg:这时候我们总不能一行行去数吧,因此
- 本文实例为大家分享了Python时间戳使用和相互转换的具体代码,供大家参考,具体内容如下1.将字符串的时间转换为时间戳方法: &n
- python实现取余操作的方法:可以利用求模运算符(%)来实现。求模运算符可以将两个数相除得到其余数。我们还可以使用divmod()函数来实
- 今天发现有一个备份的mysql数据文件夹异常变大,一查发现是多了三个文件:ibdata1 ib_logfile0 ib_logfile1,前
- 先给大家分享JQuery判断radio单选框是否选中并获取值的方法https://www.aspxhome.com/article/1548