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.

index.cpp 2.1 kB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. /**
  2. * \file dnn/test/common/index.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 "test/common/index.h"
  12. #include "test/common/utils.h"
  13. namespace megdnn {
  14. namespace test {
  15. Index::Index(TensorLayout layout, size_t linear) : m_layout(layout), m_linear(linear) {
  16. linear_to_array();
  17. array_to_offset();
  18. }
  19. Index::Index(TensorLayout layout, TensorShape array)
  20. : m_layout(layout), m_array(array) {
  21. array_to_linear();
  22. array_to_offset();
  23. }
  24. void Index::linear_to_array() {
  25. auto linear = m_linear;
  26. auto& array = m_array;
  27. array.ndim = m_layout.ndim;
  28. for (size_t j = m_layout.ndim; j > 0; --j) {
  29. size_t i = j - 1;
  30. array[i] = linear % m_layout[i];
  31. linear /= m_layout[i];
  32. }
  33. megdnn_assert(linear == 0);
  34. }
  35. void Index::array_to_linear() {
  36. auto& linear = m_linear;
  37. megdnn_assert(m_array.ndim == m_layout.ndim);
  38. linear = 0;
  39. for (size_t i = 0; i < m_array.ndim; ++i) {
  40. megdnn_assert(m_array[i] < m_layout[i]);
  41. linear = linear * m_layout[i] + m_array[i];
  42. }
  43. }
  44. void Index::array_to_offset() {
  45. auto& offset = m_offset;
  46. megdnn_assert(m_array.ndim == m_layout.ndim);
  47. offset = 0;
  48. for (size_t i = 0; i < m_array.ndim; ++i) {
  49. megdnn_assert(m_array[i] < m_layout[i]);
  50. offset += m_array[i] * m_layout.stride[i];
  51. }
  52. }
  53. std::string Index::to_string() const {
  54. std::string res = "";
  55. res.append("{");
  56. res.append("array=");
  57. res.append(m_array.to_string());
  58. res.append(",linear=");
  59. res.append(std::to_string(m_linear));
  60. res.append(",offset=");
  61. res.append(std::to_string(m_offset));
  62. res.append("}");
  63. return res;
  64. }
  65. } // namespace test
  66. } // namespace megdnn
  67. // vim: syntax=cpp.doxygen