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 <set>
18 #include "ops/topk.h"
19 #include "ops/op_utils.h"
20 #include "utils/check_convert_utils.h"
21
22 namespace mindspore {
23 namespace ops {
Init(const bool sorted)24 void TopK::Init(const bool sorted) { this->set_sorted(sorted); }
set_sorted(const bool sorted)25 void TopK::set_sorted(const bool sorted) { (void)this->AddAttr(kSorted, MakeValue(sorted)); }
26
get_sorted() const27 bool TopK::get_sorted() const {
28 auto value_ptr = this->GetAttr(kSorted);
29 return GetValue<bool>(value_ptr);
30 }
TopKInfer(const abstract::AnalysisEnginePtr &,const PrimitivePtr & primitive,const std::vector<AbstractBasePtr> & input_args)31 AbstractBasePtr TopKInfer(const abstract::AnalysisEnginePtr &, const PrimitivePtr &primitive,
32 const std::vector<AbstractBasePtr> &input_args) {
33 MS_EXCEPTION_IF_NULL(primitive);
34 auto prim_name = primitive->name();
35 const int64_t input_num = 2;
36 (void)CheckAndConvertUtils::CheckInteger("top_k_infer", SizeToLong(input_args.size()), kEqual, input_num, prim_name);
37
38 // Infer dtype
39 for (const auto &item : input_args) {
40 MS_EXCEPTION_IF_NULL(item);
41 }
42 auto output1_type = kInt32;
43 const std::set<TypePtr> valid_types = {kFloat16, kFloat32};
44 auto output0_type =
45 CheckAndConvertUtils::CheckTensorTypeValid("input_x", input_args[0]->BuildType(), valid_types, prim_name);
46
47 // Infer shape
48 auto x_shape = CheckAndConvertUtils::ConvertShapePtrToShapeMap(input_args[0]->BuildShape())[kShape];
49 auto k_v = GetValue<int>(input_args[1]->BuildValue());
50 auto ndims = x_shape.size() - 1;
51 x_shape[ndims] = k_v;
52
53 auto output0 = std::make_shared<abstract::AbstractTensor>(output0_type, x_shape);
54 auto output1 = std::make_shared<abstract::AbstractTensor>(output1_type, x_shape);
55 AbstractBasePtrList output = {output0, output1};
56 return std::make_shared<abstract::AbstractTuple>(output);
57 }
58 REGISTER_PRIMITIVE_C(kNameTopK, TopK);
59 } // namespace ops
60 } // namespace mindspore
61