1 /**
2 * Copyright 2021 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 #ifndef MINDSPORE_CCSRC_DEBUG_RDR_RECORDER_MANAGER_H_
17 #define MINDSPORE_CCSRC_DEBUG_RDR_RECORDER_MANAGER_H_
18 #include <vector>
19 #include <string>
20 #include <sstream>
21 #include <map>
22 #include <unordered_map>
23 #include <memory>
24 #include <mutex>
25 #include <utility>
26
27 namespace mindspore {
28 // The number is the reciprocal of the golden ratio.
29 const unsigned int MAGIC_CONSTANT = 0x9e3779b9;
30 const unsigned int HASH_SHIFT_LEFT = 6;
31 const unsigned int HASH_SHIFT_RIGHT = 2;
32
33 template <typename T>
hash_combine(std::size_t * seed,const T & val)34 inline void hash_combine(std::size_t *seed, const T &val) {
35 *seed ^= std::hash<T>()(val) + MAGIC_CONSTANT + (*seed << HASH_SHIFT_LEFT) + (*seed >> HASH_SHIFT_RIGHT);
36 }
37
38 template <typename T1, typename T2>
hash_seed(const T1 & val1,const T2 & val2)39 inline std::size_t hash_seed(const T1 &val1, const T2 &val2) {
40 std::size_t seed = 0;
41 hash_combine(&seed, val1);
42 hash_combine(&seed, val2);
43 return seed;
44 }
45
46 struct pair_hash {
47 template <class T1, class T2>
operatorpair_hash48 std::size_t operator()(const std::pair<T1, T2> &p) const {
49 return hash_seed(p.first, p.second);
50 }
51 };
52
53 class BaseRecorder;
54 using BaseRecorderPtr = std::shared_ptr<BaseRecorder>;
55 class RecorderManager {
56 public:
Instance()57 static RecorderManager &Instance() {
58 static RecorderManager manager;
59 manager.UpdateRdrEnable();
60 return manager;
61 }
62
63 void UpdateRdrEnable();
64 bool RdrEnable() const;
65 bool CheckRdrMemIsRecord() const;
66 void SetRdrMemIsRecord(bool is_enable = true);
67
68 bool RecordObject(const BaseRecorderPtr &recorder);
69 BaseRecorderPtr GetRecorder(std::string module, std::string name);
70 void TriggerAll();
71 void ClearAll();
72
73 private:
RecorderManager()74 RecorderManager() {}
~RecorderManager()75 ~RecorderManager() {}
76
77 bool rdr_enable_{false};
78 bool rdr_has_record_mem_{false};
79
80 mutable std::mutex mtx_;
81 // <module, name>, BaserRecorderPtr
82 std::unordered_map<std::pair<std::string, std::string>, BaseRecorderPtr, pair_hash> recorder_container_;
83 };
84 } // namespace mindspore
85 #endif // MINDSPORE_CCSRC_DEBUG_RDR_RECORDER_MANAGER_H_
86