简体   繁体   English

在 Tensorflow 2.0 中使用 Numpy 操作会影响其性能吗?

[英]Does using Numpy operations in Tensorflow 2.0 impact its performance?

I am studying the transformer code here as an example.我正在研究这里的转换器代码作为示例。

The positional encoding function below uses numpy for all of its operations.下面的位置编码函数使用 numpy 进行所有操作。 Then it casts them back to TF tensor when returning the result.然后在返回结果时将它们转换回 TF 张量。 Does such a pattern impact the performance when running the code especially when I run it on an GPU?在运行代码时,尤其是在 GPU 上运行时,这种模式会影响性能吗? Is that recommended to use only TF operations when implementing a model?是否建议在实现模型时仅使用 TF 操作?

def get_positional_encoding(self, max_len):
    """PE_(pos, 2i) = sin(pos/10000^(2i/d_model))
    PE_(pos, 2i+1) = cos(pos/10000^(2i/d_model))
    """

    pos = np.expand_dims(np.arange(0, max_len), axis=1)
    div_term = np.array([[1 / np.power(10000, (2 * (i//2) / self.d_model)) for i in range(self.d_model)]])       

    pos = pos * div_term

    pe = np.zeros((max_len, self.d_model))
    pe[:, 0:self.d_model//2] = np.sin(pos[:, 0::2])
    pe[:, self.d_model//2:] = np.cos(pos[:, 0::2])

    pe = np.expand_dims(pe, 0)

    print(pe.shape)

    return tf.cast(pe, dtype=tf.float32) 

Yes , it does impact the performance generally this is assuming that you can properly execute the code without any errors.是的,它确实会影响性能,前提是您可以正确执行代码而不会出现任何错误。

One factor is the time required passing/copying the values from CPU to GPU , which adds a lot of overhead time , the larger the matrices.一个因素是将值从 CPU 传递/复制到 GPU 所需时间,这会增加大量开销时间,矩阵越大。

Tensorflow is built to run in the GPU , so when you are using all Tensorflow operations in every part of your code, you will see a drastic improvement in performance just because of the time required in passing values from CPU to GPU , this is not considering the optimizations applied when using Tensors for computations. Tensorflow是为在GPU 中运行而构建的,因此当您在代码的每个部分使用所有 Tensorflow 操作时,您将看到性能的显提高,因为将值从 CPU 传递到 GPU所需的时间,这是不考虑的使用张量进行计算时应用的优化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM