有没有办法把pytorch张量转换成张量



https://github.com/taoshen58/BiBloSA/blob/ec67cbdc411278dd29e8888e9fd6451695efc26c/context_fusion/self_attn.py#L29

我需要使用上面在TensorFlow中实现的链接中的mulit_dimensional_attention,但我正在使用PyTorch,所以我可以将PyTorch张量转换为TensorFlow张量吗?或者我必须在PyTorch中实现它。

我试图在这里使用的代码我必须将"rep_tensor"作为TensorFlow张量类型传递,但我有PyTorch张量

def multi_dimensional_attention(rep_tensor, rep_mask=None, scope=None,
keep_prob=1., is_train=None, wd=0., activation='elu',
tensor_dict=None, name=None):
# bs, sl, vec = tf.shape(rep_tensor)[0], tf.shape(rep_tensor)[1], tf.shape(rep_tensor)[2]
ivec = rep_tensor.shape[2]
with tf.variable_scope(scope or 'multi_dimensional_attention'):
map1 = bn_dense_layer(rep_tensor, ivec, True, 0., 'bn_dense_map1', activation,
False, wd, keep_prob, is_train)
map2 = bn_dense_layer(map1, ivec, True, 0., 'bn_dense_map2', 'linear',
False, wd, keep_prob, is_train)
# map2_masked = exp_mask_for_high_rank(map2, rep_mask)
soft = tf.nn.softmax(map2, 1)  # bs,sl,vec
attn_output = tf.reduce_sum(soft * rep_tensor, 1)  # bs, vec
# save attn
if tensor_dict is not None and name is not None:
tensor_dict[name] = soft
return attn_output

您可以将pytorch张量转换为numpy数组,并将其转换为tensorflow张量,反之亦然:

import torch
import tensorflow as tf
pytorch_tensor = torch.zeros(10)
np_tensor = pytorch_tensor.numpy()
tf_tensor = tf.convert_to_tensor(np_tensor)

话虽如此,如果你想训练一个使用pytorch和tensorflow组合的模型,那将是……尴尬、缓慢、有缺陷的,至少需要很长时间才能写作。因为图书馆必须弄清楚如何反向宣传成本。

因此,除非你的pytorch注意力块是经过预训练的,否则我建议你只坚持使用一个或另一个库,有很多例子可以在其中一个库中实现你想要的任何东西,也有很多预训练的模型可以同时实现这两个库。Tensorflow通常会快一点,但速度差异并没有那么大,我上面介绍的那种"破解"可能会让整个过程比单独使用任何一个库都慢。

@George解决方案很好,但截至2023年4月,至少不需要转换为numpy的中间步骤(尽管我不确定它是否在转换过程中内部使用(。所以,这是一个简单的命令,比如:

import torch
import tensorflow as tf
pytorch_tensor = torch.zeros(10)
tf_tensor = tf.convert_to_tensor(pytorch_tensor)

至于尴尬、缓慢等评论,我见过像《尤洛夫5》这样的不朽作品在某个时候把这种组合搞混了。

最新更新