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.

argmax_cpu_kernel.cc 2.4 kB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /**
  2. * Copyright 2019 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 "kernel/cpu/argmax_cpu_kernel.h"
  17. #include "device/cpu/cpu_device_address.h"
  18. namespace mindspore {
  19. namespace kernel {
  20. void ArgmaxCPUKernel::InitKernel(const CNodePtr &kernel_node) {
  21. MS_EXCEPTION_IF_NULL(kernel_node);
  22. std::vector<size_t> shape = AnfAlgo::GetInputDeviceShape(kernel_node, 0);
  23. if (shape.size() != 2) {
  24. MS_LOG(EXCEPTION) << "argmax kernel dims invalid " << shape.size();
  25. }
  26. batch_size_ = shape[0];
  27. class_num_ = shape[1];
  28. int axis = AnfAlgo::GetNodeAttr<int>(kernel_node, AXIS);
  29. if (axis != -1 && axis != 1) {
  30. MS_LOG(EXCEPTION) << "argmax kernel not support axis " << axis;
  31. }
  32. }
  33. bool ArgmaxCPUKernel::Launch(const std::vector<kernel::AddressPtr> &inputs,
  34. const std::vector<kernel::AddressPtr> & /*workspaces*/,
  35. const std::vector<kernel::AddressPtr> &outputs) {
  36. if (inputs.empty() || outputs.empty()) {
  37. MS_LOG(EXCEPTION) << "input or output empty!";
  38. }
  39. size_t batch_float_size = batch_size_ * sizeof(float);
  40. size_t batch_class_float_size = class_num_ * batch_float_size;
  41. if (inputs[0]->size != batch_class_float_size || outputs[0]->size != batch_float_size) {
  42. MS_LOG(EXCEPTION) << "invalid input or output data size!";
  43. }
  44. auto input = reinterpret_cast<float *>(inputs[0]->addr);
  45. auto output = reinterpret_cast<int *>(outputs[0]->addr);
  46. size_t row_start = 0;
  47. for (size_t i = 0; i < batch_size_; ++i) {
  48. size_t max_index = 0;
  49. float max_value = input[row_start];
  50. for (size_t j = 1; j < class_num_; ++j) {
  51. size_t index = row_start + j;
  52. if (input[index] > max_value) {
  53. max_value = input[index];
  54. max_index = j;
  55. }
  56. }
  57. output[i] = SizeToInt(max_index);
  58. row_start += class_num_;
  59. }
  60. return true;
  61. }
  62. } // namespace kernel
  63. } // namespace mindspore