| 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.w3 = nn.Parameter(torch.rand(24)) |
| 25 | self.w4 = nn.Parameter(torch.rand(12, 16)) |
| 26 | self.w5 = nn.Parameter(torch.rand(24)) |
| 27 | |
| 28 | def forward(self, x, y, z, w0, w1, w2): |
| 29 | x = F.rms_norm(x, (24,), w0) |
| 30 | x = F.rms_norm(x, (12,24), None) |
| 31 | x = F.rms_norm(x, (24,), self.w3) |
| 32 | |
| 33 | y = F.rms_norm(y, (16,), None, eps=1e-3) |
| 34 | y = F.rms_norm(y, (12,16), w1) |
| 35 | y = F.rms_norm(y, (12,16), self.w4) |
| 36 | |
| 37 | z = F.rms_norm(z, (24,), w2) |
| 38 | z = F.rms_norm(z, (12,16,24), None, eps=1e-2) |
| 39 | z = F.rms_norm(z, (24,), self.w5) |
| 40 | return x, y, z |
| 41 | |
| 42 | def test(): |
| 43 | if version.parse(torch.__version__) < version.parse('2.4'): |
| 44 | return True |
| 45 | |
| 46 | net = Model() |
| 47 | net.eval() |
| 48 | |
| 49 | torch.manual_seed(0) |
| 50 | x = torch.rand(1, 12, 24) |
| 51 | y = torch.rand(2, 3, 12, 16) |
| 52 | z = torch.rand(1, 10, 12, 16, 24) |
| 53 | w0 = torch.rand(24) |
| 54 | w1 = torch.rand(12, 16) |
| 55 | w2 = torch.rand(24) |
| 56 | |
| 57 | a0, a1, a2 = net(x, y, z, w0, w1, w2) |
| 58 | |
| 59 | # export torchscript |
| 60 | mod = torch.jit.trace(net, (x, y, z, w0, w1, w2)) |
| 61 | mod.save("test_F_rms_norm.pt") |
| 62 | |
| 63 | # torchscript to pnnx |
| 64 | import os |
| 65 | os.system("../src/pnnx test_F_rms_norm.pt inputshape=[1,12,24],[2,3,12,16],[1,10,12,16,24],[24],[12,16],[24]") |
| 66 | |
| 67 | # pnnx inference |
| 68 | import test_F_rms_norm_pnnx |
| 69 | b0, b1, b2 = test_F_rms_norm_pnnx.test_inference() |
| 70 | |
| 71 | return torch.equal(a0, b0) and torch.equal(a1, b1) and torch.equal(a2, b2) |
| 72 | |
| 73 | if __name__ == "__main__": |
| 74 | if test(): |
| 75 | exit(0) |
| 76 | else: |
| 77 | exit(1) |