| 1 | // Tencent is pleased to support the open source community by making ncnn available. |
| 2 | // |
| 3 | // Copyright (C) 2023 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 | #include "fuse_layernorm.h" |
| 16 | |
| 17 | #include "pass_level2.h" |
| 18 | |
| 19 | #include <math.h> |
| 20 | #include <string.h> |
| 21 | |
| 22 | namespace pnnx { |
| 23 | |
| 24 | class fuse_layernorm_pass : public GraphRewriterPass |
| 25 | { |
| 26 | public: |
| 27 | const char* match_pattern_graph() const |
| 28 | { |
| 29 | return R"PNNXIR(7767517 |
| 30 | 8 7 |
| 31 | pnnx.Input input 0 1 input #input=(1,%c,?,?)f32 |
| 32 | pnnx.Attribute op_0 0 1 weight @data #weight=(%c,1,1)f32 |
| 33 | pnnx.Attribute op_1 0 1 bias @data #bias=(%c,1,1)f32 |
| 34 | torch.mean op_2 1 1 input mean dim=(1) keepdim=True |
| 35 | pnnx.Expression op_3 2 1 input mean 2 expr=pow(sub(@0,@1),2) |
| 36 | torch.mean op_4 1 1 2 var dim=(1) keepdim=True |
| 37 | pnnx.Expression op_5 5 1 weight input mean var bias out expr=add(mul(@0,div(sub(@1,@2),sqrt(add(@3,%eps)))),@4) |
| 38 | pnnx.Output output 1 0 out |
| 39 | )PNNXIR"; |
| 40 | } |
| 41 | |
| 42 | const char* replace_pattern_graph() const |
| 43 | { |
| 44 | return R"PNNXIR(7767517 |
| 45 | 5 4 |
| 46 | pnnx.Input input 0 1 input |
| 47 | Tensor.permute op_0 1 1 input a dims=(0,2,3,1) |
| 48 | nn.LayerNorm op_1 1 1 a b elementwise_affine=True eps=%eps normalized_shape=(%c) @weight=%op_0.data @bias=%op_1.data |
| 49 | Tensor.permute op_2 1 1 b out dims=(0,3,1,2) |
| 50 | pnnx.Output output 1 0 out |
| 51 | )PNNXIR"; |
| 52 | } |
| 53 | |
| 54 | void write(const std::map<std::string, Operator*>& ops, const std::map<std::string, Parameter>& captured_params, const std::map<std::string, Attribute>& captured_attrs) const |
| 55 | { |
| 56 | GraphRewriterPass::write(ops, captured_params, captured_attrs); |
| 57 | |
| 58 | // fix weight bias shape from (c,1,1) to (c) |
| 59 | const int c = captured_params.at("c").i; |
| 60 | Operator* op_1 = ops.at("op_1"); |
| 61 | op_1->attrs["weight"].shape = {c}; |
| 62 | op_1->attrs["bias"].shape = {c}; |
| 63 | } |
| 64 | }; |
| 65 | |
| 66 | void fuse_layernorm(Graph& graph) |
| 67 | { |
| 68 | fuse_layernorm_pass a; |
| 69 | int opindex = 0; |
| 70 | |
| 71 | pnnx_graph_rewrite(graph, &a, opindex); |
| 72 | } |
| 73 | |
| 74 | } // namespace pnnx |