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.cpp 2.4 kB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. /**
  2. * \file dnn/src/common/topk.cpp
  3. * MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
  4. *
  5. * Copyright (c) 2014-2021 Megvii Inc. All rights reserved.
  6. *
  7. * Unless required by applicable law or agreed to in writing,
  8. * software distributed under the License is distributed on an
  9. * "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. */
  11. #include "megdnn/oprs/general.h"
  12. #include "src/common/utils.h"
  13. #include <cmath>
  14. using namespace megdnn;
  15. void TopK::deduce_layout(int k, const TensorLayout& data, TensorLayout& values,
  16. TensorLayout& indices) {
  17. megdnn_assert(k && data.ndim == 2 && data.stride[1] == 1,
  18. "invalid k=%d data=%s", k, data.to_string().c_str());
  19. values.dtype = data.dtype;
  20. indices.dtype = dtype::Int32{};
  21. switch (param().mode) {
  22. case Param::Mode::KTH_ONLY:
  23. values.init_contiguous_stride({data[0]});
  24. indices.ndim = 0;
  25. break;
  26. case Param::Mode::VALUE_IDX_NOSORT:
  27. case Param::Mode::VALUE_IDX_SORTED:
  28. values.init_contiguous_stride(
  29. {data[0], std::min<size_t>(std::abs(k), data.shape[1])});
  30. indices.init_contiguous_stride(values);
  31. break;
  32. default:
  33. megdnn_throw("invalid TopK mode");
  34. }
  35. }
  36. void TopK::exec(int k, _megdnn_tensor_in data, _megdnn_tensor_out values,
  37. _megdnn_tensor_out indices, _megdnn_workspace workspace) {
  38. TensorLayout oval, oidx;
  39. deduce_layout(k, data.layout, oval, oidx);
  40. megdnn_assert_eq_layout(oval, values.layout);
  41. int32_t* iptr = nullptr;
  42. if (param().mode == Param::Mode::KTH_ONLY) {
  43. megdnn_assert_eq_shape(indices.layout, TensorShape{});
  44. } else {
  45. iptr = indices.ptr<int32_t>();
  46. megdnn_assert_eq_layout(oidx, indices.layout);
  47. }
  48. megdnn_assert(workspace.size >= get_workspace_in_bytes(k, data.layout,
  49. values.layout,
  50. indices.layout));
  51. if (static_cast<size_t>(std::abs(k)) > data.layout[1]) {
  52. if (k > 0) {
  53. k = data.layout[1];
  54. } else {
  55. k = -static_cast<int>(data.layout[1]);
  56. }
  57. }
  58. do_exec(k, data, values, iptr, workspace);
  59. }
  60. // vim: syntax=cpp.doxygen

MegEngine 安装包中集成了使用 GPU 运行代码所需的 CUDA 环境,不用区分 CPU 和 GPU 版。 如果想要运行 GPU 程序,请确保机器本身配有 GPU 硬件设备并安装好驱动。 如果你想体验在云端 GPU 算力平台进行深度学习开发的感觉,欢迎访问 MegStudio 平台