1 /**
2 * Copyright 2020 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 "src/runtime/kernel/arm/int8/topk_int8.h"
18 #include "src/kernel_registry.h"
19 #include "include/errorcode.h"
20
21 using mindspore::lite::KernelRegistrar;
22 using mindspore::lite::RET_ERROR;
23 using mindspore::lite::RET_OK;
24 using mindspore::schema::PrimitiveType_TopKFusion;
25
26 namespace mindspore::kernel {
Init()27 int TopKInt8CPUKernel::Init() {
28 CHECK_LESS_RETURN(in_tensors_.size(), 1);
29 CHECK_LESS_RETURN(out_tensors_.size(), 1);
30 if (!InferShapeDone()) {
31 return RET_OK;
32 }
33 return ReSize();
34 }
35
ReSize()36 int TopKInt8CPUKernel::ReSize() {
37 TopkParameter *parameter = reinterpret_cast<TopkParameter *>(op_parameter_);
38 CHECK_NULL_RETURN(parameter);
39 lite::Tensor *input = in_tensors_.at(0);
40 parameter->last_dim_size_ = input->shape().at(input->shape().size() - 1);
41 parameter->loop_num_ = 1;
42 for (size_t i = 0; i < input->shape().size() - 1; ++i) {
43 parameter->loop_num_ *= input->shape().at(i);
44 }
45 return RET_OK;
46 }
47
Run()48 int TopKInt8CPUKernel::Run() {
49 int8_t *input_data = reinterpret_cast<int8_t *>(in_tensors_.at(0)->data());
50 CHECK_NULL_RETURN(input_data);
51 int8_t *output_data = reinterpret_cast<int8_t *>(out_tensors_.at(0)->data());
52 CHECK_NULL_RETURN(output_data);
53 int32_t *output_index = reinterpret_cast<int32_t *>(out_tensors_.at(1)->data());
54 CHECK_NULL_RETURN(output_index);
55
56 MS_ASSERT(ms_context_->allocator != nullptr);
57 TopkParameter *parameter = reinterpret_cast<TopkParameter *>(op_parameter_);
58 parameter->topk_node_list_ = ms_context_->allocator->Malloc(sizeof(TopkNodeInt8) * parameter->last_dim_size_);
59 if (parameter->topk_node_list_ == nullptr) {
60 MS_LOG(ERROR) << "Memory allocation failed";
61 return RET_ERROR;
62 }
63 TopkInt8(input_data, output_data, output_index, reinterpret_cast<TopkParameter *>(op_parameter_));
64 ms_context_->allocator->Free(parameter->topk_node_list_);
65 return RET_OK;
66 }
67
68 REG_KERNEL(kCPU, kNumberTypeInt8, PrimitiveType_TopKFusion, LiteKernelCreator<TopKInt8CPUKernel>)
69 } // namespace mindspore::kernel
70