1 /**
2 * Copyright 2019-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 #include <string>
17
18 #include "pipeline/jit/remove_value_node_dup.h"
19 #include "ir/anf.h"
20 #include "ir/func_graph.h"
21 #include "ir/tensor.h"
22 #include "ir/manager.h"
23 #include "frontend/optimizer/cse.h"
24 #include "utils/log_adapter.h"
25 #include "utils/hashing.h"
26 #include "utils/convert_utils.h"
27
28 namespace mindspore {
29 namespace pipeline {
TryToDoReplace(FuncGraphManager * const manager,const AnfNodePtr & node,HashCache * const hash_cache,HashValue * const hash_value)30 void TryToDoReplace(FuncGraphManager *const manager, const AnfNodePtr &node, HashCache *const hash_cache,
31 HashValue *const hash_value) {
32 MS_EXCEPTION_IF_NULL(manager);
33 MS_EXCEPTION_IF_NULL(hash_cache);
34 const auto &to_check_value = GetValueNode(node);
35 MS_EXCEPTION_IF_NULL(to_check_value);
36
37 // Calculate hash value.
38 size_t h;
39 auto hash_iter = hash_value->find(node);
40 if (hash_iter == hash_value->end()) {
41 h = hash_combine(to_check_value->hash(), (opt::AbsOf(node)->hash()));
42 (*hash_value)[node] = h;
43 } else {
44 h = hash_iter->second;
45 }
46
47 auto bucket_iter = hash_cache->find(h);
48 if (bucket_iter == hash_cache->end()) {
49 // Meet for the first time, add bucket.
50 (*hash_cache)[h] = {node};
51 return;
52 }
53
54 auto &bucket = bucket_iter->second;
55 // Check if need to replace node with value node already met.
56 for (const auto &v : bucket) {
57 // Already met and cached.
58 if (v == node) {
59 return;
60 }
61 const auto &existed_value = GetValueNode(v);
62 MS_EXCEPTION_IF_NULL(existed_value);
63 auto equal = [&]() -> bool {
64 if (existed_value->isa<tensor::Tensor>() && to_check_value->isa<tensor::Tensor>()) {
65 return existed_value->cast<tensor::TensorPtr>()->ValueEqual(*(to_check_value->cast<tensor::TensorPtr>()));
66 }
67 return *existed_value == *to_check_value;
68 };
69 if (equal()) {
70 (void)manager->Replace(node, v);
71 return;
72 }
73 }
74
75 // Meet for the first time, append node to bucket.
76 bucket.emplace_back(node);
77 }
78 } // namespace pipeline
79 } // namespace mindspore
80