1 /**
2 * Copyright 2021 Huawei Technologies Co., Ltd
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include "nnacl/infer/layer_norm_infer.h"
18 #include "nnacl/infer/infer_register.h"
19
LayerNormInferShape(const TensorC * const * inputs,size_t inputs_size,TensorC ** outputs,size_t outputs_size,OpParameter * parameter)20 int LayerNormInferShape(const TensorC *const *inputs, size_t inputs_size, TensorC **outputs, size_t outputs_size,
21 OpParameter *parameter) {
22 if ((inputs_size != 1 && inputs_size != 3) || (outputs_size != 1 && outputs_size != 3)) {
23 return NNACL_INPUT_TENSOR_ERROR;
24 }
25 int check_ret = CheckAugmentNull(inputs, inputs_size, outputs, outputs_size, parameter);
26 if (check_ret != NNACL_OK) {
27 return check_ret;
28 }
29
30 const TensorC *input = inputs[0];
31 TensorC *output = outputs[0];
32 SetDataTypeFormat(output, input);
33 if (!InferFlag(inputs, inputs_size)) {
34 return NNACL_INFER_INVALID;
35 }
36
37 LayerNormParameter *param = (LayerNormParameter *)parameter;
38 NNACL_CHECK_NULL_RETURN_ERR(param);
39 if (input->shape_size_ > COMM_SHAPE_SIZE) {
40 return NNACL_INPUT_TENSOR_ERROR;
41 }
42 if (param->begin_params_axis_ < (-1 * (int)(input->shape_size_)) ||
43 param->begin_params_axis_ >= (int)(input->shape_size_)) {
44 return NNACL_PARAM_INVALID;
45 }
46 param->begin_norm_axis_ =
47 param->begin_norm_axis_ < 0 ? param->begin_norm_axis_ + ((int)(input->shape_size_)) : param->begin_norm_axis_;
48 SetShapeTensor(output, input);
49 // take care of other outputs
50 if (outputs_size == 3) {
51 TensorC *output_mean = outputs[1];
52 TensorC *output_var = outputs[2];
53 SetDataTypeFormat(output_mean, input);
54 SetDataTypeFormat(output_var, input);
55 int size = 0;
56 NNACL_CHECK_TRUE_RET(param->begin_norm_axis_ <= MAX_SHAPE_SIZE, NNACL_ERR);
57 for (; size < param->begin_norm_axis_; size++) {
58 output_mean->shape_[size] = input->shape_[size];
59 output_var->shape_[size] = input->shape_[size];
60 }
61 output_mean->shape_size_ = (size_t)size;
62 output_var->shape_size_ = (size_t)size;
63 }
64
65 return NNACL_OK;
66 }
67
68 REG_INFER(LayerNormFusion, PrimType_LayerNormFusion, LayerNormInferShape)
69