• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /**
2  * Copyright 2023 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/kernel/non_zero.h"
18 #include "nnacl/kernel/default_kernel_base.h"
19 #include "nnacl/tensor_c_utils.h"
20 
NonZeroCompute(KernelBase * self)21 int NonZeroCompute(KernelBase *self) {
22   TensorC *input = self->in_[FIRST_INPUT];
23   NNACL_CHECK_NULL_RETURN_ERR(input);
24   TensorC *output = self->out_[OUTPUT_INDEX];
25   NNACL_CHECK_NULL_RETURN_ERR(output);
26 
27   NNACL_CHECK_FALSE(input->shape_size_ != DIMENSION_2D, NNACL_NON_ZERO_SHAPE_INVALID);
28 
29   bool *input_data = (bool *)input->data_;
30   NNACL_CHECK_NULL_RETURN_ERR(input_data);
31   int *output_data = (int *)output->data_;
32   NNACL_CHECK_NULL_RETURN_ERR(output_data);
33 
34   int non_zero_nums = output->shape_[Index1];
35   int non_zero_count = 0;
36 
37   int *coordiate_values = (int *)self->env_->Alloc(self->env_->allocator_, input->shape_size_ * sizeof(int));
38   NNACL_MALLOC_CHECK_NULL_RETURN_ERR(coordiate_values);
39 
40   for (int i = 0; i < GetElementNum(input); i += 1) {
41     if (input_data[i]) {
42       for (size_t j = 0; j < input->shape_size_; j++) {
43         output_data[non_zero_count + (int)j * non_zero_nums] = coordiate_values[j];
44       }
45       non_zero_count++;
46     }
47     for (size_t idx = input->shape_size_; idx >= 1; --idx) {
48       if (coordiate_values[idx - 1] != input->shape_[idx - 1] - 1) {
49         coordiate_values[idx - 1] = coordiate_values[idx - 1] + 1;
50         break;
51       }
52       coordiate_values[idx - 1] = 0;
53     }
54   }
55 
56   return NNACL_OK;
57 }
58 
CreateNonZero(OpParameter * param,int data_type)59 KernelBase *CreateNonZero(OpParameter *param, int data_type) {
60   NonZeroStruct *non_zero = (NonZeroStruct *)malloc(sizeof(NonZeroStruct));
61   NNACL_CHECK_NULL_RETURN_NULL(non_zero);
62   non_zero->base_.Release = DefaultRelease;
63   non_zero->base_.Prepare = DefaultPrepare2In1Out;
64   non_zero->base_.Resize = DefaultResize;
65   non_zero->base_.Compute = NonZeroCompute;
66   return (KernelBase *)non_zero;
67 }
68 
69 REG_KERNEL_CREATOR(PrimType_NonZero, kNumberTypeBool, CreateNonZero)
70