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.

algorithm_cache.h 2.4 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. /**
  2. * \file dnn/include/megdnn/heuristic_cache.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
  10. * implied.
  11. */
  12. #pragma once
  13. #include "megdnn/basic_types.h"
  14. #include "megdnn/oprs/base.h"
  15. #include <mutex>
  16. #include <string>
  17. #include <unordered_map>
  18. namespace megdnn {
  19. class AlgorithmCache {
  20. private:
  21. AlgorithmCache() = default;
  22. public:
  23. MGE_WIN_DECLSPEC_FUC static AlgorithmCache& instance();
  24. struct KeyStorage {
  25. size_t k1, k2;
  26. bool operator==(const KeyStorage& k) const { return k1 == k.k1 && k2 == k.k2; }
  27. };
  28. struct Key {
  29. Handle* m_handle;
  30. uint32_t m_opr_type;
  31. const TensorLayout* m_inp_layouts_ptr;
  32. size_t m_inp_layouts_size;
  33. const void* m_param_ptr;
  34. size_t m_param_size;
  35. mutable SmallVector<size_t> m_buf;
  36. public:
  37. Key(Handle* opr_handle, Algorithm::OprType opr_type,
  38. const TensorLayout* inp_layouts_ptr, size_t inp_layouts_size,
  39. const void* param_ptr = nullptr, size_t param_size = 0)
  40. : m_handle{opr_handle},
  41. m_opr_type{static_cast<uint32_t>(opr_type)},
  42. m_inp_layouts_ptr{inp_layouts_ptr},
  43. m_inp_layouts_size{inp_layouts_size},
  44. m_param_ptr{param_ptr},
  45. m_param_size{param_size} {}
  46. KeyStorage build_key_storage() const;
  47. };
  48. struct Result {
  49. ExecutionPolicy policy;
  50. size_t workspace;
  51. // for cache collision
  52. SmallVector<size_t> m_buf;
  53. SmallVector<char> m_param_buf;
  54. };
  55. MGE_WIN_DECLSPEC_FUC void put(const Key& key, Result& result);
  56. MGE_WIN_DECLSPEC_FUC Result get(const Key& key);
  57. void clear();
  58. private:
  59. struct Hash {
  60. size_t operator()(const KeyStorage& k) const {
  61. size_t h1 = k.k1;
  62. size_t h2 = k.k2;
  63. h1 ^= h2 + 0x9e3779b9 + (h1 << 6) + (h1 >> 2);
  64. return h1;
  65. }
  66. };
  67. std::unordered_map<KeyStorage, Result, Hash> m_heuristic_cache;
  68. #if __DEPLOY_ON_XP_SP2__
  69. size_t m_mtx;
  70. #else
  71. std::mutex m_mtx;
  72. #endif
  73. };
  74. } // namespace megdnn