def index_copy_inplace_nograd(x, dim, index, tensor): query_key = [] for k in range(dim): query_key.append(None) if isinstance(index, Tensor): index = index.long() query_key.append(index) query_key = paddle.concat(query_key) paddle.scatter_(x, query_key, tensor) return x
def scatter_add_(self, dim,index, updates ): assert dim==0, "scatter_add_, no support dim>0" if "64" in str(updates.dtype): updates=updates.astype("float32") if "64" in str(self.dtype): self=self.astype("float32") if len(index.shape)==1: paddle.scatter_(self, index , updates.astype("float32"), overwrite=False) else: for ii in range(index.shape[1]): paddle.scatter_(self,index[:,ii],updates.astype("float32"),overwrite=False) return self
def __setitem__(self, key, value): if isinstance(key,tuple): if len(key)==2: return super(Tensor,self).__setitem__(key,value) if isinstance(key,int): return super(Tensor, self).__setitem__(key, value) def convert_key_to_inttensor(key): if isinstance(key, np.ndarray): # print(max(args),min(args),self.shape,len(args),len(set(args)) ) key=paddorch.from_numpy(key).long() # print("converted numpy", type(args)) if isinstance(key,paddle.Tensor): if key.dtype==paddle.fluid.core.VarDesc.VarType.BOOL: key = paddle.masked_select(paddle.arange(len(key)), key) elif key.dtype==paddle.fluid.core.VarDesc.VarType.INT32 or key.dtype==paddle.fluid.core.VarDesc.VarType.INT64: return key else: return key.astype("int32") if isinstance(key,int): return paddorch.LongTensor(np.array([key])) if isinstance(key,list): key = paddorch.from_numpy(key).long() return key if isinstance(key, np.ndarray) or isinstance(key,paddle.Tensor): key = convert_key_to_inttensor(key) elif isinstance(key,Iterable) : if isinstance(key[0],slice): return super(Tensor, self).__setitem__(key, value) key2=[] for i in range(len(key)): key2.append(convert_key_to_inttensor(key[i])) key=paddle.stack(key2,axis=1) if len(key2)==1: key= key.reshape([-1]) else: key=convert_key_to_inttensor(key) if key.shape[0]==0: ##empty selection, do nothing return self if not isinstance(value,paddle.Tensor): value=paddle.ones_like(key)*float(value) return paddle.scatter_(self,key,value)
def inplace_api_processing(self, var): index = paddle.to_tensor([2, 1, 0, 1], dtype='int64') updates = paddle.to_tensor( [[1, 1], [2, 2], [3, 3], [4, 4]], dtype='float32') return paddle.scatter_(var, index, updates, overwrite=False)