| 1 | # Tencent is pleased to support the open source community by making ncnn available. |
| 2 | # |
| 3 | # Copyright (C) 2024 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 | |
| 15 | import torch |
| 16 | import torch.nn as nn |
| 17 | import torch.nn.functional as F |
| 18 | from packaging import version |
| 19 | |
| 20 | class Model(nn.Module): |
| 21 | def __init__(self): |
| 22 | super(Model, self).__init__() |
| 23 | |
| 24 | self.rmsn_0 = nn.RMSNorm(64) |
| 25 | self.rmsn_0.weight = nn.Parameter(torch.rand(64)) |
| 26 | self.rmsn_1 = nn.RMSNorm(normalized_shape=(24,64), eps=1e-2, elementwise_affine=False) |
| 27 | |
| 28 | def forward(self, x, y, z): |
| 29 | x = self.rmsn_0(x) |
| 30 | x = self.rmsn_1(x) |
| 31 | |
| 32 | y = self.rmsn_0(y) |
| 33 | y = self.rmsn_1(y) |
| 34 | |
| 35 | z = self.rmsn_0(z) |
| 36 | z = self.rmsn_1(z) |
| 37 | return x, y, z |
| 38 | |
| 39 | def test(): |
| 40 | if version.parse(torch.__version__) < version.parse('2.4'): |
| 41 | return True |
| 42 | |
| 43 | net = Model() |
| 44 | net.eval() |
| 45 | |
| 46 | torch.manual_seed(0) |
| 47 | x = torch.rand(1, 24, 64) |
| 48 | y = torch.rand(1, 12, 24, 64) |
| 49 | z = torch.rand(1, 12, 16, 24, 64) |
| 50 | |
| 51 | a0, a1, a2 = net(x, y, z) |
| 52 | |
| 53 | # export torchscript |
| 54 | mod = torch.jit.trace(net, (x, y, z)) |
| 55 | mod.save("test_nn_RMSNorm.pt") |
| 56 | |
| 57 | # torchscript to pnnx |
| 58 | import os |
| 59 | os.system("../src/pnnx test_nn_RMSNorm.pt inputshape=[1,24,64],[1,12,24,64],[1,12,16,24,64]") |
| 60 | |
| 61 | # pnnx inference |
| 62 | import test_nn_RMSNorm_pnnx |
| 63 | b0, b1, b2 = test_nn_RMSNorm_pnnx.test_inference() |
| 64 | |
| 65 | return torch.equal(a0, b0) and torch.equal(a1, b1) and torch.equal(a2, b2) |
| 66 | |
| 67 | if __name__ == "__main__": |
| 68 | if test(): |
| 69 | exit(0) |
| 70 | else: |
| 71 | exit(1) |