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.h 2.0 kB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. /**
  2. * \file dnn/test/common/index.h
  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. #pragma once
  12. #include "megdnn/basic_types.h"
  13. #include "test/common/rng.h"
  14. namespace megdnn {
  15. namespace test {
  16. /**
  17. * array: index in the array form
  18. * linear: a single index number by assuming contiguous layout
  19. * offset: the memory offset in nr elements (can be negative)
  20. *
  21. * dtype is ignored.
  22. */
  23. class Index {
  24. public:
  25. Index(TensorLayout layout, size_t linear);
  26. Index(TensorLayout layout, TensorShape array);
  27. std::string to_string() const;
  28. TensorShape array() const { return m_array; }
  29. TensorLayout layout() const { return m_layout; }
  30. size_t linear_index() const { return m_linear; }
  31. ptrdiff_t offset() const { return m_offset; }
  32. /**
  33. * Add a universal offset to all return values to make the minimal
  34. * offset zero.
  35. */
  36. size_t positive_offset() const { return m_offset - m_layout.span().low_elem; }
  37. private:
  38. TensorLayout m_layout;
  39. size_t m_linear;
  40. TensorShape m_array;
  41. ptrdiff_t m_offset;
  42. void linear_to_array();
  43. void array_to_linear();
  44. void array_to_offset();
  45. };
  46. class IndexRNG final : public RNG {
  47. size_t& m_size;
  48. std::mt19937_64 m_rng;
  49. public:
  50. IndexRNG(size_t& sz, size_t seed) : m_size{sz}, m_rng(seed) {}
  51. void gen(const TensorND& tensor) override {
  52. std::uniform_int_distribution<int> dist(-static_cast<int>(m_size), m_size - 1);
  53. auto ptr = tensor.ptr<int>() + tensor.layout.span().low_elem;
  54. for (size_t i = 0; i < tensor.layout.span().dist_elem(); ++i)
  55. ptr[i] = dist(m_rng);
  56. }
  57. };
  58. } // namespace test
  59. } // namespace megdnn
  60. // vim: syntax=cpp.doxygen