【问题标题】:Why the computing efficiency of torch.tanh is much higher than the direct expression?为什么torch.tanh的计算效率比直接表达高很多?
【发布时间】:2022-11-13 12:07:07
【问题描述】:

计算“tanh”的两种方法如下所示。为什么torch.tanh(1)的计算效率远高于直接表达式(2)?我很困惑。我在哪里可以找到pytorch中torch.tanh的原始代码?它是由 C/C++ 编写的吗?

import torch
import time

def tanh(x):
    return (torch.exp(x) - torch.exp(-x)) / (torch.exp(x) + torch.exp(-x))

class Function(torch.nn.Module):
    def __init__(self):
        super(Function, self).__init__()
        self.Linear1 = torch.nn.Linear(3, 50)
        self.Linear2 = torch.nn.Linear(50, 50)
        self.Linear3 = torch.nn.Linear(50, 50)
        self.Linear4 = torch.nn.Linear(50, 1)
    def forward(self, x):
        # (1) for torch.torch
        x = torch.tanh(self.Linear1(x))
        x = torch.tanh(self.Linear2(x))
        x = torch.tanh(self.Linear3(x))
        x = torch.tanh(self.Linear4(x))

        # (2) for direct expression
        # x = tanh(self.Linear1(x))
        # x = tanh(self.Linear2(x))
        # x = tanh(self.Linear3(x))
        # x = tanh(self.Linear4(x))

        return x

func = Function()

x= torch.ones(1000,3)

T1 = time.time()
for i in range(10000):
    y = func(x)
T2 = time.time()
print(T2-T1)

【问题讨论】:

    标签: performance pytorch expression activation-function hyperbolic-function


    【解决方案1】:

    数学函数是用高度优化的代码编写的,它们可以使用高级 CPU 功能和多核,甚至可以利用 GPU。

    在您的 tanh 函数中,它会评估 exp 函数四次,执行 2 次减法和 1 次除法,创建临时张量需要的内存分配也可能很慢,更不用说 python 解释器的开销了,慢了 4 到 10 倍是合理的。

    【讨论】:

      猜你喜欢
      • 2019-06-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多