【发布时间】:2020-07-31 03:03:48
【问题描述】:
我需要将代码 pytorch 转移到 tensorflow 这个pytorch代码在这里NADST
encoded_context = ft['encoded_context2']
encoded_in_domainslots = ft['encoded_in_domainslots2']
self.pointer_attn(ft['out_states'], encoded_context, encoded_context, context_mask)
pointer_attn = self.pointer_attn.attn.squeeze(1)
p_vocab = F.softmax(vocab_attn, dim = -1)
context_index = context.unsqueeze(1).expand_as(pointer_attn)
p_context_ptr = torch.zeros(p_vocab.size()).cuda()
p_context_ptr.scatter_add_(2, context_index, pointer_attn)
我想把代码"p_context_ptr.scatter_add_(2, context_index, pointer_attn)"改成tensorflow版本。
所以我使用了tensorflow函数的“tf.compat.v1.tensor_scatter_nd_add()”,但不是同一个操作torch scatter_add_()函数
我一直在尝试工作直到现在,但我的一些代码没有找到解决方案
def get_scatter_add(tensor, indices, updates):
if indices.shape.rank > 2:
tensor = tf.compat.v1.reshape(tensor, shape=[-1, tensor.shape[-1]])
indices = tf.compat.v1.reshape(indices, shape=[-1, indices.shape[-1]])
updates = tf.compat.v1.reshape(updates, shape=[-1, updates.shape[-1]])
one_hot_index = tf.compat.v1.one_hot(indices=indices, depth=tensor.shape[-1])
tile_update = tf.compat.v1.expand_dims(updates, axis=-1)
updates = tf.compat.v1.to_float(one_hot_index) * tf.compat.v1.to_float(tile_update)
indices = tf.compat.v1.expand_dims(indices, axis=-1)
update = tensor.shape[indices.shape[-1]:]
res = indices.shape[:-1] + update
scatter = tf.compat.v1.tensor_scatter_nd_add(tensor, indices, updates)
return scatter
但是,内存溢出,我的变量形状是 tensor.shape()->[1100, 19200], update.shape()->[1100, 900], updates.shape()->[1100 , 900]
这个问题怎么解决???
感谢您的回复
祝你有美好的一天!!!
【问题讨论】:
标签: python tensorflow