Elffuss BraidHub

kikocis/ncnn public

master · 2.0 KiBRawPermalink
1# Tencent is pleased to support the open source community by making ncnn available.
2#
3# Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved.
4#
5# Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
6# in compliance with the License. You may obtain a copy of the License at
7#
8# https://opensource.org/licenses/BSD-3-Clause
9#
10# Unless required by applicable law or agreed to in writing, software distributed
11# under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
12# CONDITIONS OF ANY KIND, either express or implied. See the License for the
13# specific language governing permissions and limitations under the License.
14
15import torch
16import torch.nn as nn
17import torch.nn.functional as F
18import math
19
20def gelu_forward_0(x):
21 return x * 0.5 * (1.0 + torch.erf(x / math.sqrt(2.0)))
22
23def gelu_forward_1(x):
24 return 0.5 * x * (1.0 + torch.tanh(math.sqrt(2.0 / math.pi) * (x + 0.044715 * torch.pow(x, 3.0))))
25
26class Model(nn.Module):
27 def __init__(self):
28 super(Model, self).__init__()
29
30 def forward(self, x, y, z, w):
31 x = x * 2 - 1
32 y = y * 2 - 1
33 z = z * 2 - 1
34 w = w * 2 - 1
35 x = F.gelu(x)
36 y = F.gelu(y)
37 z = gelu_forward_0(z)
38 w = gelu_forward_1(w)
39 return x, y, z, w
40
41def test():
42 net = Model()
43 net.eval()
44
45 torch.manual_seed(0)
46 x = torch.rand(1, 16)
47 y = torch.rand(12, 2, 16)
48 z = torch.rand(1, 3, 12, 16)
49 w = torch.rand(1, 5, 7, 9, 11)
50
51 a = net(x, y, z, w)
52
53 # export torchscript
54 mod = torch.jit.trace(net, (x, y, z, w))
55 mod.save("test_F_gelu.pt")
56
57 # torchscript to pnnx
58 import os
59 os.system("../src/pnnx test_F_gelu.pt inputshape=[1,16],[12,2,16],[1,3,12,16],[1,5,7,9,11]")
60
61 # pnnx inference
62 import test_F_gelu_pnnx
63 b = test_F_gelu_pnnx.test_inference()
64
65 for a0, b0 in zip(a, b):
66 if not torch.allclose(a0, b0, 1e-3, 1e-3):
67 return False
68 return True
69
70if __name__ == "__main__":
71 if test():
72 exit(0)
73 else:
74 exit(1)