You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

topk.cc 2.2 kB

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