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