[英]How to swap values in PyTorch tensor without using in-place operation (conserve gradient)
我有一個名為state
的張量,形狀為torch.Size([N, 2**n, 2**n])
,我想應用以下操作:
state[[0,1]] = state[[1,0]]
state[0] = -1*state[0]
這兩個都是就地操作。 是否有一些不合適的操作可以替代它們? 這些行位於 for-loop 內,因此僅創建新變量會有點困難。
我設法弄明白了!
代替:
state[[0,1]] = state[[1,0]] # in-place operation
和:
state = state[[1,0]] # out-of-place operation
對於第二行,我們替換:
state[0] = -1*state[0] # in-place operation
和:
# out-of-place operations
temp = torch.ones(state.shape).type(state.type()).to(state.device)
temp[1] = -1*temp[1]
state = state*temp
這似乎在做這項工作!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.