clone()是不内存共享的。
clone()得到的Tensor不仅拷贝了原始的value,而且会计算梯度传播信息,copy_()只拷贝数值。对b处理,grad会返回到a身上。但是b 不会有 grad 属性。
b = a.clone()#a经过克隆得到b,
c = (b ** 2).mean()#
c.backward()
print('a_grad:', a.grad)#但是梯度传播没有因此中断
a_grad: tensor([ 0.4000, 0.8000, 1.2000, 1.6000, 2.0000])
1
So if you want to copy a tensor and detach from the computation graph you should be using
y = x.clone().detach()
Since it is the cleanest and most readable way. With all other version there is some hidden logic and it is also not 100% clear what happens to the computation graph and gradient propagation.
x.data 与 x.detach() 返回的 tensor 有相同的地方, 也有不同的地方:
相同:
都和 x 共享同一块数据
都和 x 的 计算历史无关
requires_grad = False
不同:
y=x.data 在某些情况下不安全, 某些情况, 指的就是 上述 inplace operation 的第二种情况
detach用法:
如果我们有两个网络 A,B , 两个关系是这样的 y=A(x),z=B(y) 现在我们想用 z.backward() 来为 B 网络的参数来求梯度,但是又不想求 A 网络参数的梯度。
#y=A(x), z=B(y) 求B中参数的梯度,不求A中参数的梯度
#第一种方法
y = A(x)
z = B(y.detach())
z.backward()