計算“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)
uj5u.com熱心網友回復:
數學函式是用高度優化的代碼撰寫的,它們可以使用高級 CPU 功能和多核,甚至可以利用 GPU。
在您的 tanh 函式中,它對函式進行四次評估exp,進行 2 次減法和 1 次除法,創建臨時張量需要的記憶體分配也可能很慢,更不用說 python 解釋器的開銷,慢 4 到 10 倍是合理的。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/533223.html
下一篇:減少函式的時間(Python)
