1. 程式人生 > 程式設計 >解決Pytorch自定義層出現多Variable共享記憶體錯誤問題

解決Pytorch自定義層出現多Variable共享記憶體錯誤問題

錯誤資訊:

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,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,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,-1).t())

grad_swapped_weighted = grad_swapped_weighted.t().contiguous().view(1,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[:,:],所以這裡的解決方案是:

 @staticmethod
 def backward(ctx,:]
  # 這兩個後面修改值了,所以也要加clone,防止它們與grad_output共享記憶體
  grad_latter_all = grad_output[:,:].clone()
  grad_swapped_all = grad_output[:,:].clone()

  spatial_size = ctx.h * ctx.w

  W_mat_all = Variable(ctx.Tensor(ctx.bz,-1).t())

   grad_swapped_weighted = grad_swapped_weighted.t().contiguous().view(1,grad_swapped_weighted.mul(ctx.triple_w))

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

  return grad_input,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

以上這篇解決Pytorch自定義層出現多Variable共享記憶體錯誤問題就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。